Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/tests/test_object_server.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
test_object_server.py · 351.4 KB · 10206 lines
1import asyncio
2import base64
3import json
4import tarfile
5import urllib.parse
6from pathlib import Path
7
8import object_correlation
9import object_credentials
10import object_execution
11import object_events
12import object_file_changes
13import object_handlers
14import object_ids
15import object_logs
16import object_package_changes
17import object_packages
18import object_permission_audit
19import object_permission_store
20import object_record_changes
21import object_server
22import object_source_changes
23import object_state
24import object_versions
25
26TEST_ADMIN_TOKEN = "unit-test-only-admin-token"
27ANONYMOUS_IDENTITY = {
28 "user_id": None,
29 "account_id": None,
30 "roles": [],
31 "subscriptions": [],
32 "auth_method": "anonymous",
33}
34
35
36def write_source(path, content):
37 path.parent.mkdir(parents=True, exist_ok=True)
38 path.write_text(content)
39 return path
40
41
42def write_records(data_dir, collection, content):
43 path = data_dir / "collections" / collection / "records.tsv"
44 path.parent.mkdir(parents=True, exist_ok=True)
45 path.write_text(content)
46 return path
47
48
49def request(
50 path,
51 method="GET",
52 query_string="",
53 body=b"",
54 headers=None,
55 body_chunks=None,
56 client=None,
57):
58 status, headers, payload = raw_request(
59 path,
60 method=method,
61 query_string=query_string,
62 body=body,
63 headers=headers,
64 body_chunks=body_chunks,
65 client=client,
66 )
67 return status, headers, json.loads(payload.decode("utf-8"))
68
69
70def raw_request(
71 path,
72 method="GET",
73 query_string="",
74 body=b"",
75 headers=None,
76 body_chunks=None,
77 client=None,
78):
79 return asyncio.run(
80 asgi_request(
81 path,
82 method=method,
83 query_string=query_string,
84 body=body,
85 headers=headers,
86 body_chunks=body_chunks,
87 client=client,
88 )
89 )
90
91
92async def asgi_request(
93 path,
94 method="GET",
95 query_string="",
96 body=b"",
97 headers=None,
98 body_chunks=None,
99 client=None,
100):
101 messages = []
102 chunks = body_chunks if body_chunks is not None else [body]
103 chunk_index = 0
104
105 async def receive():
106 nonlocal chunk_index
107 if chunk_index < len(chunks):
108 chunk = chunks[chunk_index]
109 chunk_index += 1
110 return {
111 "type": "http.request",
112 "body": chunk,
113 "more_body": chunk_index < len(chunks),
114 }
115 return {"type": "http.disconnect"}
116
117 async def send(message):
118 messages.append(message)
119
120 scope_headers = [(b"accept", b"application/json")]
121 for name, value in headers or []:
122 if isinstance(name, str):
123 name = name.encode("latin-1")
124 if isinstance(value, str):
125 value = value.encode("latin-1")
126 scope_headers.append((name, value))
127
128 scope = {
129 "type": "http",
130 "method": method,
131 "path": path,
132 "query_string": query_string.encode("utf-8"),
133 "headers": scope_headers,
134 "client": client or ("127.0.0.1", 12345),
135 }
136 await object_server.app(scope, receive, send)
137
138 start = next(message for message in messages if message["type"] == "http.response.start")
139 body_parts = [
140 message.get("body", b"")
141 for message in messages
142 if message["type"] == "http.response.body"
143 ]
144 payload = b"".join(body_parts)
145 return start["status"], dict(start["headers"]), payload
146
147
148def enable_source_writes(monkeypatch, root, data_dir):
149 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
150 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
151 monkeypatch.setenv("DBBASIC_ENABLE_SOURCE_WRITES", "true")
152 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", TEST_ADMIN_TOKEN)
153
154
155def enable_file_writes(monkeypatch, root, data_dir):
156 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
157 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
158 monkeypatch.setenv("DBBASIC_ENABLE_FILE_WRITES", "true")
159 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", TEST_ADMIN_TOKEN)
160
161
162def auth_headers():
163 return [("authorization", f"Token {TEST_ADMIN_TOKEN}")]
164
165
166def session_headers(token):
167 return [("authorization", f"Bearer {token}")]
168
169
170def enable_admin_token(monkeypatch):
171 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", TEST_ADMIN_TOKEN)
172
173
174def save_permission_policy(data_dir, policy):
175 object_permission_store.replace_policy(policy, data_dir)
176
177
178def write_package(root, package_id, payload, files=()):
179 package_dir = root / package_id
180 package_dir.mkdir(parents=True)
181 (package_dir / object_packages.MANIFEST_FILE).write_text(json.dumps(payload))
182 for relative_path, content in files:
183 write_source(package_dir / relative_path, content)
184 return package_dir
185
186
187def claim_limit_slot(limiter, limit):
188 token = limiter.try_acquire(limit)
189 assert token is not None
190 return token
191
192
193def create_identity_session(payload):
194 status, _, created = request(
195 "/identity/sessions",
196 method="POST",
197 body=json.dumps(payload).encode(),
198 headers=auth_headers(),
199 )
200 assert status == 201
201 return created["token"], created["session"]
202
203
204def update_source(object_id, code, *, author="test-api", message="Update source"):
205 return request(
206 f"/objects/{object_id}",
207 method="PUT",
208 query_string="source=true",
209 body=json.dumps(
210 {
211 "code": code,
212 "author": author,
213 "message": message,
214 }
215 ).encode(),
216 headers=auth_headers(),
217 )
218
219
220def test_health_endpoint_returns_ok():
221 status, headers, payload = request("/health")
222
223 assert status == 200
224 assert headers[b"content-type"] == b"application/json; charset=utf-8"
225 correlation_id = headers[b"x-dbbasic-correlation-id"].decode("latin-1")
226 assert object_correlation.normalize_correlation_id(correlation_id) == correlation_id
227 assert payload == {"status": "ok"}
228
229
230def test_response_preserves_valid_correlation_header():
231 correlation_id = "123e4567-e89b-42d3-a456-426614174000"
232
233 status, headers, payload = request(
234 "/health",
235 headers=[("x-dbbasic-correlation-id", correlation_id)],
236 )
237
238 assert status == 200
239 assert payload == {"status": "ok"}
240 assert headers[b"x-dbbasic-correlation-id"].decode("latin-1") == correlation_id
241
242
243def test_response_replaces_invalid_correlation_header():
244 status, headers, payload = request(
245 "/health",
246 headers=[("x-dbbasic-correlation-id", "not-a-uuid")],
247 )
248
249 assert status == 200
250 assert payload == {"status": "ok"}
251 correlation_id = headers[b"x-dbbasic-correlation-id"].decode("latin-1")
252 assert correlation_id != "not-a-uuid"
253 assert object_correlation.normalize_correlation_id(correlation_id) == correlation_id
254
255
256def test_identity_endpoint_returns_anonymous_subject(monkeypatch):
257 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
258 monkeypatch.delenv("DBBASIC_PERMISSION_TRUST_HEADERS", raising=False)
259
260 status, _, payload = request("/identity")
261
262 assert status == 200
263 assert payload == {
264 "status": "ok",
265 "subject": {
266 "user_id": None,
267 "account_id": None,
268 "roles": [],
269 "subscriptions": [],
270 "authenticated": False,
271 },
272 "auth": {
273 "method": "anonymous",
274 "trusted_headers_enabled": False,
275 "trusted_headers_present": False,
276 },
277 "permissions": {
278 "enforcement_enabled": False,
279 "enforcement_requested": False,
280 "enforcement_blocked": False,
281 "audit_enabled": False,
282 },
283 }
284
285
286def test_identity_endpoint_reports_admin_token_subject(monkeypatch):
287 enable_admin_token(monkeypatch)
288
289 status, _, payload = request("/identity", headers=auth_headers())
290
291 assert status == 200
292 assert payload["subject"] == {
293 "user_id": "admin",
294 "account_id": None,
295 "roles": ["admin"],
296 "subscriptions": [],
297 "authenticated": True,
298 }
299 assert payload["auth"]["method"] == "admin_token"
300
301
302def test_identity_accounts_create_list_and_get(tmp_path, monkeypatch):
303 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
304 enable_admin_token(monkeypatch)
305
306 status, _, created = request(
307 "/identity/accounts",
308 method="POST",
309 body=json.dumps(
310 {
311 "account_id": "acme",
312 "name": "Acme Corp",
313 "subscriptions": ["pro"],
314 }
315 ).encode(),
316 headers=auth_headers(),
317 )
318
319 assert status == 201
320 assert created["status"] == "ok"
321 assert created["account"]["account_id"] == "acme"
322 assert created["account"]["subscriptions"] == ["pro"]
323
324 status, _, listed = request("/identity/accounts", headers=auth_headers())
325
326 assert status == 200
327 assert listed["accounts"] == [created["account"]]
328 assert listed["count"] == 1
329
330 status, _, fetched = request("/identity/accounts/acme", headers=auth_headers())
331
332 assert status == 200
333 assert fetched["account"] == created["account"]
334
335
336def test_identity_users_create_list_filter_and_get(tmp_path, monkeypatch):
337 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
338 enable_admin_token(monkeypatch)
339
340 request(
341 "/identity/accounts",
342 method="POST",
343 body=json.dumps({"account_id": "acme"}).encode(),
344 headers=auth_headers(),
345 )
346 status, _, created = request(
347 "/identity/users",
348 method="POST",
349 body=json.dumps(
350 {
351 "user_id": "u_7",
352 "account_id": "acme",
353 "email": "alice@example.com",
354 "roles": ["sales"],
355 }
356 ).encode(),
357 headers=auth_headers(),
358 )
359
360 assert status == 201
361 assert created["status"] == "ok"
362 assert created["user"]["user_id"] == "u_7"
363 assert created["user"]["account_id"] == "acme"
364 assert created["user"]["roles"] == ["sales"]
365
366 status, _, listed = request(
367 "/identity/users",
368 query_string="account_id=acme",
369 headers=auth_headers(),
370 )
371
372 assert status == 200
373 assert listed["users"] == [created["user"]]
374 assert listed["count"] == 1
375
376 status, _, fetched = request("/identity/users/u_7", headers=auth_headers())
377
378 assert status == 200
379 assert fetched["user"] == created["user"]
380
381
382def test_identity_user_password_set_replace_and_remove(tmp_path, monkeypatch):
383 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
384 enable_admin_token(monkeypatch)
385 request(
386 "/identity/users",
387 method="POST",
388 body=json.dumps({"user_id": "u_7", "email": "alice@example.com"}).encode(),
389 headers=auth_headers(),
390 )
391
392 set_status, _, set_payload = request(
393 "/identity/users/u_7/password",
394 method="POST",
395 body=json.dumps({"password": "correct horse battery"}).encode(),
396 headers=auth_headers(),
397 )
398 replace_status, _, replace_payload = request(
399 "/identity/users/u_7/password",
400 method="POST",
401 body=json.dumps({"password": "another good password"}).encode(),
402 headers=auth_headers(),
403 )
404 remove_status, _, remove_payload = request(
405 "/identity/users/u_7/password",
406 method="DELETE",
407 headers=auth_headers(),
408 )
409
410 assert set_status == 200
411 assert set_payload == {
412 "status": "ok",
413 "user_id": "u_7",
414 "operation": "created",
415 "updated_at": set_payload["updated_at"],
416 }
417 assert "password" not in json.dumps(set_payload)
418 assert replace_status == 200
419 assert replace_payload["operation"] == "replaced"
420 assert remove_status == 200
421 assert remove_payload == {"status": "ok", "user_id": "u_7", "removed": True}
422
423 assert object_credentials.verify_password("u_7", "correct horse battery", base_dir=tmp_path) is False
424
425
426def test_identity_user_password_rejects_unknown_user_and_bad_payloads(tmp_path, monkeypatch):
427 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
428 enable_admin_token(monkeypatch)
429 request(
430 "/identity/users",
431 method="POST",
432 body=json.dumps({"user_id": "u_7"}).encode(),
433 headers=auth_headers(),
434 )
435
436 missing_status, _, missing_payload = request(
437 "/identity/users/u_missing/password",
438 method="POST",
439 body=json.dumps({"password": "long enough password"}).encode(),
440 headers=auth_headers(),
441 )
442 short_status, _, short_payload = request(
443 "/identity/users/u_7/password",
444 method="POST",
445 body=json.dumps({"password": "short"}).encode(),
446 headers=auth_headers(),
447 )
448 get_status, _, get_payload = request(
449 "/identity/users/u_7/password",
450 headers=auth_headers(),
451 )
452 unauth_status, _, unauth_payload = request(
453 "/identity/users/u_7/password",
454 method="POST",
455 body=json.dumps({"password": "long enough password"}).encode(),
456 )
457
458 assert missing_status == 404
459 assert short_status == 400
460 assert "at least 8 characters" in short_payload["error"]
461 assert get_status == 405
462 assert unauth_status == 401
463 assert unauth_payload == {"status": "error", "error": "Unauthorized"}
464 assert not object_credentials.credentials_path(tmp_path).exists() or (
465 "long enough password" not in object_credentials.credentials_path(tmp_path).read_text()
466 )
467 assert missing_payload["status"] == "error"
468 assert get_payload == {"status": "error", "error": "Method not allowed"}
469
470
471def test_admin_identity_user_password_alias(tmp_path, monkeypatch):
472 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
473 enable_admin_token(monkeypatch)
474 request(
475 "/identity/users",
476 method="POST",
477 body=json.dumps({"user_id": "u_7"}).encode(),
478 headers=auth_headers(),
479 )
480
481 set_status, _, set_payload = request(
482 "/admin/identity/users/u_7/password",
483 method="POST",
484 body=json.dumps({"password": "long enough password"}).encode(),
485 headers=auth_headers(),
486 )
487 unauth_status, _, unauth_payload = request(
488 "/admin/identity/users/u_7/password",
489 method="POST",
490 body=json.dumps({"password": "long enough password"}).encode(),
491 )
492 remove_status, _, remove_payload = request(
493 "/admin/identity/users/u_7/password",
494 method="DELETE",
495 headers=auth_headers(),
496 )
497
498 assert set_status == 200
499 assert set_payload["operation"] == "created"
500 assert unauth_status == 401
501 assert unauth_payload == {"status": "error", "error": "Unauthorized"}
502 assert remove_status == 200
503 assert remove_payload["removed"] is True
504
505
506def test_identity_account_and_user_routes_are_admin_gated(tmp_path, monkeypatch):
507 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
508 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
509
510 status, _, account_payload = request("/identity/accounts")
511 status_user, _, user_payload = request("/identity/users")
512
513 assert status == 403
514 assert account_payload == {
515 "status": "error",
516 "error": "Identity accounts require DBBASIC_ADMIN_TOKEN.",
517 }
518 assert status_user == 403
519 assert user_payload == {
520 "status": "error",
521 "error": "Identity users require DBBASIC_ADMIN_TOKEN.",
522 }
523
524
525def test_identity_session_uses_registered_user_profile(tmp_path, monkeypatch):
526 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
527 enable_admin_token(monkeypatch)
528
529 request(
530 "/identity/accounts",
531 method="POST",
532 body=json.dumps(
533 {
534 "account_id": "acme",
535 "subscriptions": ["pro"],
536 }
537 ).encode(),
538 headers=auth_headers(),
539 )
540 request(
541 "/identity/users",
542 method="POST",
543 body=json.dumps(
544 {
545 "user_id": "u_7",
546 "account_id": "acme",
547 "roles": ["sales"],
548 "subscriptions": ["team"],
549 }
550 ).encode(),
551 headers=auth_headers(),
552 )
553
554 status, _, created = request(
555 "/identity/sessions",
556 method="POST",
557 body=json.dumps({"user_id": "u_7", "label": "scroll"}).encode(),
558 headers=auth_headers(),
559 )
560
561 assert status == 201
562 assert created["session"]["account_id"] == "acme"
563 assert created["session"]["roles"] == ["sales"]
564 assert created["session"]["subscriptions"] == ["team", "pro"]
565
566 status, _, identity = request(
567 "/identity",
568 headers=[("authorization", f"Bearer {created['token']}")],
569 )
570
571 assert status == 200
572 assert identity["subject"]["account_id"] == "acme"
573 assert identity["subject"]["roles"] == ["sales"]
574 assert identity["subject"]["subscriptions"] == ["team", "pro"]
575
576
577def test_identity_session_strict_known_user_mode(tmp_path, monkeypatch):
578 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
579 monkeypatch.setenv(object_server.REQUIRE_KNOWN_IDENTITY_USERS_ENV, "true")
580 enable_admin_token(monkeypatch)
581
582 status, _, payload = request(
583 "/identity/sessions",
584 method="POST",
585 body=json.dumps({"user_id": "missing"}).encode(),
586 headers=auth_headers(),
587 )
588
589 assert status == 404
590 assert payload == {"status": "error", "error": "User not found: missing"}
591
592
593def test_identity_session_create_and_use(tmp_path, monkeypatch):
594 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
595 enable_admin_token(monkeypatch)
596
597 status, _, created = request(
598 "/identity/sessions",
599 method="POST",
600 body=json.dumps(
601 {
602 "user_id": "7",
603 "account_id": "acme",
604 "roles": ["sales", "manager"],
605 "subscriptions": ["pro"],
606 "label": "scroll",
607 }
608 ).encode(),
609 headers=auth_headers(),
610 )
611
612 assert status == 201
613 assert created["status"] == "ok"
614 assert created["token"]
615 assert created["session"]["user_id"] == "7"
616 assert created["session"]["account_id"] == "acme"
617 assert created["session"]["roles"] == ["sales", "manager"]
618 assert "token_hash" not in created["session"]
619
620 status, _, identity = request(
621 "/identity",
622 headers=[("authorization", f"Bearer {created['token']}")],
623 )
624
625 assert status == 200
626 assert identity["auth"]["method"] == "session_token"
627 assert identity["subject"] == {
628 "user_id": "7",
629 "account_id": "acme",
630 "roles": ["sales", "manager"],
631 "subscriptions": ["pro"],
632 "authenticated": True,
633 }
634
635
636def test_identity_sessions_are_admin_gated(tmp_path, monkeypatch):
637 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
638 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
639
640 status, _, payload = request("/identity/sessions")
641
642 assert status == 403
643 assert payload == {
644 "status": "error",
645 "error": "Identity sessions require DBBASIC_ADMIN_TOKEN.",
646 }
647
648
649def test_identity_session_list_and_revoke(tmp_path, monkeypatch):
650 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
651 enable_admin_token(monkeypatch)
652 _, _, created = request(
653 "/identity/sessions",
654 method="POST",
655 body=json.dumps({"user_id": "7", "roles": ["sales"]}).encode(),
656 headers=auth_headers(),
657 )
658 session_id = created["session"]["session_id"]
659 token = created["token"]
660
661 status, _, listing = request("/identity/sessions", headers=auth_headers())
662
663 assert status == 200
664 assert listing["count"] == 1
665 assert listing["sessions"][0]["session_id"] == session_id
666 assert "token" not in listing["sessions"][0]
667
668 status, _, revoked = request(
669 f"/identity/sessions/{session_id}",
670 method="DELETE",
671 headers=auth_headers(),
672 )
673
674 assert status == 200
675 assert revoked["session"]["active"] is False
676 assert revoked["session"]["revoked_at"] is not None
677
678 status, _, identity = request("/identity", headers=[("authorization", f"Token {token}")])
679
680 assert status == 200
681 assert identity["auth"]["method"] == "anonymous"
682 assert identity["subject"]["authenticated"] is False
683
684
685def test_identity_current_session_returns_active_session_without_admin_token(
686 tmp_path,
687 monkeypatch,
688):
689 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
690 enable_admin_token(monkeypatch)
691 _, _, created = request(
692 "/identity/sessions",
693 method="POST",
694 body=json.dumps(
695 {
696 "user_id": "u_7",
697 "account_id": "acme",
698 "roles": ["sales"],
699 "subscriptions": ["pro"],
700 "label": "scroll",
701 }
702 ).encode(),
703 headers=auth_headers(),
704 )
705
706 status, _, payload = request(
707 "/identity/session",
708 headers=[("authorization", f"Bearer {created['token']}")],
709 )
710
711 assert status == 200
712 assert payload["status"] == "ok"
713 assert payload["session"]["session_id"] == created["session"]["session_id"]
714 assert payload["session"]["user_id"] == "u_7"
715 assert payload["session"]["account_id"] == "acme"
716 assert payload["session"]["roles"] == ["sales"]
717 assert payload["session"]["subscriptions"] == ["pro"]
718 assert payload["session"]["label"] == "scroll"
719 assert payload["session"]["active"] is True
720 assert "token" not in payload["session"]
721 assert "token_hash" not in payload["session"]
722
723
724def test_identity_current_session_rejects_missing_invalid_and_admin_tokens(
725 tmp_path,
726 monkeypatch,
727):
728 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
729 enable_admin_token(monkeypatch)
730
731 missing_status, _, missing_payload = request("/identity/session")
732 invalid_status, _, invalid_payload = request(
733 "/identity/session",
734 headers=[("authorization", "Token not-a-session-token")],
735 )
736 admin_status, _, admin_payload = request("/identity/session", headers=auth_headers())
737
738 assert missing_status == 401
739 assert invalid_status == 401
740 assert admin_status == 401
741 assert missing_payload == {"status": "error", "error": "Active session token required"}
742 assert invalid_payload == {"status": "error", "error": "Active session token required"}
743 assert admin_payload == {"status": "error", "error": "Active session token required"}
744
745
746def test_identity_current_session_can_revoke_itself(tmp_path, monkeypatch):
747 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
748 enable_admin_token(monkeypatch)
749 _, _, created = request(
750 "/identity/sessions",
751 method="POST",
752 body=json.dumps({"user_id": "u_7", "roles": ["sales"]}).encode(),
753 headers=auth_headers(),
754 )
755 token_headers = [("authorization", f"Token {created['token']}")]
756
757 status, _, payload = request("/identity/session", method="DELETE", headers=token_headers)
758
759 assert status == 200
760 assert payload["session"]["session_id"] == created["session"]["session_id"]
761 assert payload["session"]["active"] is False
762 assert payload["session"]["revoked_at"] is not None
763
764 identity_status, _, identity = request("/identity", headers=token_headers)
765 session_status, _, session_payload = request("/identity/session", headers=token_headers)
766
767 assert identity_status == 200
768 assert identity["auth"]["method"] == "anonymous"
769 assert identity["subject"]["authenticated"] is False
770 assert session_status == 401
771 assert session_payload == {"status": "error", "error": "Active session token required"}
772
773
774def test_identity_current_session_login_is_disabled_by_default(tmp_path, monkeypatch):
775 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
776 monkeypatch.delenv(object_server.SESSION_LOGIN_ENV, raising=False)
777 monkeypatch.delenv(object_server.SESSION_LOGIN_TOKEN_ENV, raising=False)
778
779 status, _, payload = request(
780 "/identity/session",
781 method="POST",
782 body=json.dumps({"user_id": "u_7"}).encode(),
783 )
784
785 assert status == 403
786 assert payload == {
787 "status": "error",
788 "error": "Session login is disabled. Set DBBASIC_ENABLE_SESSION_LOGIN=true.",
789 }
790
791
792def test_identity_current_session_login_requires_configured_login_token(
793 tmp_path,
794 monkeypatch,
795):
796 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
797 monkeypatch.setenv(object_server.SESSION_LOGIN_ENV, "true")
798 monkeypatch.delenv(object_server.SESSION_LOGIN_TOKEN_ENV, raising=False)
799
800 status, _, payload = request(
801 "/identity/session",
802 method="POST",
803 body=json.dumps({"user_id": "u_7"}).encode(),
804 )
805
806 assert status == 403
807 assert payload == {
808 "status": "error",
809 "error": "Session login token is not configured. Set DBBASIC_SESSION_LOGIN_TOKEN.",
810 }
811
812
813def test_identity_current_session_login_rejects_wrong_token(tmp_path, monkeypatch):
814 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
815 monkeypatch.setenv(object_server.SESSION_LOGIN_ENV, "true")
816 monkeypatch.setenv(object_server.SESSION_LOGIN_TOKEN_ENV, "login-token")
817
818 status, _, payload = request(
819 "/identity/session",
820 method="POST",
821 body=json.dumps({"user_id": "u_7"}).encode(),
822 headers=[("authorization", "Token wrong")],
823 )
824
825 assert status == 401
826 assert payload == {"status": "error", "error": "Unauthorized"}
827
828
829def test_identity_current_session_login_uses_registered_user_profile(tmp_path, monkeypatch):
830 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
831 monkeypatch.setenv(object_server.SESSION_LOGIN_ENV, "true")
832 monkeypatch.setenv(object_server.SESSION_LOGIN_TOKEN_ENV, "login-token")
833 enable_admin_token(monkeypatch)
834 request(
835 "/identity/accounts",
836 method="POST",
837 body=json.dumps({"account_id": "acme", "subscriptions": ["team"]}).encode(),
838 headers=auth_headers(),
839 )
840 request(
841 "/identity/users",
842 method="POST",
843 body=json.dumps(
844 {
845 "user_id": "u_7",
846 "account_id": "acme",
847 "roles": ["sales"],
848 "subscriptions": ["pro"],
849 }
850 ).encode(),
851 headers=auth_headers(),
852 )
853
854 status, _, created = request(
855 "/identity/session",
856 method="POST",
857 body=json.dumps({"user_id": "u_7", "label": "scroll", "ttl_seconds": 3600}).encode(),
858 headers=[("authorization", "Token login-token")],
859 )
860
861 assert status == 201
862 assert created["status"] == "ok"
863 assert created["token"]
864 assert created["session"]["user_id"] == "u_7"
865 assert created["session"]["account_id"] == "acme"
866 assert created["session"]["roles"] == ["sales"]
867 assert created["session"]["subscriptions"] == ["pro", "team"]
868 assert created["session"]["label"] == "scroll"
869 assert "token_hash" not in created["session"]
870
871 session_status, _, session_payload = request(
872 "/identity/session",
873 headers=[("authorization", f"Bearer {created['token']}")],
874 )
875
876 assert session_status == 200
877 assert session_payload["session"]["session_id"] == created["session"]["session_id"]
878
879
880def test_identity_current_session_login_rejects_role_overrides(tmp_path, monkeypatch):
881 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
882 monkeypatch.setenv(object_server.SESSION_LOGIN_ENV, "true")
883 monkeypatch.setenv(object_server.SESSION_LOGIN_TOKEN_ENV, "login-token")
884
885 status, _, payload = request(
886 "/identity/session",
887 method="POST",
888 body=json.dumps(
889 {
890 "user_id": "u_7",
891 "account_id": "acme",
892 "roles": ["admin"],
893 "subscriptions": ["enterprise"],
894 }
895 ).encode(),
896 headers=[("authorization", "Token login-token")],
897 )
898
899 assert status == 400
900 assert payload == {
901 "status": "error",
902 "error": (
903 "Unsupported session login field(s): account_id, roles, subscriptions"
904 ),
905 }
906
907
908def test_identity_current_session_login_requires_known_active_user(tmp_path, monkeypatch):
909 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
910 monkeypatch.setenv(object_server.SESSION_LOGIN_ENV, "true")
911 monkeypatch.setenv(object_server.SESSION_LOGIN_TOKEN_ENV, "login-token")
912
913 status, _, payload = request(
914 "/identity/session",
915 method="POST",
916 body=json.dumps({"user_id": "missing"}).encode(),
917 headers=[("authorization", "Token login-token")],
918 )
919
920 assert status == 404
921 assert payload == {"status": "error", "error": "User not found: missing"}
922
923
924def _create_password_user(monkeypatch, *, user_id="u_7", email="alice@example.com", password="correct horse battery"):
925 enable_admin_token(monkeypatch)
926 request(
927 "/identity/users",
928 method="POST",
929 body=json.dumps({"user_id": user_id, "email": email}).encode(),
930 headers=auth_headers(),
931 )
932 request(
933 f"/identity/users/{user_id}/password",
934 method="POST",
935 body=json.dumps({"password": password}).encode(),
936 headers=auth_headers(),
937 )
938
939
940def test_password_login_is_disabled_by_default(tmp_path, monkeypatch):
941 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
942 monkeypatch.delenv(object_server.PASSWORD_LOGIN_ENV, raising=False)
943
944 status, _, payload = request(
945 "/identity/session",
946 method="POST",
947 body=json.dumps({"email": "alice@example.com", "password": "whatever12"}).encode(),
948 )
949
950 assert status == 403
951 assert payload == {
952 "status": "error",
953 "error": "Password login is disabled. Set DBBASIC_ENABLE_PASSWORD_LOGIN=true.",
954 }
955
956
957def test_password_login_mints_session_by_email_and_user_id(tmp_path, monkeypatch):
958 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
959 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
960 _create_password_user(monkeypatch)
961
962 email_status, _, email_login = request(
963 "/identity/session",
964 method="POST",
965 body=json.dumps(
966 {"email": "Alice@Example.com", "password": "correct horse battery", "label": "browser"}
967 ).encode(),
968 )
969 user_id_status, _, user_id_login = request(
970 "/identity/session",
971 method="POST",
972 body=json.dumps({"user_id": "u_7", "password": "correct horse battery"}).encode(),
973 )
974
975 assert email_status == 201
976 assert email_login["status"] == "ok"
977 assert email_login["token"]
978 assert email_login["session"]["user_id"] == "u_7"
979 assert email_login["session"]["label"] == "browser"
980 assert user_id_status == 201
981 assert user_id_login["session"]["label"] == "password login"
982
983 session_status, _, session_payload = request(
984 "/identity/session",
985 headers=[("authorization", f"Bearer {email_login['token']}")],
986 )
987
988 assert session_status == 200
989 assert session_payload["session"]["user_id"] == "u_7"
990
991
992def test_password_login_rejects_bad_credentials_uniformly(tmp_path, monkeypatch):
993 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
994 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
995 monkeypatch.setattr(object_server, "PASSWORD_LOGIN_FAILURE_DELAY_SECONDS", 0)
996 _create_password_user(monkeypatch)
997
998 wrong_status, _, wrong_payload = request(
999 "/identity/session",
1000 method="POST",
1001 body=json.dumps({"email": "alice@example.com", "password": "wrong password"}).encode(),
1002 )
1003 unknown_status, _, unknown_payload = request(
1004 "/identity/session",
1005 method="POST",
1006 body=json.dumps({"email": "nobody@example.com", "password": "wrong password"}).encode(),
1007 )
1008 unknown_user_status, _, unknown_user_payload = request(
1009 "/identity/session",
1010 method="POST",
1011 body=json.dumps({"user_id": "u_missing", "password": "wrong password"}).encode(),
1012 )
1013
1014 assert wrong_status == unknown_status == unknown_user_status == 401
1015 assert wrong_payload == unknown_payload == unknown_user_payload == {
1016 "status": "error",
1017 "error": "Invalid credentials",
1018 }
1019
1020
1021def test_password_login_rejects_overrides_and_bad_payloads(tmp_path, monkeypatch):
1022 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1023 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1024 _create_password_user(monkeypatch)
1025
1026 roles_status, _, roles_payload = request(
1027 "/identity/session",
1028 method="POST",
1029 body=json.dumps(
1030 {"email": "alice@example.com", "password": "correct horse battery", "roles": ["admin"]}
1031 ).encode(),
1032 )
1033 both_status, _, both_payload = request(
1034 "/identity/session",
1035 method="POST",
1036 body=json.dumps(
1037 {"user_id": "u_7", "email": "alice@example.com", "password": "correct horse battery"}
1038 ).encode(),
1039 )
1040 neither_status, _, neither_payload = request(
1041 "/identity/session",
1042 method="POST",
1043 body=json.dumps({"password": "correct horse battery"}).encode(),
1044 )
1045
1046 assert roles_status == 400
1047 assert roles_payload == {
1048 "status": "error",
1049 "error": "Unsupported password login fields: roles",
1050 }
1051 assert both_status == 400
1052 assert both_payload["error"] == "Provide exactly one of user_id or email"
1053 assert neither_status == 400
1054 assert neither_payload["error"] == "Provide exactly one of user_id or email"
1055
1056
1057def _password_login_token(*, email="alice@example.com", password="correct horse battery"):
1058 status, _, payload = request(
1059 "/identity/session",
1060 method="POST",
1061 body=json.dumps({"email": email, "password": password}).encode(),
1062 )
1063 assert status == 201
1064 return payload["token"]
1065
1066
1067def test_session_cookie_resolves_current_session_and_subject(tmp_path, monkeypatch):
1068 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1069 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1070 _create_password_user(monkeypatch)
1071 token = _password_login_token()
1072
1073 session_status, _, session_payload = request(
1074 "/identity/session",
1075 headers=[("cookie", f"dbbasic_session={token}")],
1076 )
1077 identity_status, _, identity_payload = request(
1078 "/identity",
1079 headers=[("cookie", f"other=1; dbbasic_session={token}")],
1080 )
1081
1082 assert session_status == 200
1083 assert session_payload["session"]["user_id"] == "u_7"
1084 assert identity_status == 200
1085 assert identity_payload["subject"]["user_id"] == "u_7"
1086 assert identity_payload["auth"]["method"] == "session_cookie"
1087
1088
1089def test_cookie_authenticated_writes_reject_cross_origin(tmp_path, monkeypatch):
1090 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1091 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1092 _create_password_user(monkeypatch)
1093 token = _password_login_token()
1094
1095 cross_status, _, cross_payload = request(
1096 "/identity/session",
1097 method="DELETE",
1098 headers=[
1099 ("cookie", f"dbbasic_session={token}"),
1100 ("origin", "https://evil.example.com"),
1101 ("host", "object.dbbasic.com"),
1102 ],
1103 )
1104 same_status, _, same_payload = request(
1105 "/identity/session",
1106 method="DELETE",
1107 headers=[
1108 ("cookie", f"dbbasic_session={token}"),
1109 ("origin", "https://object.dbbasic.com"),
1110 ("host", "object.dbbasic.com"),
1111 ],
1112 )
1113
1114 assert cross_status == 403
1115 assert cross_payload == {
1116 "status": "error",
1117 "error": "Cross-origin cookie request rejected",
1118 }
1119 assert same_status == 200
1120 assert same_payload["session"]["revoked_at"] is not None
1121
1122
1123def test_header_authenticated_writes_ignore_origin(tmp_path, monkeypatch):
1124 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1125 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1126 _create_password_user(monkeypatch)
1127 token = _password_login_token()
1128
1129 status, _, payload = request(
1130 "/identity/session",
1131 method="DELETE",
1132 headers=[
1133 ("authorization", f"Bearer {token}"),
1134 ("origin", "https://anywhere.example.com"),
1135 ("host", "object.dbbasic.com"),
1136 ],
1137 )
1138
1139 assert status == 200
1140 assert payload["session"]["revoked_at"] is not None
1141
1142
1143def test_authorization_header_wins_over_session_cookie(tmp_path, monkeypatch):
1144 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1145 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1146 _create_password_user(monkeypatch)
1147 token = _password_login_token()
1148
1149 status, _, payload = request(
1150 "/identity",
1151 headers=[
1152 ("authorization", "Bearer not-a-real-token"),
1153 ("cookie", f"dbbasic_session={token}"),
1154 ],
1155 )
1156
1157 assert status == 200
1158 assert payload["subject"]["user_id"] is None
1159 assert payload["auth"]["method"] == "anonymous"
1160
1161
1162def _login_form_request(form: dict[str, str], extra_headers=None):
1163 body = urllib.parse.urlencode(form).encode()
1164 headers = [("content-type", "application/x-www-form-urlencoded")]
1165 headers.extend(extra_headers or [])
1166 return raw_request("/login", method="POST", body=body, headers=headers)
1167
1168
1169def test_login_page_disabled_by_default(tmp_path, monkeypatch):
1170 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1171 monkeypatch.delenv(object_server.PASSWORD_LOGIN_ENV, raising=False)
1172
1173 status, headers, body = raw_request("/login")
1174
1175 assert status == 403
1176 assert b"text/html" in headers[b"content-type"]
1177 assert b"Password login is disabled" in body
1178
1179
1180def test_login_page_renders_form_when_enabled(tmp_path, monkeypatch):
1181 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1182 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1183
1184 status, headers, body = raw_request("/login")
1185 error_status, _, error_body = raw_request("/login", query_string="error=1")
1186
1187 assert status == 200
1188 assert b"text/html" in headers[b"content-type"]
1189 assert b'<form method="post" action="/login">' in body
1190 assert b'name="password"' in body
1191 assert b"Invalid email or password." not in body
1192 assert error_status == 200
1193 assert b"Invalid email or password." in error_body
1194
1195
1196def test_login_form_success_sets_cookie_and_redirects(tmp_path, monkeypatch):
1197 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1198 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1199 _create_password_user(monkeypatch)
1200
1201 status, headers, _ = _login_form_request(
1202 {"email": "alice@example.com", "password": "correct horse battery", "next": "/dashboard"}
1203 )
1204
1205 assert status == 303
1206 assert headers[b"location"] == b"/dashboard"
1207 cookie = headers[b"set-cookie"].decode()
1208 assert cookie.startswith("dbbasic_session=")
1209 assert "HttpOnly" in cookie
1210 assert "SameSite=Lax" in cookie
1211 assert "Secure" in cookie
1212 assert "Path=/" in cookie
1213
1214 token = cookie.split(";")[0].split("=", 1)[1]
1215 session_status, _, session_payload = request(
1216 "/identity/session",
1217 headers=[("cookie", f"dbbasic_session={token}")],
1218 )
1219 assert session_status == 200
1220 assert session_payload["session"]["user_id"] == "u_7"
1221 assert session_payload["session"]["label"] == "browser login"
1222
1223
1224def test_login_form_failure_redirects_with_error(tmp_path, monkeypatch):
1225 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1226 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1227 monkeypatch.setattr(object_server, "PASSWORD_LOGIN_FAILURE_DELAY_SECONDS", 0)
1228 _create_password_user(monkeypatch)
1229
1230 status, headers, _ = _login_form_request(
1231 {"email": "alice@example.com", "password": "wrong password", "next": "/dashboard"}
1232 )
1233
1234 assert status == 303
1235 assert headers[b"location"] == b"/login?error=1&next=/dashboard"
1236 assert b"set-cookie" not in headers
1237
1238
1239def test_login_next_path_is_sanitized(tmp_path, monkeypatch):
1240 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1241 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1242 _create_password_user(monkeypatch)
1243
1244 status, headers, _ = _login_form_request(
1245 {
1246 "email": "alice@example.com",
1247 "password": "correct horse battery",
1248 "next": "//evil.example.com/phish",
1249 }
1250 )
1251
1252 assert status == 303
1253 assert headers[b"location"] == b"/"
1254
1255
1256def test_login_cookie_secure_can_be_disabled_for_local_dev(tmp_path, monkeypatch):
1257 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1258 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1259 monkeypatch.setenv(object_server.COOKIE_SECURE_ENV, "false")
1260 _create_password_user(monkeypatch)
1261
1262 status, headers, _ = _login_form_request(
1263 {"email": "alice@example.com", "password": "correct horse battery"}
1264 )
1265
1266 assert status == 303
1267 assert "Secure" not in headers[b"set-cookie"].decode()
1268
1269
1270def test_login_rejects_json_body(tmp_path, monkeypatch):
1271 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1272 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1273
1274 status, _, payload = request(
1275 "/login",
1276 method="POST",
1277 body=json.dumps({"email": "a@example.com", "password": "x" * 10}).encode(),
1278 headers=[("content-type", "application/json")],
1279 )
1280
1281 assert status == 400
1282 assert "JSON clients should use POST /identity/session" in payload["error"]
1283
1284
1285def test_logout_revokes_session_and_clears_cookie(tmp_path, monkeypatch):
1286 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1287 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1288 _create_password_user(monkeypatch)
1289 token = _password_login_token()
1290
1291 status, headers, _ = raw_request(
1292 "/logout",
1293 method="POST",
1294 headers=[("cookie", f"dbbasic_session={token}")],
1295 )
1296 session_status, _, session_payload = request(
1297 "/identity/session",
1298 headers=[("cookie", f"dbbasic_session={token}")],
1299 )
1300
1301 assert status == 303
1302 assert headers[b"location"] == b"/login"
1303 cookie = headers[b"set-cookie"].decode()
1304 assert cookie.startswith("dbbasic_session=;")
1305 assert "Max-Age=0" in cookie
1306 assert session_status == 401
1307 assert session_payload == {"status": "error", "error": "Active session token required"}
1308
1309
1310def test_login_page_redirects_active_session(tmp_path, monkeypatch):
1311 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1312 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1313 _create_password_user(monkeypatch)
1314 token = _password_login_token()
1315
1316 status, headers, _ = raw_request(
1317 "/login",
1318 headers=[("cookie", f"dbbasic_session={token}")],
1319 )
1320
1321 assert status == 303
1322 assert headers[b"location"] == b"/"
1323
1324
1325def test_objects_receive_request_identity(tmp_path, monkeypatch):
1326 root = tmp_path / "objects"
1327 write_source(
1328 root / "whoami" / "echo.py",
1329 "def GET(request):\n return {'identity': request['_identity']}\n"
1330 "def POST(request):\n return {'identity': request['_identity']}\n",
1331 )
1332 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
1333 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path / "data"))
1334 monkeypatch.setenv(object_server.TRUSTED_IN_PROCESS_OBJECTS_ENV, "whoami_echo")
1335 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1336 _create_password_user(monkeypatch)
1337 token = _password_login_token()
1338
1339 anonymous_status, _, anonymous_payload = request("/objects/whoami_echo")
1340 cookie_status, _, cookie_payload = request(
1341 "/objects/whoami_echo",
1342 headers=[("cookie", f"dbbasic_session={token}")],
1343 )
1344 admin_status, _, admin_payload = request("/objects/whoami_echo", headers=auth_headers())
1345 spoof_status, _, spoof_payload = request(
1346 "/objects/whoami_echo",
1347 method="POST",
1348 body=json.dumps({"_identity": {"user_id": "fake-admin", "roles": ["admin"]}}).encode(),
1349 )
1350
1351 assert anonymous_status == 200
1352 assert anonymous_payload["identity"]["user_id"] is None
1353 assert anonymous_payload["identity"]["auth_method"] == "anonymous"
1354 assert cookie_status == 200
1355 assert cookie_payload["identity"]["user_id"] == "u_7"
1356 assert cookie_payload["identity"]["auth_method"] == "session_cookie"
1357 assert admin_status == 200
1358 assert admin_payload["identity"]["user_id"] == "admin"
1359 assert admin_payload["identity"]["roles"] == ["admin"]
1360 assert admin_payload["identity"]["auth_method"] == "admin_token"
1361 assert spoof_status == 200
1362 assert spoof_payload["identity"]["user_id"] is None
1363 assert spoof_payload["identity"]["roles"] == []
1364 assert spoof_payload["identity"]["auth_method"] == "anonymous"
1365
1366
1367def test_admin_role_session_matches_admin_token_across_gated_surfaces(tmp_path, monkeypatch):
1368 root = tmp_path / "objects"
1369 data_dir = tmp_path / "data"
1370 write_source(
1371 root / "probe" / "tool.py",
1372 "def GET(request):\n return {'ok': True}\n"
1373 "def POST(request):\n return {'ok': True}\n",
1374 )
1375 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
1376 schema_file = data_dir / "schemas" / "contacts.json"
1377 schema_file.parent.mkdir(parents=True, exist_ok=True)
1378 schema_file.write_text(json.dumps({"fields": [{"name": "id"}, {"name": "name"}]}))
1379 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
1380 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
1381 monkeypatch.setenv(object_server.TRUSTED_IN_PROCESS_OBJECTS_ENV, "probe_tool")
1382 monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true")
1383 monkeypatch.setenv("DBBASIC_ENABLE_SOURCE_WRITES", "true")
1384 monkeypatch.setenv("DBBASIC_ENABLE_FILE_WRITES", "true")
1385 enable_admin_token(monkeypatch)
1386 request(
1387 "/identity/users",
1388 method="POST",
1389 body=json.dumps({"user_id": "dan", "email": "dan@example.com", "roles": ["admin"]}).encode(),
1390 headers=auth_headers(),
1391 )
1392 session_token, _ = create_identity_session({"user_id": "dan", "label": "parity"})
1393
1394 identities = {
1395 "admin_token": auth_headers(),
1396 "admin_session": [("authorization", f"Bearer {session_token}")],
1397 }
1398
1399 endpoints = [
1400 ("GET", "/admin/status", "", None),
1401 ("GET", "/admin/changes", "limit=10", None),
1402 ("GET", "/admin/objects", "", None),
1403 ("GET", "/admin/objects/probe_tool", "source=true&format=json", None),
1404 ("GET", "/admin/objects/probe_tool", "state=true", None),
1405 ("GET", "/admin/objects/probe_tool", "logs=true&limit=10", None),
1406 ("GET", "/admin/objects/probe_tool", "metadata=true", None),
1407 ("GET", "/admin/objects/probe_tool", "versions=true&limit=10", None),
1408 ("GET", "/admin/objects/probe_tool", "changes=true&limit=10", None),
1409 ("GET", "/admin/objects/probe_tool", "files=true", None),
1410 ("GET", "/admin/files", "", None),
1411 ("GET", "/admin/files/probe_tool", "", None),
1412 ("GET", "/admin/collections", "", None),
1413 ("GET", "/admin/collections/contacts", "", None),
1414 ("GET", "/admin/collections/contacts/records", "", None),
1415 ("GET", "/admin/collections/contacts/records/c1", "", None),
1416 ("GET", "/admin/collections/contacts/changes", "", None),
1417 ("GET", "/admin/schemas", "", None),
1418 ("GET", "/admin/schemas/contacts", "format=json", None),
1419 ("GET", "/admin/identity/accounts", "", None),
1420 ("GET", "/admin/identity/users", "", None),
1421 ("GET", "/admin/identity/sessions", "", None),
1422 ("GET", "/daemon/status", "", None),
1423 ("GET", "/daemon/scheduler/tasks", "", None),
1424 ("GET", "/daemon/queue/messages", "", None),
1425 ("GET", "/events", "", None),
1426 ("GET", "/events/deliveries", "", None),
1427 ("GET", "/events/subscriptions", "", None),
1428 ("GET", "/packages", "", None),
1429 ("GET", "/permissions/policy", "", None),
1430 ("GET", "/permissions/status", "", None),
1431 ("GET", "/permissions/audit", "", None),
1432 ("GET", "/identity/accounts", "", None),
1433 ("GET", "/identity/users", "", None),
1434 ("GET", "/identity/sessions", "", None),
1435 (
1436 "POST",
1437 "/admin/objects",
1438 "",
1439 lambda label: {"object_id": f"made_{label}", "code": "def GET(request):\n return {}\n"},
1440 ),
1441 (
1442 "PUT",
1443 "/admin/objects/probe_tool",
1444 "source=true",
1445 lambda label: {"code": f"def GET(request):\n return {{'v': '{label}'}}\n"},
1446 ),
1447 ("POST", "/admin/objects/probe_tool/execute", "", lambda label: {"method": "GET", "payload": {}}),
1448 (
1449 "POST",
1450 "/admin/collections/contacts/records",
1451 "",
1452 lambda label: {"id": f"rec_{label}", "name": label},
1453 ),
1454 (
1455 "PUT",
1456 "/admin/collections/contacts/records/c1",
1457 "",
1458 lambda label: {"name": f"Ada {label}"},
1459 ),
1460 (
1461 "PUT",
1462 "/admin/schemas/contacts",
1463 "",
1464 lambda label: {
1465 "schema": {"fields": [{"name": "id"}, {"name": "name"}]},
1466 "author": label,
1467 "message": f"parity {label}",
1468 },
1469 ),
1470 (
1471 "POST",
1472 "/admin/identity/users/dan/password",
1473 "",
1474 lambda label: {"password": f"parity password {label}"},
1475 ),
1476 (
1477 "POST",
1478 "/permissions/check",
1479 "",
1480 lambda label: {
1481 "subject": {"user_id": "7", "roles": ["sales"]},
1482 "action": "read",
1483 "collection": "contacts",
1484 },
1485 ),
1486 ]
1487
1488 mismatches = []
1489 for method, path, query_string, body_factory in endpoints:
1490 statuses = {}
1491 for label, headers in identities.items():
1492 body = b""
1493 if body_factory is not None:
1494 body = json.dumps(body_factory(label)).encode()
1495 status, _, payload = request(
1496 path,
1497 method=method,
1498 query_string=query_string,
1499 body=body,
1500 headers=headers,
1501 )
1502 statuses[label] = status
1503 if statuses["admin_token"] != statuses["admin_session"]:
1504 mismatches.append((method, path, query_string, statuses))
1505 elif statuses["admin_token"] >= 400:
1506 mismatches.append((method, path, query_string, {"both_failed": statuses}))
1507
1508 assert not mismatches, f"Session/token parity failures: {mismatches}"
1509
1510
1511def test_object_create_warns_when_source_defines_no_http_methods(tmp_path, monkeypatch):
1512 root = tmp_path / "objects"
1513 data_dir = tmp_path / "data"
1514 enable_source_writes(monkeypatch, root, data_dir)
1515
1516 no_methods_status, _, no_methods = request(
1517 "/admin/objects",
1518 method="POST",
1519 body=json.dumps(
1520 {"object_id": "probe_legacy", "code": "def handle_get(state, query):\n return {}\n"}
1521 ).encode(),
1522 headers=auth_headers(),
1523 )
1524 syntax_status, _, syntax = request(
1525 "/admin/objects",
1526 method="POST",
1527 body=json.dumps({"object_id": "probe_broken", "code": "def GET(request:\n"}).encode(),
1528 headers=auth_headers(),
1529 )
1530
1531 assert no_methods_status == 201
1532 assert no_methods["methods"] == []
1533 assert "cannot execute" in no_methods["warnings"][0]
1534 assert "GET(request)" in no_methods["warnings"][0]
1535 assert syntax_status == 201
1536 assert syntax["methods"] == []
1537 assert "syntax error" in syntax["warnings"][0]
1538
1539
1540def test_record_changes_carry_correlation_id(tmp_path, monkeypatch):
1541 data_dir = tmp_path / "data"
1542 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
1543 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir))
1544 enable_admin_token(monkeypatch)
1545 correlation_id = "123e4567-e89b-42d3-a456-426614174000"
1546
1547 request(
1548 "/admin/collections/contacts/records",
1549 method="POST",
1550 body=json.dumps({"id": "c2", "name": "Grace"}).encode(),
1551 headers=[*auth_headers(), ("x-dbbasic-correlation-id", correlation_id)],
1552 )
1553 status, _, payload = request(
1554 "/admin/collections/contacts/changes",
1555 headers=auth_headers(),
1556 )
1557
1558 assert status == 200
1559 assert payload["changes"][0]["correlation_id"] == correlation_id
1560
1561
1562def test_ops_feed_records_auth_and_execution_events(tmp_path, monkeypatch):
1563 root = tmp_path / "objects"
1564 write_source(root / "site" / "broken.py", "def GET(request):\n raise ValueError('kaboom')\n")
1565 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
1566 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path / "data"))
1567 monkeypatch.setenv(object_server.TRUSTED_IN_PROCESS_OBJECTS_ENV, "site_broken")
1568 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1569 monkeypatch.setattr(object_server, "PASSWORD_LOGIN_FAILURE_DELAY_SECONDS", 0)
1570 _create_password_user(monkeypatch)
1571
1572 request(
1573 "/identity/session",
1574 method="POST",
1575 body=json.dumps({"email": "alice@example.com", "password": "wrong password"}).encode(),
1576 )
1577 token = _password_login_token()
1578 request("/objects/site_broken")
1579 raw_request(
1580 "/logout",
1581 method="POST",
1582 headers=[("cookie", f"dbbasic_session={token}")],
1583 )
1584
1585 status, _, payload = request("/admin/ops", headers=auth_headers())
1586 failures_status, _, failures = request(
1587 "/admin/ops",
1588 query_string="kind=auth&event=login_failed",
1589 headers=auth_headers(),
1590 )
1591 unauth_status, _, _ = request("/admin/ops")
1592
1593 assert status == 200
1594 events = payload["events"]
1595 kinds = [(entry["kind"], entry.get("event") or entry.get("error_type")) for entry in events]
1596 assert ("auth", "logout") in kinds
1597 assert ("execution_error", "ObjectMethodExecutionError") in kinds
1598 assert ("auth", "login_succeeded") in kinds
1599 assert ("auth", "login_failed") in kinds
1600 execution = next(e for e in events if e["kind"] == "execution_error")
1601 assert execution["object_id"] == "site_broken"
1602 assert "kaboom" in execution["message"]
1603 assert execution["correlation_id"]
1604 assert failures_status == 200
1605 assert failures["events"][0]["identifier"] == "alice@example.com"
1606 serialized = json.dumps(payload)
1607 assert "correct horse battery" not in serialized
1608 assert "wrong password" not in serialized
1609 assert unauth_status == 401
1610
1611
1612def test_login_lockout_blocks_after_repeated_failures(tmp_path, monkeypatch):
1613 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1614 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1615 monkeypatch.setenv(object_server.LOGIN_LOCKOUT_ATTEMPTS_ENV, "3")
1616 monkeypatch.setattr(object_server, "PASSWORD_LOGIN_FAILURE_DELAY_SECONDS", 0)
1617 _create_password_user(monkeypatch)
1618
1619 for _ in range(3):
1620 request(
1621 "/identity/session",
1622 method="POST",
1623 body=json.dumps({"email": "alice@example.com", "password": "wrong password"}).encode(),
1624 )
1625
1626 locked_status, _, locked_payload = request(
1627 "/identity/session",
1628 method="POST",
1629 body=json.dumps({"email": "alice@example.com", "password": "correct horse battery"}).encode(),
1630 )
1631 other_status, _, _ = request(
1632 "/identity/session",
1633 method="POST",
1634 body=json.dumps({"email": "other@example.com", "password": "correct horse battery"}).encode(),
1635 )
1636 form_status, form_headers, _ = raw_request(
1637 "/login",
1638 method="POST",
1639 body=b"email=alice%40example.com&password=correct+horse+battery",
1640 headers=[("content-type", "application/x-www-form-urlencoded")],
1641 )
1642 locked_page_status, _, locked_page = raw_request("/login", query_string="error=locked")
1643
1644 assert locked_status == 429
1645 assert locked_payload == {"status": "error", "error": object_server.LOGIN_LOCKED_MESSAGE}
1646 assert other_status == 401 # different identifier is not locked
1647 assert form_status == 303
1648 assert form_headers[b"location"].startswith(b"/login?error=locked")
1649 assert locked_page_status == 200
1650 assert object_server.LOGIN_LOCKED_MESSAGE.encode() in locked_page
1651
1652 events = request("/admin/ops", query_string="kind=auth", headers=auth_headers())[2]["events"]
1653 assert any(entry.get("event") == "login_locked" for entry in events)
1654
1655
1656def test_login_lockout_resets_after_success_and_respects_window(tmp_path, monkeypatch):
1657 import object_ops_log
1658 from datetime import datetime, timedelta, timezone
1659
1660 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1661 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
1662 monkeypatch.setenv(object_server.LOGIN_LOCKOUT_ATTEMPTS_ENV, "3")
1663 monkeypatch.setattr(object_server, "PASSWORD_LOGIN_FAILURE_DELAY_SECONDS", 0)
1664 _create_password_user(monkeypatch)
1665
1666 old = datetime.now(timezone.utc) - timedelta(hours=2)
1667 for _ in range(5):
1668 object_ops_log.append_event(
1669 object_ops_log.AUTH,
1670 {"event": "login_failed", "identifier": "alice@example.com"},
1671 base_dir=tmp_path,
1672 now=old,
1673 )
1674
1675 stale_status, _, _ = request(
1676 "/identity/session",
1677 method="POST",
1678 body=json.dumps({"email": "alice@example.com", "password": "correct horse battery"}).encode(),
1679 )
1680 assert stale_status == 201 # old failures are outside the window
1681
1682 for _ in range(2):
1683 request(
1684 "/identity/session",
1685 method="POST",
1686 body=json.dumps({"email": "alice@example.com", "password": "wrong password"}).encode(),
1687 )
1688 after_success_status, _, _ = request(
1689 "/identity/session",
1690 method="POST",
1691 body=json.dumps({"email": "alice@example.com", "password": "correct horse battery"}).encode(),
1692 )
1693 assert after_success_status == 201 # two recent failures stay under the threshold
1694
1695 monkeypatch.setenv(object_server.LOGIN_LOCKOUT_ATTEMPTS_ENV, "0")
1696 for _ in range(6):
1697 request(
1698 "/identity/session",
1699 method="POST",
1700 body=json.dumps({"email": "alice@example.com", "password": "wrong password"}).encode(),
1701 )
1702 disabled_status, _, _ = request(
1703 "/identity/session",
1704 method="POST",
1705 body=json.dumps({"email": "alice@example.com", "password": "correct horse battery"}).encode(),
1706 )
1707 assert disabled_status == 201 # lockout disabled via env
1708
1709
1710def test_identity_endpoint_ignores_untrusted_identity_headers(monkeypatch):
1711 monkeypatch.delenv("DBBASIC_PERMISSION_TRUST_HEADERS", raising=False)
1712 headers = [
1713 ("x-dbbasic-user-id", "7"),
1714 ("x-dbbasic-account-id", "acme"),
1715 ("x-dbbasic-roles", "sales"),
1716 ]
1717
1718 status, _, payload = request("/identity", headers=headers)
1719
1720 assert status == 200
1721 assert payload["subject"]["user_id"] is None
1722 assert payload["subject"]["account_id"] is None
1723 assert payload["subject"]["roles"] == []
1724 assert payload["auth"] == {
1725 "method": "anonymous",
1726 "trusted_headers_enabled": False,
1727 "trusted_headers_present": True,
1728 }
1729
1730
1731def test_identity_endpoint_reports_trusted_header_subject(monkeypatch):
1732 monkeypatch.setenv("DBBASIC_PERMISSION_TRUST_HEADERS", "true")
1733 headers = [
1734 ("x-dbbasic-user-id", "7"),
1735 ("x-dbbasic-account-id", "acme"),
1736 ("x-dbbasic-roles", "sales,manager,sales"),
1737 ("x-dbbasic-subscriptions", "pro,temporary"),
1738 ]
1739
1740 status, _, payload = request("/identity", headers=headers)
1741
1742 assert status == 200
1743 assert payload["subject"] == {
1744 "user_id": "7",
1745 "account_id": "acme",
1746 "roles": ["sales", "manager"],
1747 "subscriptions": ["pro", "temporary"],
1748 "authenticated": True,
1749 }
1750 assert payload["auth"] == {
1751 "method": "trusted_headers",
1752 "trusted_headers_enabled": True,
1753 "trusted_headers_present": True,
1754 }
1755
1756
1757def test_identity_endpoint_rejects_non_get_methods():
1758 status, _, payload = request("/identity", method="POST")
1759
1760 assert status == 405
1761 assert payload == {"status": "error", "error": "Method not allowed"}
1762
1763
1764def test_health_endpoint_bypasses_request_concurrency_limit(monkeypatch):
1765 monkeypatch.setenv(object_server.MAX_CONCURRENT_REQUESTS_ENV, "1")
1766 token = claim_limit_slot(object_server._request_limiter, 1)
1767 try:
1768 status, _, payload = request("/health")
1769 finally:
1770 token.release()
1771
1772 assert status == 200
1773 assert payload == {"status": "ok"}
1774
1775
1776def test_health_capacity_requires_admin_token_configuration(monkeypatch):
1777 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
1778
1779 status, _, payload = request("/health", query_string="capacity=true")
1780
1781 assert status == 403
1782 assert payload == {
1783 "status": "error",
1784 "error": "Health capacity requires DBBASIC_ADMIN_TOKEN.",
1785 }
1786
1787
1788def test_health_capacity_requires_authorization_header(monkeypatch):
1789 enable_admin_token(monkeypatch)
1790
1791 status, _, payload = request("/health", query_string="capacity=true")
1792
1793 assert status == 401
1794 assert payload == {"status": "error", "error": "Unauthorized"}
1795
1796
1797def test_health_capacity_reports_version_config_objects_and_slots(tmp_path, monkeypatch):
1798 root = tmp_path / "objects"
1799 data_dir = tmp_path / "data"
1800 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
1801 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
1802 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
1803 monkeypatch.setenv(object_server.MAX_REQUEST_BYTES_ENV, "2048")
1804 monkeypatch.setenv(object_server.MAX_CONCURRENT_REQUESTS_ENV, "2")
1805 monkeypatch.setenv(object_server.MAX_CONCURRENT_EXECUTIONS_ENV, "1")
1806 monkeypatch.setenv(object_server.TRUSTED_IN_PROCESS_OBJECTS_ENV, "site_home, basics_counter")
1807 enable_admin_token(monkeypatch)
1808
1809 token = claim_limit_slot(object_server._request_limiter, 2)
1810 try:
1811 status, _, payload = request(
1812 "/health",
1813 query_string="capacity=true",
1814 headers=auth_headers(),
1815 )
1816 finally:
1817 token.release()
1818
1819 assert status == 200
1820 assert payload["status"] == "ok"
1821 assert payload["version"] == "0.0.1"
1822 assert payload["station_id"] == "standalone"
1823 assert payload["objects"] == {"count": 1}
1824 assert payload["checks"]["storage"] == {"status": "ok"}
1825 assert payload["config"]["max_request_bytes"] == 2048
1826 assert payload["config"]["max_concurrent_requests"] == 2
1827 assert payload["config"]["max_concurrent_executions"] == 1
1828 assert payload["config"]["trusted_in_process_objects"] == ["basics_counter", "site_home"]
1829 assert payload["config"]["permission_enforcement_enabled"] is False
1830 assert payload["config"]["permission_audit_enabled"] is False
1831 assert payload["config"]["permission_trust_headers"] is False
1832 assert payload["capacity"]["requests"] == {
1833 "in_flight": 1,
1834 "max": 2,
1835 "available": 1,
1836 "limited": True,
1837 }
1838 assert payload["capacity"]["object_executions"] == {
1839 "in_flight": 0,
1840 "max": 1,
1841 "available": 1,
1842 "limited": True,
1843 }
1844 assert "metrics" not in payload
1845
1846
1847def test_health_metrics_keeps_old_dashboard_shape(monkeypatch):
1848 enable_admin_token(monkeypatch)
1849 request("/missing-before-health-metrics")
1850
1851 status, _, payload = request(
1852 "/health",
1853 query_string="metrics=true",
1854 headers=auth_headers(),
1855 )
1856
1857 assert status == 200
1858 assert payload["status"] == "ok"
1859 assert payload["requests"] >= 1
1860 assert payload["errors"] >= 0
1861 assert payload["rps"] >= 0
1862 assert set(payload["response_time_ms"]) == {"avg", "p50", "p95", "p99"}
1863 assert payload["metrics"]["total_requests"] >= 1
1864 assert payload["metrics"]["total_4xx"] >= 1
1865 assert "top_paths" in payload["metrics"]
1866
1867
1868def test_health_metrics_reports_disk_and_cpu_capacity(tmp_path, monkeypatch):
1869 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1870 enable_admin_token(monkeypatch)
1871
1872 request("/health", query_string="metrics=true", headers=auth_headers())
1873 status, _, payload = request(
1874 "/health",
1875 query_string="metrics=true",
1876 headers=auth_headers(),
1877 )
1878
1879 assert status == 200
1880 disk = payload["system"]["disk"]
1881 assert disk["total_gb"] > 0
1882 assert 0 <= disk["used_percent"] <= 100
1883 assert disk["used_gb"] <= disk["total_gb"]
1884 cpu_percent = payload["system"].get("cpu_percent")
1885 assert cpu_percent is None or 0 <= cpu_percent <= 100
1886
1887
1888def test_health_metrics_history_snapshots_and_readback(tmp_path, monkeypatch):
1889 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1890 monkeypatch.setenv(object_server.METRICS_SNAPSHOT_SECONDS_ENV, "1")
1891 monkeypatch.setattr(object_server, "_LAST_METRICS_SNAPSHOT", 0.0)
1892 enable_admin_token(monkeypatch)
1893
1894 request("/health")
1895 monkeypatch.setattr(object_server, "_LAST_METRICS_SNAPSHOT", 0.0)
1896 status, _, payload = request(
1897 "/health",
1898 query_string="metrics=true&history=true",
1899 headers=auth_headers(),
1900 )
1901
1902 assert status == 200
1903 assert len(payload["history"]) >= 2
1904 latest = payload["history"][-1]
1905 assert latest["requests"] >= 1
1906 assert latest["timestamp"].endswith("Z")
1907
1908 monkeypatch.setenv(object_server.METRICS_SNAPSHOT_SECONDS_ENV, "0")
1909 plain_status, _, plain_payload = request(
1910 "/health",
1911 query_string="metrics=true",
1912 headers=auth_headers(),
1913 )
1914 assert plain_status == 200
1915 assert "history" not in plain_payload
1916
1917
1918def test_admin_status_requires_admin_token(monkeypatch):
1919 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
1920
1921 status, _, payload = request("/admin/status", headers=auth_headers())
1922
1923 assert status == 403
1924 assert payload == {
1925 "status": "error",
1926 "error": "Admin status requires DBBASIC_ADMIN_TOKEN.",
1927 }
1928
1929
1930def test_admin_status_rejects_admin_session_when_session_admin_gates_disabled(tmp_path, monkeypatch):
1931 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1932 enable_admin_token(monkeypatch)
1933 token, _ = create_identity_session({"user_id": "admin-user", "roles": ["admin"]})
1934
1935 status, _, payload = request("/admin/status", headers=session_headers(token))
1936
1937 assert status == 401
1938 assert payload == {"status": "error", "error": "Unauthorized"}
1939
1940
1941def test_admin_status_accepts_admin_session_when_session_admin_gates_enabled(tmp_path, monkeypatch):
1942 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1943 monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true")
1944 enable_admin_token(monkeypatch)
1945 token, _ = create_identity_session({"user_id": "admin-user", "roles": ["admin"]})
1946
1947 status, _, payload = request("/admin/status", headers=session_headers(token))
1948
1949 assert status == 200
1950 assert payload["status"] == "ok"
1951
1952
1953def test_admin_status_rejects_non_admin_session_when_session_admin_gates_enabled(
1954 tmp_path,
1955 monkeypatch,
1956):
1957 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1958 monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true")
1959 enable_admin_token(monkeypatch)
1960 token, _ = create_identity_session({"user_id": "sales-user", "roles": ["sales"]})
1961
1962 status, _, payload = request("/admin/status", headers=session_headers(token))
1963
1964 assert status == 401
1965 assert payload == {"status": "error", "error": "Unauthorized"}
1966
1967
1968def test_admin_status_rejects_revoked_admin_session_when_session_admin_gates_enabled(
1969 tmp_path,
1970 monkeypatch,
1971):
1972 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
1973 monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true")
1974 enable_admin_token(monkeypatch)
1975 token, session = create_identity_session({"user_id": "admin-user", "roles": ["admin"]})
1976 status, _, _ = request(
1977 f"/identity/sessions/{session['session_id']}",
1978 method="DELETE",
1979 headers=auth_headers(),
1980 )
1981 assert status == 200
1982
1983 status, _, payload = request("/admin/status", headers=session_headers(token))
1984
1985 assert status == 401
1986 assert payload == {"status": "error", "error": "Unauthorized"}
1987
1988
1989def test_admin_status_reports_inventory_capabilities_and_package_posture(tmp_path, monkeypatch):
1990 root = tmp_path / "objects"
1991 data_dir = tmp_path / "data"
1992 packages_root = tmp_path / "packages"
1993 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
1994 schema_file = data_dir / "schemas" / "dbbasic_probe.json"
1995 schema_file.parent.mkdir(parents=True, exist_ok=True)
1996 schema_file.write_text(
1997 json.dumps(
1998 {
1999 "title": "Probe",
2000 "fields": [{"name": "note", "type": "text"}],
2001 }
2002 )
2003 )
2004 write_records(data_dir, "dbbasic_probe", "id\tnote\nprobe_001\talready installed\n")
2005 write_package(
2006 packages_root,
2007 "probe-pack",
2008 {
2009 "id": "probe-pack",
2010 "name": "Probe Pack",
2011 "version": "0.1.0",
2012 "description": "Status fixture",
2013 "objects": [{"id": "site_home", "path": "objects/site/home.py"}],
2014 "schemas": [{"collection": "dbbasic_probe", "path": "schemas/dbbasic_probe.json"}],
2015 "permissions": [],
2016 "seed": [],
2017 "migrations": [],
2018 },
2019 files=(
2020 ("objects/site/home.py", "def GET(request): return {'ok': True}\n"),
2021 (
2022 "schemas/dbbasic_probe.json",
2023 json.dumps({"title": "Probe", "fields": [{"name": "note", "type": "text"}]}),
2024 ),
2025 ),
2026 )
2027 object_package_changes.append_package_change(
2028 package_id="probe-pack",
2029 action="dry_run",
2030 package_version="0.1.0",
2031 actor="unit-test",
2032 base_dir=data_dir,
2033 )
2034 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2035 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2036 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
2037 monkeypatch.setenv(object_server.MAX_REQUEST_BYTES_ENV, "2048")
2038 monkeypatch.setenv(object_server.MAX_OBJECT_FILE_BYTES_ENV, "1024")
2039 monkeypatch.setenv(object_server.MAX_CONCURRENT_REQUESTS_ENV, "3")
2040 monkeypatch.setenv(object_server.MAX_CONCURRENT_EXECUTIONS_ENV, "2")
2041 enable_admin_token(monkeypatch)
2042
2043 status, _, payload = request("/admin/status", headers=auth_headers())
2044
2045 assert status == 200
2046 assert payload["status"] == "ok"
2047 assert payload["version"] == "0.0.1"
2048 assert payload["health"]["status"] == "ok"
2049 assert "metrics" in payload["health"]
2050 assert payload["inventory"] == {
2051 "objects": 1,
2052 "collections": 2,
2053 "schemas": 2,
2054 "packages": 1,
2055 }
2056 assert payload["capabilities"]["source_writes"] == {
2057 "enabled": False,
2058 "env": "DBBASIC_ENABLE_SOURCE_WRITES",
2059 }
2060 assert payload["capabilities"]["file_writes"] == {
2061 "enabled": False,
2062 "env": "DBBASIC_ENABLE_FILE_WRITES",
2063 "max_bytes": 1024,
2064 "max_bytes_env": "DBBASIC_MAX_OBJECT_FILE_BYTES",
2065 }
2066 assert payload["capabilities"]["package_installs"] == {
2067 "enabled": False,
2068 "env": "DBBASIC_ENABLE_PACKAGE_INSTALLS",
2069 }
2070 assert payload["capabilities"]["identity"]["session_login_enabled"] is False
2071 assert payload["capabilities"]["identity"]["session_login_token_configured"] is False
2072 assert payload["capabilities"]["identity"]["session_admin_gates_enabled"] is False
2073 assert payload["capabilities"]["identity"]["session_admin_gates_env"] == (
2074 object_server.SESSION_ADMIN_GATES_ENV
2075 )
2076 assert payload["capabilities"]["limits"]["max_request_bytes"] == 2048
2077 assert payload["capabilities"]["limits"]["max_object_file_bytes"] == 1024
2078 assert payload["capabilities"]["limits"]["max_concurrent_requests"] == 3
2079 assert payload["capabilities"]["limits"]["max_concurrent_executions"] == 2
2080 assert payload["permissions"]["enforcement_enabled"] is False
2081 assert payload["permissions"]["audit_enabled"] is False
2082 assert payload["packages"][0]["id"] == "probe-pack"
2083 assert payload["packages"][0]["status"] == "installed"
2084 assert payload["packages"][0]["install"]["installed_count"] == 2
2085 assert payload["packages"][0]["install"]["installable_count"] == 2
2086 assert payload["packages"][0]["install"]["install_enabled"] is False
2087 assert payload["packages"][0]["changes"]["total"] == 1
2088 assert payload["packages"][0]["changes"]["latest"]["action"] == "dry_run"
2089
2090
2091def test_daemon_status_requires_admin_token(monkeypatch):
2092 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
2093
2094 status, _, payload = request("/daemon/status", headers=auth_headers())
2095
2096 assert status == 403
2097 assert payload == {
2098 "status": "error",
2099 "error": "Daemon status requires DBBASIC_ADMIN_TOKEN.",
2100 }
2101
2102
2103def test_daemon_status_reports_scheduler_queue_and_event_state(tmp_path, monkeypatch):
2104 root = tmp_path / "objects"
2105 data_dir = tmp_path / "data"
2106 write_source(root / "triggers" / "scheduler.py", "def POST(request):\n return {'ok': True}\n")
2107 write_source(root / "triggers" / "queue.py", "def POST(request):\n return {'ok': True}\n")
2108 write_source(root / "triggers" / "events.py", "def POST(request):\n return {'ok': True}\n")
2109
2110 scheduler = object_state.ObjectStateManager("scheduler", base_dir=data_dir)
2111 scheduler.set("task_due", json.dumps({"id": "due", "status": "active", "next_run": 1}))
2112 queue = object_state.ObjectStateManager("queue", base_dir=data_dir)
2113 queue.set("msg_ready", json.dumps({"id": "ready", "status": "pending", "visible_after": 1}))
2114 events = object_state.ObjectStateManager("events", base_dir=data_dir)
2115 events.set(
2116 "event_1_evt",
2117 json.dumps(
2118 {
2119 "id": "evt",
2120 "event_type": "collection.record.created",
2121 "payload": {"hidden": True},
2122 "timestamp": 1,
2123 }
2124 ),
2125 )
2126
2127 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2128 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2129 enable_admin_token(monkeypatch)
2130
2131 status, _, payload = request("/daemon/status", headers=auth_headers())
2132
2133 assert status == 200
2134 assert payload["status"] == "ok"
2135 assert set(payload) == {"status", "timestamp", "daemon", "scheduler", "queue", "events", "cleanup"}
2136 assert payload["daemon"]["triggers"]["scheduler"]["source_present"] is True
2137 assert payload["scheduler"]["tasks"]["active"] == 1
2138 assert payload["queue"]["messages"]["pending_visible"] == 1
2139 assert payload["events"]["events"]["latest"]["id"] == "evt"
2140 assert "payload" not in payload["events"]["events"]["latest"]
2141
2142
2143def test_daemon_scheduler_task_api_creates_lists_updates_and_deletes(tmp_path, monkeypatch):
2144 data_dir = tmp_path / "data"
2145 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2146 enable_admin_token(monkeypatch)
2147
2148 status, _, created = request(
2149 "/daemon/scheduler/tasks",
2150 method="POST",
2151 body=json.dumps(
2152 {
2153 "object_id": "system_dashboard",
2154 "method": "POST",
2155 "type": "onetime",
2156 "schedule": "2026-07-01T12:00:00Z",
2157 "payload": {"refresh": True},
2158 }
2159 ).encode(),
2160 headers=auth_headers(),
2161 )
2162
2163 assert status == 201
2164 assert created["status"] == "ok"
2165 task = created["task"]
2166 assert object_ids.is_uuid4(task["id"])
2167 assert task["object_id"] == "system_dashboard"
2168 assert task["payload_present"] is True
2169 assert "payload" not in task
2170
2171 status, _, listed = request("/daemon/scheduler/tasks", headers=auth_headers())
2172
2173 assert status == 200
2174 assert listed["status"] == "ok"
2175 assert listed["count"] == 1
2176 assert listed["tasks"] == [task]
2177
2178 status, _, updated = request(
2179 f"/daemon/scheduler/tasks/{task['id']}",
2180 method="PATCH",
2181 body=json.dumps({"status": "paused"}).encode(),
2182 headers=auth_headers(),
2183 )
2184
2185 assert status == 200
2186 assert updated["task"]["id"] == task["id"]
2187 assert updated["task"]["status"] == "paused"
2188
2189 status, _, deleted = request(
2190 f"/daemon/scheduler/tasks/{task['id']}",
2191 method="DELETE",
2192 headers=auth_headers(),
2193 )
2194
2195 assert status == 200
2196 assert deleted["deleted"] is True
2197 assert deleted["task"]["id"] == task["id"]
2198
2199
2200def test_daemon_queue_message_api_enqueues_lists_retries_and_deletes(tmp_path, monkeypatch):
2201 data_dir = tmp_path / "data"
2202 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2203 enable_admin_token(monkeypatch)
2204
2205 status, _, created = request(
2206 "/daemon/queue/messages",
2207 method="POST",
2208 body=json.dumps(
2209 {
2210 "object_id": "system_dashboard",
2211 "queue_name": "default",
2212 "priority_level": 7,
2213 "payload": {"refresh": True},
2214 }
2215 ).encode(),
2216 headers=auth_headers(),
2217 )
2218
2219 assert status == 201
2220 message = created["message"]
2221 assert object_ids.is_uuid4(message["id"])
2222 assert message["status"] == "pending"
2223 assert message["message"]["object_id"] == "system_dashboard"
2224 assert message["message"]["payload_present"] is True
2225 assert "payload" not in message["message"]
2226
2227 status, _, listed = request(
2228 "/daemon/queue/messages",
2229 query_string="status=pending&queue_name=default",
2230 headers=auth_headers(),
2231 )
2232
2233 assert status == 200
2234 assert listed["count"] == 1
2235 assert listed["messages"] == [message]
2236
2237 status, _, cancelled = request(
2238 f"/daemon/queue/messages/{message['id']}",
2239 method="PATCH",
2240 body=json.dumps({"action": "cancel"}).encode(),
2241 headers=auth_headers(),
2242 )
2243
2244 assert status == 200
2245 assert cancelled["message"]["status"] == "cancelled"
2246
2247 status, _, retried = request(
2248 f"/daemon/queue/messages/{message['id']}",
2249 method="PATCH",
2250 body=json.dumps({"action": "retry"}).encode(),
2251 headers=auth_headers(),
2252 )
2253
2254 assert status == 200
2255 assert retried["message"]["status"] == "pending"
2256
2257 status, _, deleted = request(
2258 f"/daemon/queue/messages/{message['id']}",
2259 method="DELETE",
2260 headers=auth_headers(),
2261 )
2262
2263 assert status == 200
2264 assert deleted["deleted"] is True
2265 assert deleted["message"]["id"] == message["id"]
2266
2267
2268def test_daemon_control_routes_require_admin_token(monkeypatch):
2269 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
2270
2271 scheduler_status, _, scheduler_payload = request("/daemon/scheduler/tasks")
2272 queue_status, _, queue_payload = request("/daemon/queue/messages")
2273
2274 assert scheduler_status == 403
2275 assert scheduler_payload == {
2276 "status": "error",
2277 "error": "Daemon scheduler controls require DBBASIC_ADMIN_TOKEN.",
2278 }
2279 assert queue_status == 403
2280 assert queue_payload == {
2281 "status": "error",
2282 "error": "Daemon queue controls require DBBASIC_ADMIN_TOKEN.",
2283 }
2284
2285
2286def test_request_concurrency_limit_returns_503_when_full(monkeypatch):
2287 monkeypatch.setenv(object_server.MAX_CONCURRENT_REQUESTS_ENV, "1")
2288 token = claim_limit_slot(object_server._request_limiter, 1)
2289 try:
2290 status, _, payload = request("/missing")
2291 finally:
2292 token.release()
2293
2294 assert status == 503
2295 assert payload == {
2296 "status": "error",
2297 "error": "Server is busy",
2298 "limit": "requests",
2299 "max_concurrent": 1,
2300 }
2301
2302
2303def test_request_concurrency_limit_releases_after_error(monkeypatch):
2304 monkeypatch.setenv(object_server.MAX_CONCURRENT_REQUESTS_ENV, "1")
2305
2306 first_status, _, first_payload = request("/missing")
2307 second_status, _, second_payload = request("/missing")
2308
2309 assert first_status == 404
2310 assert first_payload == {"status": "error", "error": "Not found"}
2311 assert second_status == 404
2312 assert second_payload == {"status": "error", "error": "Not found"}
2313
2314
2315def test_rate_limit_returns_429_with_retry_after(tmp_path, monkeypatch):
2316 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path / "data"))
2317 monkeypatch.setenv(object_server.RATE_LIMIT_REQUESTS_ENV, "1")
2318 monkeypatch.setenv(object_server.RATE_LIMIT_WINDOW_SECONDS_ENV, "60")
2319 client = ("198.51.100.10", 54321)
2320
2321 first_status, _, first_payload = request("/missing", client=client)
2322 second_status, second_headers, second_payload = request("/missing", client=client)
2323
2324 assert first_status == 404
2325 assert first_payload == {"status": "error", "error": "Not found"}
2326 assert second_status == 429
2327 assert second_headers[b"retry-after"].isdigit()
2328 assert second_payload["status"] == "error"
2329 assert second_payload["error"] == "Rate limit exceeded"
2330 assert second_payload["limit"] == 1
2331 assert second_payload["window_seconds"] == 60
2332
2333
2334def test_plain_health_bypasses_rate_limit(tmp_path, monkeypatch):
2335 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path / "data"))
2336 monkeypatch.setenv(object_server.RATE_LIMIT_REQUESTS_ENV, "1")
2337 client = ("198.51.100.10", 54321)
2338
2339 assert request("/health", client=client)[2] == {"status": "ok"}
2340 assert request("/health", client=client)[2] == {"status": "ok"}
2341
2342
2343def test_admin_token_uses_separate_rate_limit_bucket(tmp_path, monkeypatch):
2344 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path / "data"))
2345 monkeypatch.setenv(object_server.RATE_LIMIT_REQUESTS_ENV, "1")
2346 monkeypatch.setenv(object_server.RATE_LIMIT_WINDOW_SECONDS_ENV, "60")
2347 enable_admin_token(monkeypatch)
2348 client = ("198.51.100.10", 54321)
2349
2350 assert request("/missing", client=client)[0] == 404
2351 status, _, payload = request(
2352 "/health",
2353 query_string="capacity=true",
2354 headers=auth_headers(),
2355 client=client,
2356 )
2357
2358 assert status == 200
2359 assert payload["status"] == "ok"
2360
2361
2362def test_rate_limit_can_trust_proxy_headers_when_configured(tmp_path, monkeypatch):
2363 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path / "data"))
2364 monkeypatch.setenv(object_server.RATE_LIMIT_REQUESTS_ENV, "1")
2365 monkeypatch.setenv(object_server.RATE_LIMIT_TRUST_PROXY_HEADERS_ENV, "true")
2366 proxy_client = ("127.0.0.1", 54321)
2367
2368 first_status = request(
2369 "/missing",
2370 headers=[("x-forwarded-for", "198.51.100.10")],
2371 client=proxy_client,
2372 )[0]
2373 second_status = request(
2374 "/missing",
2375 headers=[("x-forwarded-for", "198.51.100.11")],
2376 client=proxy_client,
2377 )[0]
2378
2379 assert first_status == 404
2380 assert second_status == 404
2381
2382
2383def test_object_list_returns_existing_contract_shape(tmp_path, monkeypatch):
2384 root = tmp_path / "objects"
2385 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 1}\n")
2386 write_source(root / "users" / "42" / "deals.py", "def GET(request):\n return {}\n")
2387 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2388 enable_admin_token(monkeypatch)
2389
2390 status, _, payload = request("/objects", query_string="format=json", headers=auth_headers())
2391
2392 assert status == 200
2393 assert payload["status"] == "ok"
2394 assert payload["count"] == 2
2395 assert payload["objects"] == [
2396 {
2397 "object_id": "basics_counter",
2398 "path": "basics/counter.py",
2399 "owner": "system",
2400 },
2401 {
2402 "object_id": "u_42_deals",
2403 "path": "users/42/deals.py",
2404 "owner": "42",
2405 },
2406 ]
2407
2408
2409def test_object_list_returns_empty_when_objects_dir_is_missing(tmp_path, monkeypatch):
2410 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "missing"))
2411 enable_admin_token(monkeypatch)
2412
2413 status, _, payload = request("/objects", query_string="format=json", headers=auth_headers())
2414
2415 assert status == 200
2416 assert payload == {"status": "ok", "objects": [], "count": 0}
2417
2418
2419def test_object_list_requires_admin_token_configuration(tmp_path, monkeypatch):
2420 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
2421 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
2422
2423 status, _, payload = request("/objects", query_string="format=json")
2424
2425 assert status == 403
2426 assert payload == {"status": "error", "error": "Object listing requires DBBASIC_ADMIN_TOKEN."}
2427
2428
2429def test_object_list_requires_authorization_header(tmp_path, monkeypatch):
2430 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
2431 enable_admin_token(monkeypatch)
2432
2433 status, _, payload = request("/objects", query_string="format=json")
2434
2435 assert status == 401
2436 assert payload == {"status": "error", "error": "Unauthorized"}
2437
2438
2439def test_admin_objects_alias_lists_objects_with_admin_token(tmp_path, monkeypatch):
2440 root = tmp_path / "objects"
2441 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
2442 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2443 enable_admin_token(monkeypatch)
2444
2445 missing_status, _, missing_payload = request("/admin/objects", query_string="format=json")
2446 status, _, payload = request(
2447 "/admin/objects",
2448 query_string="format=json",
2449 headers=auth_headers(),
2450 )
2451
2452 assert missing_status == 401
2453 assert missing_payload == {"status": "error", "error": "Unauthorized"}
2454 assert status == 200
2455 assert payload == {
2456 "status": "ok",
2457 "objects": [
2458 {
2459 "object_id": "basics_counter",
2460 "path": "basics/counter.py",
2461 "owner": "system",
2462 }
2463 ],
2464 "count": 1,
2465 }
2466
2467
2468def test_admin_object_alias_exposes_read_only_inspection_surfaces(tmp_path, monkeypatch):
2469 root = tmp_path / "objects"
2470 data_dir = tmp_path / "data"
2471 write_source(
2472 root / "basics" / "counter.py",
2473 "def GET(request):\n"
2474 " _state_manager.set('executed', True)\n"
2475 " return {'status': 'executed'}\n",
2476 )
2477 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2478 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2479 enable_admin_token(monkeypatch)
2480 object_logs.append_object_log(
2481 "basics_counter",
2482 "INFO",
2483 "operator inspected",
2484 base_dir=data_dir,
2485 )
2486 object_versions.VersionManager(data_dir).save_version(
2487 "basics_counter",
2488 "def GET(request):\n return {}\n",
2489 author="test",
2490 message="first",
2491 )
2492 object_source_changes.append_source_change(
2493 object_id="basics_counter",
2494 action="source_update",
2495 version_id=1,
2496 actor="test",
2497 message="first",
2498 base_dir=data_dir,
2499 )
2500
2501 metadata_status, _, metadata = request(
2502 "/admin/objects/basics_counter",
2503 headers=auth_headers(),
2504 )
2505 source_status, _, source = request(
2506 "/admin/objects/basics_counter",
2507 query_string="source=true&format=json",
2508 headers=auth_headers(),
2509 )
2510 logs_status, _, logs = request(
2511 "/admin/objects/basics_counter",
2512 query_string="logs=true&limit=10",
2513 headers=auth_headers(),
2514 )
2515 versions_status, _, versions = request(
2516 "/admin/objects/basics_counter",
2517 query_string="versions=true&limit=10",
2518 headers=auth_headers(),
2519 )
2520 changes_status, _, changes = request(
2521 "/admin/objects/basics_counter",
2522 query_string="source_changes=true&limit=10",
2523 headers=auth_headers(),
2524 )
2525
2526 assert metadata_status == 200
2527 assert metadata["status"] == "ok"
2528 assert metadata["object_id"] == "basics_counter"
2529 assert metadata["metadata"]["source_path"] == "basics/counter.py"
2530 assert object_state.get_object_state("basics_counter", base_dir=data_dir) == {}
2531
2532 assert source_status == 200
2533 assert source["source"].startswith("def GET(request):")
2534 assert logs_status == 200
2535 assert logs["logs"][0]["message"] == "operator inspected"
2536 assert versions_status == 200
2537 assert versions["versions"][0]["message"] == "first"
2538 assert changes_status == 200
2539 assert changes["changes"][0]["action"] == "source_update"
2540
2541
2542def test_admin_object_alias_rejects_unsupported_queries(tmp_path, monkeypatch):
2543 root = tmp_path / "objects"
2544 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
2545 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2546 enable_admin_token(monkeypatch)
2547
2548 status, _, payload = request(
2549 "/admin/objects/basics_counter",
2550 query_string="execute=true",
2551 headers=auth_headers(),
2552 )
2553
2554 assert status == 400
2555 assert payload["status"] == "error"
2556 assert "Unsupported admin object inspection query" in payload["error"]
2557
2558
2559def test_admin_object_execute_requires_authorization_header(tmp_path, monkeypatch):
2560 root = tmp_path / "objects"
2561 data_dir = tmp_path / "data"
2562 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'ran': True}\n")
2563 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2564 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2565 enable_admin_token(monkeypatch)
2566
2567 status, _, payload = request(
2568 "/admin/objects/basics_counter/execute",
2569 method="POST",
2570 body=json.dumps({"method": "GET"}).encode(),
2571 )
2572
2573 assert status == 401
2574 assert payload == {"status": "error", "error": "Unauthorized"}
2575 assert object_logs.get_object_logs("basics_counter", base_dir=data_dir) == []
2576
2577
2578def test_admin_object_execute_runs_get_with_payload(tmp_path, monkeypatch):
2579 root = tmp_path / "objects"
2580 data_dir = tmp_path / "data"
2581 write_source(
2582 root / "basics" / "counter.py",
2583 "def GET(request):\n"
2584 " return {'method': 'GET', 'value': request.get('value')}\n",
2585 )
2586 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2587 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2588 enable_admin_token(monkeypatch)
2589
2590 status, _, payload = request(
2591 "/admin/objects/basics_counter/execute",
2592 method="POST",
2593 body=json.dumps({"method": "GET", "payload": {"value": "from-scroll"}}).encode(),
2594 headers=auth_headers(),
2595 )
2596
2597 assert status == 200
2598 assert payload == {"method": "GET", "value": "from-scroll"}
2599 logs = object_logs.get_object_logs("basics_counter", base_dir=data_dir)
2600 assert logs[0]["message"] == "GET completed successfully"
2601 assert logs[0]["method"] == "GET"
2602
2603
2604def test_admin_object_execute_runs_post_with_payload(tmp_path, monkeypatch):
2605 root = tmp_path / "objects"
2606 write_source(
2607 root / "basics" / "counter.py",
2608 "def POST(request):\n"
2609 " return {'method': 'POST', 'value': request.get('value')}\n",
2610 )
2611 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2612 enable_admin_token(monkeypatch)
2613
2614 status, _, payload = request(
2615 "/admin/objects/basics_counter/execute",
2616 method="POST",
2617 body=json.dumps({"method": "POST", "payload": {"value": "from-scroll"}}).encode(),
2618 headers=auth_headers(),
2619 )
2620
2621 assert status == 200
2622 assert payload == {"method": "POST", "value": "from-scroll"}
2623
2624
2625def test_admin_object_execute_rejects_bad_shape(tmp_path, monkeypatch):
2626 root = tmp_path / "objects"
2627 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
2628 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2629 enable_admin_token(monkeypatch)
2630
2631 method_status, _, method_payload = request(
2632 "/admin/objects/basics_counter/execute",
2633 method="POST",
2634 body=json.dumps({"method": "PATCH"}).encode(),
2635 headers=auth_headers(),
2636 )
2637 payload_status, _, payload_payload = request(
2638 "/admin/objects/basics_counter/execute",
2639 method="POST",
2640 body=json.dumps({"payload": ["not", "object"]}).encode(),
2641 headers=auth_headers(),
2642 )
2643
2644 assert method_status == 400
2645 assert method_payload == {
2646 "status": "error",
2647 "error": "Request JSON field 'method' must be one of GET, POST, PUT, DELETE",
2648 }
2649 assert payload_status == 400
2650 assert payload_payload == {
2651 "status": "error",
2652 "error": "Request JSON field 'payload' must be an object",
2653 }
2654
2655
2656def test_admin_object_execute_rejects_non_post_method(tmp_path, monkeypatch):
2657 root = tmp_path / "objects"
2658 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
2659 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2660 enable_admin_token(monkeypatch)
2661
2662 status, _, payload = request(
2663 "/admin/objects/basics_counter/execute",
2664 method="GET",
2665 headers=auth_headers(),
2666 )
2667
2668 assert status == 405
2669 assert payload == {"status": "error", "error": "Method not allowed"}
2670
2671
2672# --- Phase 3: override objects (conflict-free customization, Rule 2) --------
2673
2674
2675def test_admin_status_reports_overrides_capability_disabled_by_default(tmp_path, monkeypatch):
2676 monkeypatch.delenv("DBBASIC_OVERRIDES_DIR", raising=False)
2677 enable_admin_token(monkeypatch)
2678
2679 status, _, payload = request("/admin/status", headers=auth_headers())
2680
2681 assert status == 200
2682 assert payload["capabilities"]["overrides"] == {
2683 "enabled": False,
2684 "env": "DBBASIC_OVERRIDES_DIR",
2685 }
2686
2687
2688def test_admin_status_reports_overrides_capability_when_enabled(tmp_path, monkeypatch):
2689 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(tmp_path / "overrides"))
2690 enable_admin_token(monkeypatch)
2691
2692 status, _, payload = request("/admin/status", headers=auth_headers())
2693
2694 assert status == 200
2695 assert payload["capabilities"]["overrides"] == {
2696 "enabled": True,
2697 "env": "DBBASIC_OVERRIDES_DIR",
2698 }
2699
2700
2701def test_admin_object_override_post_requires_overrides_enabled(tmp_path, monkeypatch):
2702 root = tmp_path / "objects"
2703 data_dir = tmp_path / "data"
2704 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
2705 monkeypatch.delenv("DBBASIC_OVERRIDES_DIR", raising=False)
2706 enable_source_writes(monkeypatch, root, data_dir)
2707
2708 status, _, payload = request(
2709 "/admin/objects/basics_counter/override",
2710 method="POST",
2711 headers=auth_headers(),
2712 )
2713
2714 assert status == 400
2715 assert "DBBASIC_OVERRIDES_DIR" in payload["error"]
2716
2717
2718def test_admin_object_override_post_requires_source_write_gate(tmp_path, monkeypatch):
2719 root = tmp_path / "objects"
2720 data_dir = tmp_path / "data"
2721 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
2722 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2723 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2724 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(tmp_path / "overrides"))
2725 enable_admin_token(monkeypatch)
2726 # Note: DBBASIC_ENABLE_SOURCE_WRITES is intentionally left unset.
2727
2728 status, _, payload = request(
2729 "/admin/objects/basics_counter/override",
2730 method="POST",
2731 headers=auth_headers(),
2732 )
2733
2734 assert status == 403
2735 assert "Source writes are disabled" in payload["error"]
2736
2737
2738def test_admin_object_override_post_copies_package_source_then_conflicts_on_repeat(tmp_path, monkeypatch):
2739 root = tmp_path / "objects"
2740 data_dir = tmp_path / "data"
2741 override_root = tmp_path / "overrides"
2742 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'v': 1}\n")
2743 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(override_root))
2744 enable_source_writes(monkeypatch, root, data_dir)
2745
2746 status, _, payload = request(
2747 "/admin/objects/basics_counter/override",
2748 method="POST",
2749 headers=auth_headers(),
2750 )
2751
2752 assert status == 200
2753 assert payload["status"] == "ok"
2754 assert payload["object_id"] == "basics_counter"
2755 assert payload["created"] is True
2756 override_file = override_root / "basics" / "counter.py"
2757 assert override_file.is_file()
2758 assert override_file.read_text() == "def GET(request):\n return {'v': 1}\n"
2759 # The package copy is untouched.
2760 assert (root / "basics" / "counter.py").read_text() == "def GET(request):\n return {'v': 1}\n"
2761
2762 repeat_status, _, repeat_payload = request(
2763 "/admin/objects/basics_counter/override",
2764 method="POST",
2765 headers=auth_headers(),
2766 )
2767
2768 assert repeat_status == 409
2769 assert "already exists" in repeat_payload["error"]
2770
2771
2772def test_admin_object_override_post_returns_404_for_missing_package_object(tmp_path, monkeypatch):
2773 root = tmp_path / "objects"
2774 data_dir = tmp_path / "data"
2775 root.mkdir()
2776 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(tmp_path / "overrides"))
2777 enable_source_writes(monkeypatch, root, data_dir)
2778
2779 status, _, payload = request(
2780 "/admin/objects/basics_counter/override",
2781 method="POST",
2782 headers=auth_headers(),
2783 )
2784
2785 assert status == 404
2786
2787
2788def test_admin_object_override_delete_removes_file_and_falls_back_to_package(tmp_path, monkeypatch):
2789 root = tmp_path / "objects"
2790 data_dir = tmp_path / "data"
2791 override_root = tmp_path / "overrides"
2792 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'v': 1}\n")
2793 write_source(override_root / "basics" / "counter.py", "def GET(request):\n return {'v': 'overridden'}\n")
2794 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(override_root))
2795 enable_source_writes(monkeypatch, root, data_dir)
2796
2797 status, _, payload = request(
2798 "/admin/objects/basics_counter/override",
2799 method="DELETE",
2800 headers=auth_headers(),
2801 )
2802
2803 assert status == 200
2804 assert payload == {"status": "ok", "object_id": "basics_counter", "removed": True}
2805 assert not (override_root / "basics" / "counter.py").exists()
2806
2807 # After removal, source reads resolve back to the package copy.
2808 source_status, _, source_payload = request(
2809 "/admin/objects/basics_counter",
2810 query_string="source=true",
2811 headers=auth_headers(),
2812 )
2813 assert source_status == 200
2814 assert source_payload["source"] == "def GET(request):\n return {'v': 1}\n"
2815
2816
2817def test_admin_object_override_delete_returns_404_when_no_override(tmp_path, monkeypatch):
2818 root = tmp_path / "objects"
2819 data_dir = tmp_path / "data"
2820 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
2821 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(tmp_path / "overrides"))
2822 enable_source_writes(monkeypatch, root, data_dir)
2823
2824 status, _, payload = request(
2825 "/admin/objects/basics_counter/override",
2826 method="DELETE",
2827 headers=auth_headers(),
2828 )
2829
2830 assert status == 404
2831
2832
2833def test_admin_object_override_rejects_invalid_object_id(tmp_path, monkeypatch):
2834 root = tmp_path / "objects"
2835 data_dir = tmp_path / "data"
2836 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(tmp_path / "overrides"))
2837 enable_source_writes(monkeypatch, root, data_dir)
2838
2839 status, _, payload = request(
2840 "/admin/objects/bad%2Fid/override",
2841 method="POST",
2842 headers=auth_headers(),
2843 )
2844
2845 assert status == 400
2846
2847
2848def test_admin_object_override_creates_execution_override_while_package_stays_pristine(
2849 tmp_path, monkeypatch
2850):
2851 root = tmp_path / "objects"
2852 data_dir = tmp_path / "data"
2853 override_root = tmp_path / "overrides"
2854 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'v': 'package'}\n")
2855 monkeypatch.setenv("DBBASIC_OVERRIDES_DIR", str(override_root))
2856 enable_source_writes(monkeypatch, root, data_dir)
2857
2858 create_status, _, _ = request(
2859 "/admin/objects/basics_counter/override",
2860 method="POST",
2861 headers=auth_headers(),
2862 )
2863 assert create_status == 200
2864
2865 # Editing via the normal source-write path now edits the override, not
2866 # the package copy, because resolution is override-first once an
2867 # override file exists.
2868 update_status, _, _ = request(
2869 "/objects/basics_counter",
2870 method="PUT",
2871 query_string="source=true",
2872 body=json.dumps(
2873 {"code": "def GET(request):\n return {'v': 'edited-override'}\n"}
2874 ).encode(),
2875 headers=auth_headers(),
2876 )
2877 assert update_status == 200
2878
2879 exec_status, _, exec_payload = request("/objects/basics_counter")
2880 assert exec_status == 200
2881 assert exec_payload == {"v": "edited-override"}
2882
2883 # The package copy on disk was never touched by the override edit.
2884 assert (root / "basics" / "counter.py").read_text() == "def GET(request):\n return {'v': 'package'}\n"
2885
2886
2887def test_admin_collection_alias_exposes_read_only_collection_surfaces(tmp_path, monkeypatch):
2888 root = tmp_path / "objects"
2889 data_dir = tmp_path / "data"
2890 write_source(root / "contacts" / "directory.py", "def GET(request):\n return {}\n")
2891 write_records(data_dir, "contacts", "id\tname\nc1\tAda\nc2\tGrace\n")
2892 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
2893 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2894 enable_admin_token(monkeypatch)
2895
2896 list_status, _, listed = request("/admin/collections", headers=auth_headers())
2897 detail_status, _, detail = request("/admin/collections/contacts", headers=auth_headers())
2898 records_status, _, records = request(
2899 "/admin/collections/contacts/records",
2900 query_string="limit=1",
2901 headers=auth_headers(),
2902 )
2903 record_status, _, record = request(
2904 "/admin/collections/contacts/records/c2",
2905 headers=auth_headers(),
2906 )
2907 collection_put_status, _, collection_put_payload = request(
2908 "/admin/collections/contacts",
2909 method="PUT",
2910 body=json.dumps({"name": "contacts"}).encode(),
2911 headers=auth_headers(),
2912 )
2913
2914 assert list_status == 200
2915 assert listed["status"] == "ok"
2916 assert [item["name"] for item in listed["collections"]] == ["contacts"]
2917 assert detail_status == 200
2918 assert detail["collection"]["name"] == "contacts"
2919 assert records_status == 200
2920 assert records["records"] == [{"id": "c1", "name": "Ada"}]
2921 assert record_status == 200
2922 assert record["record"] == {"id": "c2", "name": "Grace"}
2923 assert collection_put_status == 405
2924 assert collection_put_payload == {"status": "error", "error": "Method not allowed"}
2925
2926
2927def test_admin_collection_record_write_aliases_create_update_delete(tmp_path, monkeypatch):
2928 data_dir = tmp_path / "data"
2929 write_records(data_dir, "contacts", "id\tname\nc1\tAda\nc2\tGrace\n")
2930 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2931 enable_admin_token(monkeypatch)
2932
2933 create_status, _, create_payload = request(
2934 "/admin/collections/contacts/records",
2935 method="POST",
2936 body=json.dumps({"id": "c3", "name": "Katherine"}).encode(),
2937 headers=auth_headers(),
2938 )
2939 update_status, _, update_payload = request(
2940 "/admin/collections/contacts/records/c1",
2941 method="PUT",
2942 body=json.dumps({"name": "Ada Lovelace"}).encode(),
2943 headers=auth_headers(),
2944 )
2945 delete_status, _, delete_payload = request(
2946 "/admin/collections/contacts/records/c2",
2947 method="DELETE",
2948 headers=auth_headers(),
2949 )
2950 list_status, _, list_payload = request(
2951 "/admin/collections/contacts/records",
2952 headers=auth_headers(),
2953 )
2954
2955 assert create_status == 201
2956 assert create_payload["status"] == "ok"
2957 assert create_payload["record"] == {"id": "c3", "name": "Katherine"}
2958 assert update_status == 200
2959 assert update_payload["record"]["name"] == "Ada Lovelace"
2960 assert delete_status == 200
2961 assert delete_payload["deleted"] is True
2962 assert list_status == 200
2963 assert [item["id"] for item in list_payload["records"]] == ["c1", "c3"]
2964
2965
2966def test_record_get_returns_rev_and_if_match_guards_update(tmp_path, monkeypatch):
2967 """63: GET carries an opaque `_rev`; a PUT with a matching If-Match
2968 succeeds and returns the new `_rev`, a stale one 409s with nothing
2969 written, and an absent one is last-write-wins."""
2970 data_dir = tmp_path / "data"
2971 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
2972 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
2973 enable_admin_token(monkeypatch)
2974
2975 get_status, _, get_payload = request(
2976 "/admin/collections/contacts/records/c1", headers=auth_headers()
2977 )
2978 assert get_status == 200
2979 rev = get_payload["_rev"]
2980 assert isinstance(rev, str) and rev
2981
2982 # Matching If-Match -> 200, and a fresh, different _rev comes back.
2983 ok_status, _, ok_payload = request(
2984 "/admin/collections/contacts/records/c1",
2985 method="PUT",
2986 body=json.dumps({"name": "Ada Lovelace"}).encode(),
2987 headers=auth_headers() + [("if-match", rev)],
2988 )
2989 assert ok_status == 200
2990 assert ok_payload["record"]["name"] == "Ada Lovelace"
2991 assert ok_payload["_rev"] != rev
2992
2993 # The original (now stale) rev -> 409 conflict, no write.
2994 conflict_status, _, conflict_payload = request(
2995 "/admin/collections/contacts/records/c1",
2996 method="PUT",
2997 body=json.dumps({"name": "Grace"}).encode(),
2998 headers=auth_headers() + [("if-match", rev)],
2999 )
3000 assert conflict_status == 409
3001 assert conflict_payload["code"] == "conflict"
3002
3003 # The clobber never happened.
3004 _, _, after = request(
3005 "/admin/collections/contacts/records/c1", headers=auth_headers()
3006 )
3007 assert after["record"]["name"] == "Ada Lovelace"
3008
3009 # No If-Match at all -> last-write-wins, no conflict.
3010 lww_status, _, _ = request(
3011 "/admin/collections/contacts/records/c1",
3012 method="PUT",
3013 body=json.dumps({"name": "Katherine"}).encode(),
3014 headers=auth_headers(),
3015 )
3016 assert lww_status == 200
3017
3018
3019def test_concurrency_flag_off_ignores_if_match(tmp_path, monkeypatch):
3020 """63 Degradation: with the flag off, a stale If-Match is ignored (never a
3021 409) and the write proceeds as last-write-wins -- flipping a safety flag
3022 under load must not turn a working write path into an error path."""
3023 data_dir = tmp_path / "data"
3024 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
3025 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3026 enable_admin_token(monkeypatch)
3027 monkeypatch.setenv("DBBASIC_ENABLE_CONCURRENCY", "false")
3028
3029 status, _, payload = request(
3030 "/admin/collections/contacts/records/c1",
3031 method="PUT",
3032 body=json.dumps({"name": "Ada Lovelace"}).encode(),
3033 headers=auth_headers() + [("if-match", "definitely-stale-token")],
3034 )
3035 assert status == 200
3036 assert payload["record"]["name"] == "Ada Lovelace"
3037
3038
3039def write_append_schema(data_dir, collection, fields=None):
3040 path = data_dir / "schemas" / f"{collection}.json"
3041 path.parent.mkdir(parents=True, exist_ok=True)
3042 path.write_text(json.dumps({"fields": fields or [{"name": "id"}], "storage": "append"}))
3043 return path
3044
3045
3046def test_admin_storage_requires_admin_token(monkeypatch):
3047 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
3048
3049 status, _, payload = request("/admin/storage", headers=auth_headers())
3050
3051 assert status == 403
3052 assert payload == {
3053 "status": "error",
3054 "error": "Admin storage requires DBBASIC_ADMIN_TOKEN.",
3055 }
3056
3057
3058def test_admin_storage_rejects_unauthenticated_request(tmp_path, monkeypatch):
3059 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
3060 enable_admin_token(monkeypatch)
3061
3062 status, _, payload = request("/admin/storage")
3063
3064 assert status == 401
3065 assert payload == {"status": "error", "error": "Unauthorized"}
3066
3067
3068def test_admin_storage_lists_append_collections_with_stats(tmp_path, monkeypatch):
3069 """With DBBASIC_RECORDS_CACHE_MAX_ROWS forced to 0, every point op
3070 misses _RECORDS_CACHE and resolves via the id->offset sidecar instead
3071 (same technique object_records' own oidx tests use) -- the sidecar
3072 built along the way is exactly what lets GET /admin/storage answer
3073 real numbers instead of an "estimated" entry, without ever folding
3074 records.tsv itself."""
3075 monkeypatch.setenv("DBBASIC_RECORDS_CACHE_MAX_ROWS", "0")
3076 data_dir = tmp_path / "data"
3077 write_append_schema(data_dir, "widgets", [{"name": "id"}, {"name": "name"}])
3078 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3079 enable_admin_token(monkeypatch)
3080
3081 for i in range(3):
3082 request(
3083 "/admin/collections/widgets/records",
3084 method="POST",
3085 body=json.dumps({"id": f"w{i}", "name": f"n{i}"}).encode(),
3086 headers=auth_headers(),
3087 )
3088 request(
3089 "/admin/collections/widgets/records/w0",
3090 method="PUT",
3091 body=json.dumps({"name": "n0-updated"}).encode(),
3092 headers=auth_headers(),
3093 )
3094
3095 status, _, payload = request("/admin/storage", headers=auth_headers())
3096
3097 assert status == 200
3098 assert payload["status"] == "ok"
3099 assert len(payload["append_collections"]) == 1
3100 entry = payload["append_collections"][0]
3101 assert entry["collection"] == "widgets"
3102 assert entry["storage"] == "append"
3103 assert entry["physical_rows"] == 4
3104 assert entry["live_rows"] == 3
3105 assert entry["dead_rows"] == 1
3106 assert "estimated" not in entry
3107
3108
3109def test_admin_storage_reports_estimated_entry_without_folding(tmp_path, monkeypatch):
3110 """The ordinary (default cache threshold) case: a small append
3111 collection stays warm in _RECORDS_CACHE and no sidecar is ever built,
3112 since every point op is a cache hit. GET /admin/storage must still
3113 answer in O(1) -- an "estimated" entry, never a fold of records.tsv."""
3114 data_dir = tmp_path / "data"
3115 write_append_schema(data_dir, "widgets", [{"name": "id"}, {"name": "name"}])
3116 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3117 enable_admin_token(monkeypatch)
3118
3119 request(
3120 "/admin/collections/widgets/records",
3121 method="POST",
3122 body=json.dumps({"id": "w1", "name": "Alpha"}).encode(),
3123 headers=auth_headers(),
3124 )
3125
3126 status, _, payload = request("/admin/storage", headers=auth_headers())
3127
3128 assert status == 200
3129 entry = payload["append_collections"][0]
3130 assert entry["collection"] == "widgets"
3131 assert entry["estimated"] is True
3132 assert entry["physical_rows"] is None
3133 assert entry["live_rows"] is None
3134 assert entry["file_bytes"] > 0
3135
3136
3137def test_admin_storage_excludes_classic_collections(tmp_path, monkeypatch):
3138 data_dir = tmp_path / "data"
3139 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
3140 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3141 enable_admin_token(monkeypatch)
3142
3143 status, _, payload = request("/admin/storage", headers=auth_headers())
3144
3145 assert status == 200
3146 assert payload == {"status": "ok", "append_collections": []}
3147
3148
3149def test_admin_status_reports_append_collection_count_in_capabilities(tmp_path, monkeypatch):
3150 data_dir = tmp_path / "data"
3151 write_append_schema(data_dir, "widgets", [{"name": "id"}])
3152 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3153 enable_admin_token(monkeypatch)
3154
3155 status, _, payload = request("/admin/status", headers=auth_headers())
3156
3157 assert status == 200
3158 assert payload["capabilities"]["storage"] == {"append_collections": 1}
3159
3160
3161def test_admin_collection_compact_happy_path_shrinks_file_and_reports_duration(tmp_path, monkeypatch):
3162 data_dir = tmp_path / "data"
3163 write_append_schema(data_dir, "widgets", [{"name": "id"}, {"name": "name"}])
3164 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3165 enable_admin_token(monkeypatch)
3166
3167 request(
3168 "/admin/collections/widgets/records",
3169 method="POST",
3170 body=json.dumps({"id": "w1", "name": "Alpha"}).encode(),
3171 headers=auth_headers(),
3172 )
3173 for i in range(5):
3174 request(
3175 "/admin/collections/widgets/records/w1",
3176 method="PUT",
3177 body=json.dumps({"name": f"Alpha{i}"}).encode(),
3178 headers=auth_headers(),
3179 )
3180
3181 path = data_dir / "collections" / "widgets" / "records.tsv"
3182 bytes_before = path.stat().st_size
3183
3184 status, _, payload = request(
3185 "/admin/collections/widgets/compact",
3186 method="POST",
3187 headers=auth_headers(),
3188 )
3189
3190 assert status == 200
3191 assert payload["status"] == "ok"
3192 assert payload["collection"] == "widgets"
3193 assert payload["rows_before"] == 6
3194 assert payload["rows_after"] == 1
3195 assert payload["bytes_before"] == bytes_before
3196 assert payload["bytes_after"] < bytes_before
3197 assert isinstance(payload["duration_ms"], (int, float))
3198 assert payload["duration_ms"] >= 0
3199
3200 assert path.stat().st_size == payload["bytes_after"]
3201
3202
3203def test_admin_collection_compact_returns_400_for_classic_collection(tmp_path, monkeypatch):
3204 data_dir = tmp_path / "data"
3205 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
3206 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3207 enable_admin_token(monkeypatch)
3208
3209 status, _, payload = request(
3210 "/admin/collections/contacts/compact",
3211 method="POST",
3212 headers=auth_headers(),
3213 )
3214
3215 assert status == 400
3216 assert payload["status"] == "error"
3217 assert "not in append storage mode" in payload["error"]
3218
3219
3220def test_admin_collection_compact_returns_404_for_unknown_collection(tmp_path, monkeypatch):
3221 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
3222 enable_admin_token(monkeypatch)
3223
3224 status, _, payload = request(
3225 "/admin/collections/never_heard_of_it/compact",
3226 method="POST",
3227 headers=auth_headers(),
3228 )
3229
3230 assert status == 404
3231
3232
3233def test_admin_collection_compact_requires_admin_token(tmp_path, monkeypatch):
3234 data_dir = tmp_path / "data"
3235 write_append_schema(data_dir, "widgets", [{"name": "id"}])
3236 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3237 enable_admin_token(monkeypatch)
3238
3239 status, _, payload = request(
3240 "/admin/collections/widgets/compact",
3241 method="POST",
3242 )
3243
3244 assert status == 401
3245 assert payload == {"status": "error", "error": "Unauthorized"}
3246
3247
3248def test_admin_collection_compact_rejects_get(tmp_path, monkeypatch):
3249 data_dir = tmp_path / "data"
3250 write_append_schema(data_dir, "widgets", [{"name": "id"}])
3251 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3252 enable_admin_token(monkeypatch)
3253
3254 status, _, payload = request(
3255 "/admin/collections/widgets/compact",
3256 method="GET",
3257 headers=auth_headers(),
3258 )
3259
3260 # Falls through to the GET dispatch for /admin/collections/{collection},
3261 # which treats "compact" as an unsupported nested inspection path.
3262 assert status == 400
3263 assert payload["status"] == "error"
3264
3265
3266def test_record_update_delete_do_not_leak_existence_before_auth(tmp_path, monkeypatch):
3267 data_dir = tmp_path / "data"
3268 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
3269 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3270 enable_admin_token(monkeypatch)
3271
3272 update_status, _, update_payload = request(
3273 "/admin/collections/contacts/records/missing-record",
3274 method="PUT",
3275 body=json.dumps({"name": "Nobody"}).encode(),
3276 )
3277 delete_status, _, delete_payload = request(
3278 "/admin/collections/contacts/records/missing-record",
3279 method="DELETE",
3280 )
3281 authed_status, _, authed_payload = request(
3282 "/admin/collections/contacts/records/missing-record",
3283 method="DELETE",
3284 headers=auth_headers(),
3285 )
3286
3287 assert update_status == 401
3288 assert update_payload == {"status": "error", "error": "Unauthorized"}
3289 assert delete_status == 401
3290 assert delete_payload == {"status": "error", "error": "Unauthorized"}
3291 assert authed_status == 404
3292
3293
3294def test_record_update_delete_do_not_leak_existence_under_enforcement(tmp_path, monkeypatch):
3295 data_dir = tmp_path / "data"
3296 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
3297 save_permission_policy(
3298 data_dir,
3299 {
3300 "access_mode": "role_based",
3301 "rules": [
3302 {
3303 "effect": "allow",
3304 "principal": "role:sales",
3305 "actions": ["update", "delete"],
3306 "collection": "contacts",
3307 }
3308 ],
3309 },
3310 )
3311 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3312 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
3313 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
3314 enable_admin_token(monkeypatch)
3315 sales_headers = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]
3316
3317 anon_update_status, _, anon_update_payload = request(
3318 "/collections/contacts/records/missing-record",
3319 method="PUT",
3320 body=json.dumps({"name": "Nobody"}).encode(),
3321 )
3322 anon_delete_status, _, anon_delete_payload = request(
3323 "/collections/contacts/records/missing-record",
3324 method="DELETE",
3325 )
3326 allowed_missing_status, _, _ = request(
3327 "/collections/contacts/records/missing-record",
3328 method="DELETE",
3329 headers=sales_headers,
3330 )
3331 allowed_real_status, _, allowed_real_payload = request(
3332 "/collections/contacts/records/c1",
3333 method="PUT",
3334 body=json.dumps({"name": "Ada Lovelace"}).encode(),
3335 headers=sales_headers,
3336 )
3337
3338 assert anon_update_status == 403
3339 assert anon_update_payload["code"] == "forbidden"
3340 assert "not found" not in anon_update_payload["error"].lower()
3341 assert anon_delete_status == 403
3342 assert anon_delete_payload["code"] == "forbidden"
3343 assert allowed_missing_status == 404
3344 assert allowed_real_status == 200
3345 assert allowed_real_payload["record"]["name"] == "Ada Lovelace"
3346
3347
3348def test_admin_collection_record_write_aliases_require_admin_token(tmp_path, monkeypatch):
3349 data_dir = tmp_path / "data"
3350 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
3351 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3352 enable_admin_token(monkeypatch)
3353
3354 create_status, _, create_payload = request(
3355 "/admin/collections/contacts/records",
3356 method="POST",
3357 body=json.dumps({"id": "c2", "name": "Grace"}).encode(),
3358 )
3359 update_status, _, update_payload = request(
3360 "/admin/collections/contacts/records/c1",
3361 method="PUT",
3362 body=json.dumps({"name": "Ada Lovelace"}).encode(),
3363 )
3364 delete_status, _, delete_payload = request(
3365 "/admin/collections/contacts/records/c1",
3366 method="DELETE",
3367 )
3368 list_status, _, list_payload = request(
3369 "/admin/collections/contacts/records",
3370 headers=auth_headers(),
3371 )
3372
3373 assert create_status == 401
3374 assert create_payload == {"status": "error", "error": "Unauthorized"}
3375 assert update_status == 401
3376 assert update_payload == {"status": "error", "error": "Unauthorized"}
3377 assert delete_status == 401
3378 assert delete_payload == {"status": "error", "error": "Unauthorized"}
3379 assert list_status == 200
3380 assert list_payload["records"] == [{"id": "c1", "name": "Ada"}]
3381
3382
3383def test_admin_collection_alias_requires_admin_token(tmp_path, monkeypatch):
3384 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
3385 enable_admin_token(monkeypatch)
3386
3387 status, _, payload = request("/admin/collections")
3388
3389 assert status == 401
3390 assert payload == {"status": "error", "error": "Unauthorized"}
3391
3392
3393def test_admin_schema_alias_exposes_read_only_schema_surfaces(tmp_path, monkeypatch):
3394 data_dir = tmp_path / "data"
3395 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3396 enable_admin_token(monkeypatch)
3397 request(
3398 "/schemas/invoices",
3399 method="PUT",
3400 body=json.dumps(
3401 {
3402 "schema": {"fields": [{"name": "invoice_date", "type": "date"}]},
3403 "author": "admin",
3404 "message": "first schema",
3405 }
3406 ).encode(),
3407 headers=auth_headers(),
3408 )
3409
3410 list_status, _, listed = request("/admin/schemas", headers=auth_headers())
3411 detail_status, _, detail = request(
3412 "/admin/schemas/invoices",
3413 query_string="format=json",
3414 headers=auth_headers(),
3415 )
3416 versions_status, _, versions = request(
3417 "/admin/schemas/invoices",
3418 query_string="versions=true&limit=10",
3419 headers=auth_headers(),
3420 )
3421 version_status, _, version = request(
3422 "/admin/schemas/invoices",
3423 query_string="version=1",
3424 headers=auth_headers(),
3425 )
3426 delete_status, _, delete_payload = request(
3427 "/admin/schemas/invoices",
3428 method="DELETE",
3429 headers=auth_headers(),
3430 )
3431
3432 assert list_status == 200
3433 assert listed["schemas"][0]["name"] == "invoices"
3434 assert detail_status == 200
3435 assert detail["schema"]["fields"] == [
3436 {"name": "invoice_date", "type": "date", "required": False}
3437 ]
3438 assert versions_status == 200
3439 assert [item["version_id"] for item in versions["versions"]] == [1]
3440 assert version_status == 200
3441 assert version["version"]["schema"]["fields"] == [
3442 {"name": "invoice_date", "type": "date", "required": False}
3443 ]
3444 assert delete_status == 405
3445 assert delete_payload == {"status": "error", "error": "Method not allowed"}
3446
3447
3448def test_admin_schema_write_aliases_update_and_rollback(tmp_path, monkeypatch):
3449 data_dir = tmp_path / "data"
3450 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3451 enable_admin_token(monkeypatch)
3452
3453 put_status, _, put_payload = request(
3454 "/admin/schemas/invoices",
3455 method="PUT",
3456 body=json.dumps(
3457 {
3458 "schema": {"fields": [{"name": "invoice_date", "type": "date"}]},
3459 "author": "admin",
3460 "message": "first schema",
3461 }
3462 ).encode(),
3463 headers=auth_headers(),
3464 )
3465 update_status, _, update_payload = request(
3466 "/admin/schemas/invoices",
3467 method="PUT",
3468 body=json.dumps(
3469 {
3470 "schema": {"fields": [{"name": "total", "type": "number"}]},
3471 "author": "admin",
3472 "message": "replace fields",
3473 }
3474 ).encode(),
3475 headers=auth_headers(),
3476 )
3477 rollback_status, _, rollback_payload = request(
3478 "/admin/schemas/invoices",
3479 method="POST",
3480 body=json.dumps({"action": "rollback", "version_id": 1}).encode(),
3481 headers=auth_headers(),
3482 )
3483 detail_status, _, detail = request(
3484 "/admin/schemas/invoices",
3485 query_string="format=json",
3486 headers=auth_headers(),
3487 )
3488
3489 assert put_status == 200
3490 assert put_payload["version_id"] == 1
3491 assert update_status == 200
3492 assert update_payload["version_id"] == 2
3493 assert rollback_status == 200
3494 assert rollback_payload["status"] == "ok"
3495 assert detail_status == 200
3496 assert detail["schema"]["fields"] == [
3497 {"name": "invoice_date", "type": "date", "required": False}
3498 ]
3499
3500
3501def test_admin_schema_write_aliases_require_admin_token(tmp_path, monkeypatch):
3502 data_dir = tmp_path / "data"
3503 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3504 enable_admin_token(monkeypatch)
3505
3506 put_status, _, put_payload = request(
3507 "/admin/schemas/invoices",
3508 method="PUT",
3509 body=json.dumps({"schema": {"fields": [{"name": "total"}]}}).encode(),
3510 )
3511 rollback_status, _, rollback_payload = request(
3512 "/admin/schemas/invoices",
3513 method="POST",
3514 body=json.dumps({"action": "rollback", "version_id": 1}).encode(),
3515 )
3516
3517 assert put_status == 401
3518 assert put_payload == {"status": "error", "error": "Unauthorized"}
3519 assert rollback_status == 401
3520 assert rollback_payload == {"status": "error", "error": "Unauthorized"}
3521
3522
3523def test_admin_schema_alias_rejects_unsupported_queries(tmp_path, monkeypatch):
3524 data_dir = tmp_path / "data"
3525 schema_file = data_dir / "schemas" / "invoices.json"
3526 schema_file.parent.mkdir(parents=True, exist_ok=True)
3527 schema_file.write_text(json.dumps({"fields": []}))
3528 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3529 enable_admin_token(monkeypatch)
3530
3531 status, _, payload = request(
3532 "/admin/schemas/invoices",
3533 query_string="rollback=true",
3534 headers=auth_headers(),
3535 )
3536
3537 assert status == 400
3538 assert payload["status"] == "error"
3539 assert "Unsupported admin schema inspection query" in payload["error"]
3540
3541
3542def test_admin_identity_alias_exposes_read_only_identity_surfaces(tmp_path, monkeypatch):
3543 data_dir = tmp_path / "data"
3544 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3545 enable_admin_token(monkeypatch)
3546 request(
3547 "/identity/accounts",
3548 method="POST",
3549 body=json.dumps({"account_id": "acme", "name": "Acme Corp"}).encode(),
3550 headers=auth_headers(),
3551 )
3552 request(
3553 "/identity/users",
3554 method="POST",
3555 body=json.dumps(
3556 {
3557 "user_id": "u_7",
3558 "account_id": "acme",
3559 "email": "ada@example.com",
3560 "roles": ["admin"],
3561 }
3562 ).encode(),
3563 headers=auth_headers(),
3564 )
3565 created_status, _, created = request(
3566 "/identity/sessions",
3567 method="POST",
3568 body=json.dumps({"user_id": "u_7", "label": "scroll"}).encode(),
3569 headers=auth_headers(),
3570 )
3571
3572 accounts_status, _, accounts = request("/admin/identity/accounts", headers=auth_headers())
3573 account_status, _, account = request(
3574 "/admin/identity/accounts/acme",
3575 headers=auth_headers(),
3576 )
3577 users_status, _, users = request(
3578 "/admin/identity/users",
3579 query_string="account_id=acme",
3580 headers=auth_headers(),
3581 )
3582 user_status, _, user = request("/admin/identity/users/u_7", headers=auth_headers())
3583 sessions_status, _, sessions = request("/admin/identity/sessions", headers=auth_headers())
3584 session_status, _, session = request(
3585 f"/admin/identity/sessions/{created['session']['session_id']}",
3586 headers=auth_headers(),
3587 )
3588 create_status, _, create_payload = request(
3589 "/admin/identity/users",
3590 method="POST",
3591 body=json.dumps({"user_id": "u_8"}).encode(),
3592 headers=auth_headers(),
3593 )
3594 delete_status, _, delete_payload = request(
3595 f"/admin/identity/sessions/{created['session']['session_id']}",
3596 method="DELETE",
3597 headers=auth_headers(),
3598 )
3599
3600 assert created_status == 201
3601 assert accounts_status == 200
3602 assert accounts["accounts"][0]["account_id"] == "acme"
3603 assert account_status == 200
3604 assert account["account"]["name"] == "Acme Corp"
3605 assert users_status == 200
3606 assert users["users"][0]["user_id"] == "u_7"
3607 assert user_status == 200
3608 assert user["user"]["email"] == "ada@example.com"
3609 assert sessions_status == 200
3610 assert sessions["sessions"][0]["label"] == "scroll"
3611 assert session_status == 200
3612 assert session["session"]["user_id"] == "u_7"
3613 assert create_status == 405
3614 assert create_payload == {"status": "error", "error": "Method not allowed"}
3615 assert delete_status == 405
3616 assert delete_payload == {"status": "error", "error": "Method not allowed"}
3617
3618
3619def test_admin_identity_alias_requires_admin_token(tmp_path, monkeypatch):
3620 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
3621 enable_admin_token(monkeypatch)
3622
3623 status, _, payload = request("/admin/identity/users")
3624
3625 assert status == 401
3626 assert payload == {"status": "error", "error": "Unauthorized"}
3627
3628
3629def test_collection_list_requires_admin_token_configuration(tmp_path, monkeypatch):
3630 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
3631 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
3632
3633 status, _, payload = request("/collections")
3634
3635 assert status == 403
3636 assert payload == {"status": "error", "error": "Collection listing requires DBBASIC_ADMIN_TOKEN."}
3637
3638
3639def test_collection_list_requires_authorization_header(tmp_path, monkeypatch):
3640 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
3641 enable_admin_token(monkeypatch)
3642
3643 status, _, payload = request("/collections")
3644
3645 assert status == 401
3646 assert payload == {"status": "error", "error": "Unauthorized"}
3647
3648
3649def test_collection_list_returns_derived_collection_summaries(tmp_path, monkeypatch):
3650 root = tmp_path / "objects"
3651 data_dir = tmp_path / "data"
3652 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
3653 write_source(root / "site" / "about.py", "def GET(request):\n return {'ok': True}\n")
3654 write_source(root / "users" / "42" / "deals.py", "def GET(request):\n return {}\n")
3655 save_permission_policy(
3656 data_dir,
3657 {
3658 "access_mode": "role_based",
3659 "rules": [
3660 {
3661 "effect": "allow",
3662 "principal": "role:admin",
3663 "actions": ["read", "execute"],
3664 "collection": "site",
3665 }
3666 ],
3667 },
3668 )
3669 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
3670 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3671 enable_admin_token(monkeypatch)
3672
3673 status, _, payload = request("/collections", headers=auth_headers())
3674
3675 assert status == 200
3676 assert payload["status"] == "ok"
3677 assert payload["count"] == 2
3678 assert [item["name"] for item in payload["collections"]] == ["deals", "site"]
3679 site = payload["collections"][1]
3680 assert site["object_count"] == 2
3681 assert site["has_records"] is False
3682 assert site["owners"] == ["system"]
3683 assert site["kinds"] == {"system": 2}
3684 assert site["permission"]["principals"] == ["role:admin"]
3685
3686
3687def test_collection_detail_returns_objects(tmp_path, monkeypatch):
3688 root = tmp_path / "objects"
3689 data_dir = tmp_path / "data"
3690 write_source(root / "apps" / "widget_counter.py", "def GET(request):\n return {}\n")
3691 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
3692 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3693 enable_admin_token(monkeypatch)
3694
3695 status, _, payload = request("/collections/apps", headers=auth_headers())
3696
3697 assert status == 200
3698 assert payload["status"] == "ok"
3699 assert payload["collection"]["name"] == "apps"
3700 assert payload["collection"]["objects"] == [
3701 {
3702 "object_id": "apps_widget_counter",
3703 "path": "apps/widget_counter.py",
3704 "owner": "system",
3705 "kind": "system",
3706 "state_count": 0,
3707 "has_logs": False,
3708 "file_count": 0,
3709 }
3710 ]
3711
3712
3713def test_collection_detail_rejects_invalid_name(tmp_path, monkeypatch):
3714 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
3715 enable_admin_token(monkeypatch)
3716
3717 status, _, payload = request("/collections/bad.name", headers=auth_headers())
3718
3719 assert status == 400
3720 assert payload["status"] == "error"
3721 assert payload["error"] == "Invalid collection name: bad.name"
3722
3723
3724def test_collection_detail_rejects_missing_collection(tmp_path, monkeypatch):
3725 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
3726 enable_admin_token(monkeypatch)
3727
3728 status, _, payload = request("/collections/missing", headers=auth_headers())
3729
3730 assert status == 404
3731 assert payload == {"status": "error", "error": "Collection not found: missing"}
3732
3733
3734def test_collection_routes_reject_non_get_methods(tmp_path, monkeypatch):
3735 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
3736 enable_admin_token(monkeypatch)
3737
3738 list_status, _, list_payload = request("/collections", method="POST", headers=auth_headers())
3739 detail_status, _, detail_payload = request(
3740 "/collections/site",
3741 method="POST",
3742 headers=auth_headers(),
3743 )
3744
3745 assert list_status == 405
3746 assert detail_status == 405
3747 assert list_payload == {"status": "error", "error": "Method not allowed"}
3748 assert detail_payload == {"status": "error", "error": "Method not allowed"}
3749
3750
3751def test_collection_records_require_admin_token_configuration(tmp_path, monkeypatch):
3752 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
3753 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
3754
3755 status, _, payload = request("/collections/contacts/records")
3756
3757 assert status == 403
3758 assert payload == {"status": "error", "error": "Collection records require DBBASIC_ADMIN_TOKEN."}
3759
3760
3761def test_collection_records_require_authorization_header(tmp_path, monkeypatch):
3762 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
3763 enable_admin_token(monkeypatch)
3764
3765 status, _, payload = request("/collections/contacts/records")
3766
3767 assert status == 401
3768 assert payload == {"status": "error", "error": "Unauthorized"}
3769
3770
3771def test_collection_records_return_paginated_tsv_rows(tmp_path, monkeypatch):
3772 data_dir = tmp_path / "data"
3773 write_records(
3774 data_dir,
3775 "contacts",
3776 "id\tfirst_name\tlast_name\n"
3777 "c1\tAda\tLovelace\n"
3778 "c2\tGrace\tHopper\n"
3779 "c3\tKatherine\tJohnson\n",
3780 )
3781 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3782 enable_admin_token(monkeypatch)
3783
3784 status, _, payload = request(
3785 "/collections/contacts/records",
3786 query_string="limit=2&offset=1",
3787 headers=auth_headers(),
3788 )
3789
3790 assert status == 200
3791 # 63 ships a rev per returned row -- only the WINDOW, which is what
3792 # this offset/limit case is here to pin.
3793 assert set(payload.pop("revs")) == {"c2", "c3"}
3794 assert payload == {
3795 "status": "ok",
3796 "collection": "contacts",
3797 "records": [
3798 {"id": "c2", "first_name": "Grace", "last_name": "Hopper"},
3799 {"id": "c3", "first_name": "Katherine", "last_name": "Johnson"},
3800 ],
3801 "count": 2,
3802 "total": 3,
3803 "limit": 2,
3804 "offset": 1,
3805 "has_more": False,
3806 }
3807
3808
3809def test_collection_record_detail_returns_one_tsv_row(tmp_path, monkeypatch):
3810 data_dir = tmp_path / "data"
3811 write_records(data_dir, "contacts", "id\tname\nc1\tAda\nc2\tGrace\n")
3812 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3813 enable_admin_token(monkeypatch)
3814
3815 status, _, payload = request("/collections/contacts/records/c2", headers=auth_headers())
3816
3817 assert status == 200
3818 # 63 adds an opaque `_rev` sibling to the envelope; the meaningful body is
3819 # unchanged.
3820 assert isinstance(payload.pop("_rev"), str)
3821 assert payload == {
3822 "status": "ok",
3823 "collection": "contacts",
3824 "record": {"id": "c2", "name": "Grace"},
3825 }
3826
3827
3828def test_collection_records_return_empty_for_schema_backed_collection(tmp_path, monkeypatch):
3829 data_dir = tmp_path / "data"
3830 schema_file = data_dir / "schemas" / "invoices.json"
3831 schema_file.parent.mkdir(parents=True, exist_ok=True)
3832 schema_file.write_text(json.dumps({"fields": [{"name": "id"}]}))
3833 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3834 enable_admin_token(monkeypatch)
3835
3836 status, _, payload = request("/collections/invoices/records", headers=auth_headers())
3837
3838 assert status == 200
3839 assert payload["records"] == []
3840 assert payload["total"] == 0
3841
3842
3843def test_collection_records_reject_bad_limit(tmp_path, monkeypatch):
3844 data_dir = tmp_path / "data"
3845 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
3846 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3847 enable_admin_token(monkeypatch)
3848
3849 status, _, payload = request(
3850 "/collections/contacts/records",
3851 query_string="limit=0",
3852 headers=auth_headers(),
3853 )
3854
3855 assert status == 400
3856 assert payload == {"status": "error", "error": "Query parameter 'limit' must be at least 1"}
3857
3858
3859def test_collection_records_reject_invalid_and_missing_collection(tmp_path, monkeypatch):
3860 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
3861 enable_admin_token(monkeypatch)
3862
3863 invalid_status, _, invalid_payload = request(
3864 "/collections/bad.name/records",
3865 headers=auth_headers(),
3866 )
3867 missing_status, _, missing_payload = request(
3868 "/collections/missing/records",
3869 headers=auth_headers(),
3870 )
3871
3872 assert invalid_status == 400
3873 assert invalid_payload == {"status": "error", "error": "Invalid collection name: bad.name"}
3874 assert missing_status == 404
3875 assert missing_payload == {"status": "error", "error": "Collection not found: missing"}
3876
3877
3878def test_collection_record_detail_rejects_invalid_and_missing_record(tmp_path, monkeypatch):
3879 data_dir = tmp_path / "data"
3880 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
3881 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3882 enable_admin_token(monkeypatch)
3883
3884 invalid_status, _, invalid_payload = request(
3885 "/collections/contacts/records/bad.name",
3886 headers=auth_headers(),
3887 )
3888 missing_status, _, missing_payload = request(
3889 "/collections/contacts/records/missing",
3890 headers=auth_headers(),
3891 )
3892
3893 assert invalid_status == 400
3894 assert invalid_payload == {"status": "error", "error": "Invalid record id: bad.name"}
3895 assert missing_status == 404
3896 assert missing_payload == {
3897 "status": "error",
3898 "error": "Record not found: contacts/missing",
3899 }
3900
3901
3902def test_collection_record_routes_reject_non_get_methods(tmp_path, monkeypatch):
3903 enable_admin_token(monkeypatch)
3904
3905 list_status, _, list_payload = request(
3906 "/collections/contacts/records",
3907 method="PUT",
3908 headers=auth_headers(),
3909 )
3910 detail_status, _, detail_payload = request(
3911 "/collections/contacts/records/c1",
3912 method="POST",
3913 headers=auth_headers(),
3914 )
3915
3916 assert list_status == 405
3917 assert detail_status == 405
3918 assert list_payload == {"status": "error", "error": "Method not allowed"}
3919 assert detail_payload == {"status": "error", "error": "Method not allowed"}
3920
3921
3922def test_collection_record_create_requires_admin_token_by_default(tmp_path, monkeypatch):
3923 data_dir = tmp_path / "data"
3924 schema_file = data_dir / "schemas" / "contacts.json"
3925 schema_file.parent.mkdir(parents=True, exist_ok=True)
3926 schema_file.write_text(json.dumps({"fields": [{"name": "id"}]}))
3927 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3928 enable_admin_token(monkeypatch)
3929
3930 missing_auth_status, _, missing_auth_payload = request(
3931 "/collections/contacts/records",
3932 method="POST",
3933 body=json.dumps({"id": "c1", "name": "Ada"}).encode("utf-8"),
3934 )
3935 create_status, _, create_payload = request(
3936 "/collections/contacts/records",
3937 method="POST",
3938 body=json.dumps({"id": "c1", "name": "Ada"}).encode("utf-8"),
3939 headers=auth_headers(),
3940 )
3941
3942 assert missing_auth_status == 401
3943 assert missing_auth_payload == {"status": "error", "error": "Unauthorized"}
3944 assert create_status == 201
3945 assert create_payload == {
3946 "status": "ok",
3947 "collection": "contacts",
3948 "record": {"id": "c1", "name": "Ada"},
3949 }
3950
3951
3952def test_collection_record_create_uses_schema_validation(tmp_path, monkeypatch):
3953 data_dir = tmp_path / "data"
3954 schema_file = data_dir / "schemas" / "invoices.json"
3955 schema_file.parent.mkdir(parents=True, exist_ok=True)
3956 schema_file.write_text(
3957 json.dumps(
3958 {
3959 "fields": [
3960 {"name": "id"},
3961 {"name": "invoice_date", "type": "date", "required": True},
3962 {"name": "status", "type": "enum", "enum": ["draft", "sent"], "default": "draft"},
3963 {"name": "total", "type": "computed", "computed": "sum(line_items)"},
3964 ]
3965 }
3966 )
3967 )
3968 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
3969 enable_admin_token(monkeypatch)
3970
3971 missing_required_status, _, missing_required_payload = request(
3972 "/collections/invoices/records",
3973 method="POST",
3974 body=json.dumps({"id": "i1", "status": "draft"}).encode("utf-8"),
3975 headers=auth_headers(),
3976 )
3977 invalid_computed_status, _, invalid_computed_payload = request(
3978 "/collections/invoices/records",
3979 method="POST",
3980 body=json.dumps({"id": "i1", "invoice_date": "2026-04-08", "total": "100"}).encode("utf-8"),
3981 headers=auth_headers(),
3982 )
3983 create_status, _, create_payload = request(
3984 "/collections/invoices/records",
3985 method="POST",
3986 body=json.dumps({"id": "i1", "invoice_date": "2026-04-08"}).encode("utf-8"),
3987 headers=auth_headers(),
3988 )
3989
3990 assert missing_required_status == 400
3991 assert missing_required_payload == {
3992 "status": "error",
3993 "error": "Record field 'invoice_date' is required",
3994 }
3995 assert invalid_computed_status == 400
3996 assert invalid_computed_payload == {
3997 "status": "error",
3998 "error": "Record field 'total' is computed or read-only and cannot be written",
3999 }
4000 assert create_status == 201
4001 assert create_payload == {
4002 "status": "ok",
4003 "collection": "invoices",
4004 "record": {"id": "i1", "invoice_date": "2026-04-08", "status": "draft"},
4005 }
4006
4007
4008def test_collection_record_create_rejects_duplicate_and_invalid_payload(tmp_path, monkeypatch):
4009 data_dir = tmp_path / "data"
4010 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
4011 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4012 enable_admin_token(monkeypatch)
4013
4014 duplicate_status, _, duplicate_payload = request(
4015 "/collections/contacts/records",
4016 method="POST",
4017 body=json.dumps({"id": "c1", "name": "Again"}).encode("utf-8"),
4018 headers=auth_headers(),
4019 )
4020 generated_status, _, generated_payload = request(
4021 "/collections/contacts/records",
4022 method="POST",
4023 body=json.dumps({"name": "Server ID"}).encode("utf-8"),
4024 headers=auth_headers(),
4025 )
4026 invalid_status, _, invalid_payload = request(
4027 "/collections/contacts/records",
4028 method="POST",
4029 body=json.dumps({"name": {"nested": "bad"}}).encode("utf-8"),
4030 headers=auth_headers(),
4031 )
4032
4033 assert duplicate_status == 409
4034 assert duplicate_payload == {
4035 "status": "error",
4036 "error": "Record already exists: contacts/c1",
4037 }
4038 assert generated_status == 201
4039 assert generated_payload["record"]["name"] == "Server ID"
4040 assert invalid_status == 400
4041 assert invalid_payload == {
4042 "status": "error",
4043 "error": "Record field value must be scalar or null: name",
4044 }
4045
4046
4047EVENT_HANDLER_SOURCE = (
4048 'HANDLES = ["notes.record.created"]\n\n'
4049 "import json\n\n\n"
4050 "def EVENT(request):\n"
4051 " _state_manager.set('last_event', json.dumps(request))\n"
4052 " return {'status': 'ok'}\n"
4053)
4054
4055
4056def test_collection_record_create_dispatches_event_handlers_when_enabled(tmp_path, monkeypatch):
4057 objects_root = tmp_path / "objects"
4058 data_dir = tmp_path / "data"
4059 schema_file = data_dir / "schemas" / "notes.json"
4060 schema_file.parent.mkdir(parents=True, exist_ok=True)
4061 schema_file.write_text(json.dumps({"fields": [{"name": "id"}]}))
4062 write_source(objects_root / "notes" / "handler.py", EVENT_HANDLER_SOURCE)
4063
4064 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
4065 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4066 monkeypatch.setenv(object_handlers.HANDLERS_ENABLED_ENV, "true")
4067 enable_admin_token(monkeypatch)
4068 object_handlers.invalidate()
4069
4070 create_status, _, create_payload = request(
4071 "/collections/notes/records",
4072 method="POST",
4073 body=json.dumps({"id": "n1"}).encode("utf-8"),
4074 headers=auth_headers(),
4075 )
4076
4077 assert create_status == 201
4078 assert create_payload["record"]["id"] == "n1"
4079
4080 state = object_state.ObjectStateManager("notes_handler", base_dir=str(data_dir))
4081 fired = json.loads(state.get("last_event"))
4082 assert fired == {
4083 "event": "notes.record.created",
4084 "collection": "notes",
4085 "record_id": "n1",
4086 "action": "create",
4087 }
4088
4089 object_handlers.invalidate()
4090
4091
4092def test_collection_record_create_skips_event_handlers_when_disabled(tmp_path, monkeypatch):
4093 objects_root = tmp_path / "objects"
4094 data_dir = tmp_path / "data"
4095 schema_file = data_dir / "schemas" / "notes.json"
4096 schema_file.parent.mkdir(parents=True, exist_ok=True)
4097 schema_file.write_text(json.dumps({"fields": [{"name": "id"}]}))
4098 write_source(objects_root / "notes" / "handler.py", EVENT_HANDLER_SOURCE)
4099
4100 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
4101 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4102 monkeypatch.delenv(object_handlers.HANDLERS_ENABLED_ENV, raising=False)
4103 enable_admin_token(monkeypatch)
4104 object_handlers.invalidate()
4105
4106 create_status, _, create_payload = request(
4107 "/collections/notes/records",
4108 method="POST",
4109 body=json.dumps({"id": "n1"}).encode("utf-8"),
4110 headers=auth_headers(),
4111 )
4112
4113 # Backward-compat: with the env unset, dispatch is a no-op and the
4114 # record write itself is unaffected.
4115 assert create_status == 201
4116 assert create_payload["record"]["id"] == "n1"
4117
4118 state = object_state.ObjectStateManager("notes_handler", base_dir=str(data_dir))
4119 assert state.get("last_event") is None
4120
4121 object_handlers.invalidate()
4122
4123
4124def test_collection_record_create_survives_raising_event_handler(tmp_path, monkeypatch):
4125 objects_root = tmp_path / "objects"
4126 data_dir = tmp_path / "data"
4127 schema_file = data_dir / "schemas" / "notes.json"
4128 schema_file.parent.mkdir(parents=True, exist_ok=True)
4129 schema_file.write_text(json.dumps({"fields": [{"name": "id"}]}))
4130 write_source(
4131 objects_root / "notes" / "handler.py",
4132 'HANDLES = ["notes.record.created"]\n\n\ndef EVENT(request):\n raise RuntimeError("boom")\n',
4133 )
4134
4135 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(objects_root))
4136 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4137 monkeypatch.setenv(object_handlers.HANDLERS_ENABLED_ENV, "true")
4138 enable_admin_token(monkeypatch)
4139 object_handlers.invalidate()
4140
4141 create_status, _, create_payload = request(
4142 "/collections/notes/records",
4143 method="POST",
4144 body=json.dumps({"id": "n1"}).encode("utf-8"),
4145 headers=auth_headers(),
4146 )
4147
4148 # A handler raising must never break or roll back the triggering write.
4149 assert create_status == 201
4150 assert create_payload["record"]["id"] == "n1"
4151
4152 object_handlers.invalidate()
4153
4154
4155def test_collection_record_update_and_delete_require_admin_token_by_default(tmp_path, monkeypatch):
4156 data_dir = tmp_path / "data"
4157 write_records(data_dir, "contacts", "id\tname\nc1\tAda\nc2\tGrace\n")
4158 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4159 enable_admin_token(monkeypatch)
4160
4161 denied_status, _, denied_payload = request(
4162 "/collections/contacts/records/c1",
4163 method="PUT",
4164 body=json.dumps({"name": "Ada Lovelace"}).encode("utf-8"),
4165 )
4166 update_status, _, update_payload = request(
4167 "/collections/contacts/records/c1",
4168 method="PUT",
4169 body=json.dumps({"name": "Ada Lovelace", "email": "ada@example.com"}).encode("utf-8"),
4170 headers=auth_headers(),
4171 )
4172 delete_status, _, delete_payload = request(
4173 "/collections/contacts/records/c2",
4174 method="DELETE",
4175 headers=auth_headers(),
4176 )
4177 list_status, _, list_payload = request("/collections/contacts/records", headers=auth_headers())
4178
4179 assert denied_status == 401
4180 assert denied_payload == {"status": "error", "error": "Unauthorized"}
4181 assert update_status == 200
4182 # 63: the update response gains an opaque `_rev` (the new fingerprint) for
4183 # read-modify-write chaining; the rest of the envelope is unchanged.
4184 assert isinstance(update_payload.pop("_rev"), str)
4185 assert update_payload == {
4186 "status": "ok",
4187 "collection": "contacts",
4188 "record": {
4189 "id": "c1",
4190 "name": "Ada Lovelace",
4191 "email": "ada@example.com",
4192 },
4193 }
4194 assert delete_status == 200
4195 assert delete_payload == {
4196 "status": "ok",
4197 "collection": "contacts",
4198 "record": {"id": "c2", "name": "Grace", "email": ""},
4199 "deleted": True,
4200 }
4201 assert list_status == 200
4202 assert list_payload["records"] == [
4203 {"id": "c1", "name": "Ada Lovelace", "email": "ada@example.com"},
4204 ]
4205
4206
4207def test_collection_record_mutations_append_change_history(tmp_path, monkeypatch):
4208 data_dir = tmp_path / "data"
4209 write_records(data_dir, "contacts", "id\tname\nc1\tAda\nc2\tGrace\n")
4210 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4211 enable_admin_token(monkeypatch)
4212
4213 create_status, _, create_payload = request(
4214 "/collections/contacts/records",
4215 method="POST",
4216 body=json.dumps({"id": "c3", "name": "Katherine"}).encode("utf-8"),
4217 headers=auth_headers(),
4218 )
4219 update_status, _, update_payload = request(
4220 "/collections/contacts/records/c1",
4221 method="PUT",
4222 body=json.dumps({"name": "Ada Lovelace"}).encode("utf-8"),
4223 headers=auth_headers(),
4224 )
4225 delete_status, _, delete_payload = request(
4226 "/collections/contacts/records/c2",
4227 method="DELETE",
4228 headers=auth_headers(),
4229 )
4230
4231 assert create_status == 201
4232 assert create_payload["record"] == {"id": "c3", "name": "Katherine"}
4233 assert update_status == 200
4234 assert update_payload["record"] == {"id": "c1", "name": "Ada Lovelace"}
4235 assert delete_status == 200
4236 assert delete_payload["deleted"] is True
4237
4238 history_status, _, history_payload = request(
4239 "/collections/contacts/changes",
4240 query_string="limit=10",
4241 headers=auth_headers(),
4242 )
4243 record_status, _, record_payload = request(
4244 "/collections/contacts/records/c1/changes",
4245 headers=auth_headers(),
4246 )
4247
4248 assert history_status == 200
4249 assert history_payload["collection"] == "contacts"
4250 assert history_payload["count"] == 3
4251 assert [change["action"] for change in history_payload["changes"]] == [
4252 "delete",
4253 "update",
4254 "create",
4255 ]
4256 assert all(change["actor"] == "admin" for change in history_payload["changes"])
4257
4258 update_change = history_payload["changes"][1]
4259 assert update_change["record_id"] == "c1"
4260 assert update_change["changed_fields"] == ["name"]
4261 assert update_change["before"] == {"id": "c1", "name": "Ada"}
4262 assert update_change["after"] == {"id": "c1", "name": "Ada Lovelace"}
4263
4264 delete_change = history_payload["changes"][0]
4265 assert delete_change["record_id"] == "c2"
4266 assert delete_change["after"] is None
4267
4268 assert record_status == 200
4269 assert record_payload["record_id"] == "c1"
4270 assert record_payload["count"] == 1
4271 assert record_payload["changes"][0]["action"] == "update"
4272
4273
4274def test_collection_record_mutations_emit_exactly_one_change_each(tmp_path, monkeypatch):
4275 """HTTP API writes must produce exactly ONE change event each, attributed
4276
4277 to the API's actor -- object_records now emits the change itself as
4278 part of the write, and object_server must not also emit a second, separate
4279 change for the same mutation.
4280 """
4281 data_dir = tmp_path / "data"
4282 write_records(data_dir, "contacts", "id\tname\nc1\tAda\nc2\tGrace\n")
4283 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4284 enable_admin_token(monkeypatch)
4285
4286 create_status, _, _ = request(
4287 "/collections/contacts/records",
4288 method="POST",
4289 body=json.dumps({"id": "c3", "name": "Katherine"}).encode("utf-8"),
4290 headers=auth_headers(),
4291 )
4292 update_status, _, _ = request(
4293 "/collections/contacts/records/c1",
4294 method="PUT",
4295 body=json.dumps({"name": "Ada Lovelace"}).encode("utf-8"),
4296 headers=auth_headers(),
4297 )
4298 delete_status, _, _ = request(
4299 "/collections/contacts/records/c2",
4300 method="DELETE",
4301 headers=auth_headers(),
4302 )
4303
4304 assert create_status == 201
4305 assert update_status == 200
4306 assert delete_status == 200
4307
4308 for record_id, action in (("c3", "create"), ("c1", "update"), ("c2", "delete")):
4309 matching = object_record_changes.list_record_changes(
4310 "contacts", record_id=record_id, base_dir=data_dir
4311 )
4312 assert matching["count"] == 1, f"expected exactly one change for {record_id}"
4313 assert matching["changes"][0]["action"] == action
4314 assert matching["changes"][0]["actor"] == "admin"
4315
4316
4317def test_collection_record_mutations_publish_metadata_events(tmp_path, monkeypatch):
4318 data_dir = tmp_path / "data"
4319 write_records(data_dir, "contacts", "id\tname\nc1\tAda\nc2\tGrace\n")
4320 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4321 enable_admin_token(monkeypatch)
4322
4323 create_status, _, _ = request(
4324 "/collections/contacts/records",
4325 method="POST",
4326 body=json.dumps({"id": "c3", "name": "Katherine"}).encode("utf-8"),
4327 headers=auth_headers(),
4328 )
4329 update_status, _, _ = request(
4330 "/collections/contacts/records/c1",
4331 method="PUT",
4332 body=json.dumps({"name": "Ada Lovelace"}).encode("utf-8"),
4333 headers=auth_headers(),
4334 )
4335 delete_status, _, _ = request(
4336 "/collections/contacts/records/c2",
4337 method="DELETE",
4338 headers=auth_headers(),
4339 )
4340
4341 assert create_status == 201
4342 assert update_status == 200
4343 assert delete_status == 200
4344
4345 status, _, payload = request(
4346 "/events",
4347 query_string="limit=10",
4348 headers=auth_headers(),
4349 )
4350
4351 assert status == 200
4352 events_by_type = {event["event_type"]: event for event in payload["events"]}
4353 assert set(events_by_type) == {
4354 "collection.record.created",
4355 "collection.record.updated",
4356 "collection.record.deleted",
4357 }
4358
4359 update_event = events_by_type["collection.record.updated"]
4360 assert update_event["source"] == "record_changes"
4361 assert update_event["actor"] == "admin"
4362 assert update_event["payload"]["collection"] == "contacts"
4363 assert update_event["payload"]["record_id"] == "c1"
4364 assert update_event["payload"]["action"] == "update"
4365 assert update_event["payload"]["changed_fields"] == ["name"]
4366 assert "before" not in update_event["payload"]
4367 assert "after" not in update_event["payload"]
4368
4369 state_file = data_dir / "state" / "events" / "state.tsv"
4370 rows = state_file.read_text().splitlines()
4371 assert len(rows) == 3
4372 assert all(row.startswith("event_") for row in rows)
4373
4374
4375def test_collection_record_events_can_be_disabled(tmp_path, monkeypatch):
4376 data_dir = tmp_path / "data"
4377 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
4378 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4379 monkeypatch.setenv("DBBASIC_ENABLE_RECORD_EVENTS", "false")
4380 enable_admin_token(monkeypatch)
4381
4382 status, _, _ = request(
4383 "/collections/contacts/records",
4384 method="POST",
4385 body=json.dumps({"id": "c2", "name": "Grace"}).encode("utf-8"),
4386 headers=auth_headers(),
4387 )
4388 events_status, _, events_payload = request("/events", headers=auth_headers())
4389
4390 assert status == 201
4391 assert events_status == 200
4392 assert events_payload["events"] == []
4393
4394
4395def test_collection_record_event_publish_failure_does_not_break_mutation(
4396 tmp_path,
4397 monkeypatch,
4398):
4399 data_dir = tmp_path / "data"
4400 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
4401 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4402 enable_admin_token(monkeypatch)
4403
4404 def fail_publish(*args, **kwargs):
4405 raise OSError("event state unavailable")
4406
4407 monkeypatch.setattr(object_server.object_events, "publish_event", fail_publish)
4408
4409 status, _, payload = request(
4410 "/collections/contacts/records",
4411 method="POST",
4412 body=json.dumps({"id": "c2", "name": "Grace"}).encode("utf-8"),
4413 headers=auth_headers(),
4414 )
4415 history_status, _, history_payload = request(
4416 "/collections/contacts/changes",
4417 headers=auth_headers(),
4418 )
4419
4420 assert status == 201
4421 assert payload["record"] == {"id": "c2", "name": "Grace"}
4422 assert history_status == 200
4423 assert history_payload["changes"][0]["action"] == "create"
4424
4425
4426def test_collection_change_history_requires_admin_token(tmp_path, monkeypatch):
4427 data_dir = tmp_path / "data"
4428 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
4429 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4430 enable_admin_token(monkeypatch)
4431
4432 collection_status, _, collection_payload = request("/collections/contacts/changes")
4433 record_status, _, record_payload = request("/collections/contacts/records/c1/changes")
4434
4435 assert collection_status == 401
4436 assert collection_payload == {"status": "error", "error": "Unauthorized"}
4437 assert record_status == 401
4438 assert record_payload == {"status": "error", "error": "Unauthorized"}
4439
4440
4441def test_collection_change_history_rejects_bad_queries_and_missing_collection(tmp_path, monkeypatch):
4442 data_dir = tmp_path / "data"
4443 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
4444 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4445 enable_admin_token(monkeypatch)
4446
4447 bad_limit_status, _, bad_limit_payload = request(
4448 "/collections/contacts/changes",
4449 query_string="limit=0",
4450 headers=auth_headers(),
4451 )
4452 bad_record_status, _, bad_record_payload = request(
4453 "/collections/contacts/records/bad.name/changes",
4454 headers=auth_headers(),
4455 )
4456 missing_status, _, missing_payload = request(
4457 "/collections/missing/changes",
4458 headers=auth_headers(),
4459 )
4460
4461 assert bad_limit_status == 400
4462 assert bad_limit_payload == {
4463 "status": "error",
4464 "error": "Query parameter 'limit' must be at least 1",
4465 }
4466 assert bad_record_status == 400
4467 assert bad_record_payload == {"status": "error", "error": "Invalid record id: bad.name"}
4468 assert missing_status == 404
4469 assert missing_payload == {"status": "error", "error": "Collection not found: missing"}
4470
4471
4472def test_collection_record_update_rejects_id_change(tmp_path, monkeypatch):
4473 data_dir = tmp_path / "data"
4474 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
4475 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4476 enable_admin_token(monkeypatch)
4477
4478 status, _, payload = request(
4479 "/collections/contacts/records/c1",
4480 method="PUT",
4481 body=json.dumps({"id": "c2", "name": "Grace"}).encode("utf-8"),
4482 headers=auth_headers(),
4483 )
4484
4485 assert status == 400
4486 assert payload == {"status": "error", "error": "Record id cannot be changed"}
4487
4488
4489def test_collection_record_create_enforcement_uses_row_filter(tmp_path, monkeypatch):
4490 data_dir = tmp_path / "data"
4491 schema_file = data_dir / "schemas" / "contacts.json"
4492 schema_file.parent.mkdir(parents=True, exist_ok=True)
4493 schema_file.write_text(json.dumps({"fields": [{"name": "id"}]}))
4494 save_permission_policy(
4495 data_dir,
4496 {
4497 "access_mode": "role_based",
4498 "rules": [
4499 {
4500 "effect": "allow",
4501 "principal": "role:sales",
4502 "actions": ["create"],
4503 "collection": "contacts",
4504 "row_filter": {"owner_id": "$user_id"},
4505 }
4506 ],
4507 },
4508 )
4509 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4510 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4511 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
4512 enable_admin_token(monkeypatch)
4513 headers = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]
4514
4515 denied_status, _, denied_payload = request(
4516 "/collections/contacts/records",
4517 method="POST",
4518 body=json.dumps({"id": "c1", "name": "Bob", "owner_id": "8"}).encode("utf-8"),
4519 headers=headers,
4520 )
4521 allowed_status, _, allowed_payload = request(
4522 "/collections/contacts/records",
4523 method="POST",
4524 body=json.dumps({"id": "c2", "name": "Ada", "owner_id": "7"}).encode("utf-8"),
4525 headers=headers,
4526 )
4527
4528 assert denied_status == 403
4529 assert denied_payload == {"status": "error", "error": "no matching role rule", "code": "forbidden"}
4530 assert allowed_status == 201
4531 assert allowed_payload["record"] == {"id": "c2", "name": "Ada", "owner_id": "7"}
4532
4533
4534def test_collection_record_update_enforcement_checks_existing_and_candidate(tmp_path, monkeypatch):
4535 data_dir = tmp_path / "data"
4536 write_records(data_dir, "contacts", "id\tname\towner_id\nc1\tAda\t7\nc2\tBob\t8\n")
4537 save_permission_policy(
4538 data_dir,
4539 {
4540 "access_mode": "role_based",
4541 "rules": [
4542 {
4543 "effect": "allow",
4544 "principal": "role:sales",
4545 "actions": ["update"],
4546 "collection": "contacts",
4547 "row_filter": {"owner_id": "$user_id"},
4548 }
4549 ],
4550 },
4551 )
4552 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4553 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4554 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
4555 enable_admin_token(monkeypatch)
4556 headers = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]
4557
4558 allowed_status, _, allowed_payload = request(
4559 "/collections/contacts/records/c1",
4560 method="PUT",
4561 body=json.dumps({"name": "Ada Lovelace"}).encode("utf-8"),
4562 headers=headers,
4563 )
4564 steal_status, _, steal_payload = request(
4565 "/collections/contacts/records/c1",
4566 method="PUT",
4567 body=json.dumps({"owner_id": "8"}).encode("utf-8"),
4568 headers=headers,
4569 )
4570 other_status, _, other_payload = request(
4571 "/collections/contacts/records/c2",
4572 method="PUT",
4573 body=json.dumps({"name": "Robert"}).encode("utf-8"),
4574 headers=headers,
4575 )
4576
4577 assert allowed_status == 200
4578 assert allowed_payload["record"] == {"id": "c1", "name": "Ada Lovelace", "owner_id": "7"}
4579 assert steal_status == 403
4580 assert steal_payload == {"status": "error", "error": "no matching role rule", "code": "forbidden"}
4581 assert other_status == 403
4582 assert other_payload == {"status": "error", "error": "no matching role rule", "code": "forbidden"}
4583
4584
4585def write_schema(data_dir, collection, fields):
4586 path = data_dir / "schemas" / f"{collection}.json"
4587 path.parent.mkdir(parents=True, exist_ok=True)
4588 path.write_text(json.dumps({"fields": fields}))
4589 return path
4590
4591
4592def test_collection_record_update_enforces_transition_guard_through_http(tmp_path, monkeypatch):
4593 """FEATURE 1: a guarded transition ({"to": ..., "when": {...}}) is
4594 checked against the already-resolved request subject on the HTTP
4595 update path -- on top of, not instead of, the row-filtered update
4596 right the policy already grants."""
4597 data_dir = tmp_path / "data"
4598 write_schema(
4599 data_dir,
4600 "tickets",
4601 [
4602 {"name": "id"},
4603 {"name": "owner_id"},
4604 {
4605 "name": "status",
4606 "type": "enum",
4607 "enum": ["open", "closed"],
4608 "transitions": {"open": [{"to": "closed", "when": {"owner_id": "$user_id"}}]},
4609 },
4610 ],
4611 )
4612 write_records(data_dir, "tickets", "id\towner_id\tstatus\nt1\t7\topen\n")
4613 save_permission_policy(
4614 data_dir,
4615 {
4616 "access_mode": "role_based",
4617 "rules": [
4618 {
4619 "effect": "allow",
4620 "principal": "registered",
4621 "actions": ["update"],
4622 "collection": "tickets",
4623 }
4624 ],
4625 },
4626 )
4627 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4628 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4629 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
4630 enable_admin_token(monkeypatch)
4631
4632 denied_status, _, denied_payload = request(
4633 "/collections/tickets/records/t1",
4634 method="PUT",
4635 body=json.dumps({"status": "closed"}).encode("utf-8"),
4636 headers=[("x-dbbasic-user-id", "8")],
4637 )
4638
4639 assert denied_status == 403
4640 assert denied_payload["code"] == "forbidden"
4641 assert "cannot move from 'open' to 'closed'" in denied_payload["error"]
4642
4643 allowed_status, _, allowed_payload = request(
4644 "/collections/tickets/records/t1",
4645 method="PUT",
4646 body=json.dumps({"status": "closed"}).encode("utf-8"),
4647 headers=[("x-dbbasic-user-id", "7")],
4648 )
4649
4650 assert allowed_status == 200
4651 assert allowed_payload["record"]["status"] == "closed"
4652
4653
4654def test_writable_projects_resolves_from_write_grants_for_row_filter_and_guard(
4655 tmp_path, monkeypatch
4656):
4657 """FEATURE 2: $writable_projects narrows $accessible_projects to
4658 project_access rows with permission == "write", and it works both as
4659 a plain row filter and inside a transition guard's "when" clause."""
4660 data_dir = tmp_path / "data"
4661 write_schema(
4662 data_dir,
4663 "docs",
4664 [
4665 {"name": "id"},
4666 {"name": "project_id"},
4667 {
4668 "name": "status",
4669 "type": "enum",
4670 "enum": ["draft", "published"],
4671 "transitions": {
4672 "draft": [{"to": "published", "when": {"project_id": "$writable_projects"}}]
4673 },
4674 },
4675 ],
4676 )
4677 write_records(
4678 data_dir,
4679 "docs",
4680 "id\tproject_id\tstatus\nd1\tp1\tdraft\nd2\tp2\tdraft\n",
4681 )
4682 write_records(
4683 data_dir,
4684 "project_access",
4685 "id\tproject_id\tuser_id\tpermission\n"
4686 "g1\tp1\t7\twrite\n"
4687 "g2\tp2\t7\tread\n",
4688 )
4689 save_permission_policy(
4690 data_dir,
4691 {
4692 "access_mode": "role_based",
4693 "rules": [
4694 {
4695 "effect": "allow",
4696 "principal": "registered",
4697 "actions": ["read", "update"],
4698 "collection": "docs",
4699 "row_filter": {"project_id": "$writable_projects"},
4700 }
4701 ],
4702 },
4703 )
4704 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4705 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4706 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
4707 enable_admin_token(monkeypatch)
4708 headers = [("x-dbbasic-user-id", "7")]
4709
4710 # Row filter: only the write-granted project's doc is visible.
4711 list_status, _, list_payload = request("/collections/docs/records", headers=headers)
4712 assert list_status == 200
4713 assert [row["id"] for row in list_payload["records"]] == ["d1"]
4714
4715 # Guard: publishing the write-granted doc succeeds...
4716 allowed_status, _, allowed_payload = request(
4717 "/collections/docs/records/d1",
4718 method="PUT",
4719 body=json.dumps({"status": "published"}).encode("utf-8"),
4720 headers=headers,
4721 )
4722 assert allowed_status == 200
4723 assert allowed_payload["record"]["status"] == "published"
4724
4725 # ...but the read-only-granted project's doc is not even reachable for
4726 # update (row filter denies it before the guard is ever evaluated).
4727 denied_status, _, denied_payload = request(
4728 "/collections/docs/records/d2",
4729 method="PUT",
4730 body=json.dumps({"status": "published"}).encode("utf-8"),
4731 headers=headers,
4732 )
4733 assert denied_status == 403
4734 assert denied_payload["code"] == "forbidden"
4735
4736
4737def test_collection_record_delete_enforcement_uses_row_filter(tmp_path, monkeypatch):
4738 data_dir = tmp_path / "data"
4739 write_records(data_dir, "contacts", "id\tname\towner_id\nc1\tAda\t7\nc2\tBob\t8\n")
4740 save_permission_policy(
4741 data_dir,
4742 {
4743 "access_mode": "role_based",
4744 "rules": [
4745 {
4746 "effect": "allow",
4747 "principal": "role:sales",
4748 "actions": ["delete"],
4749 "collection": "contacts",
4750 "row_filter": {"owner_id": "$user_id"},
4751 }
4752 ],
4753 },
4754 )
4755 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4756 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4757 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
4758 enable_admin_token(monkeypatch)
4759 headers = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]
4760
4761 denied_status, _, denied_payload = request(
4762 "/collections/contacts/records/c2",
4763 method="DELETE",
4764 headers=headers,
4765 )
4766 allowed_status, _, allowed_payload = request(
4767 "/collections/contacts/records/c1",
4768 method="DELETE",
4769 headers=headers,
4770 )
4771 list_status, _, list_payload = request("/collections/contacts/records", headers=auth_headers())
4772
4773 assert denied_status == 403
4774 assert denied_payload == {"status": "error", "error": "no matching role rule", "code": "forbidden"}
4775 assert allowed_status == 200
4776 assert allowed_payload["deleted"] is True
4777 assert allowed_payload["record"] == {"id": "c1", "name": "Ada", "owner_id": "7"}
4778 assert list_status == 200
4779 assert list_payload["records"] == [{"id": "c2", "name": "Bob", "owner_id": "8"}]
4780
4781
4782def test_collection_record_writes_in_audit_mode_still_require_admin_token(tmp_path, monkeypatch):
4783 data_dir = tmp_path / "data"
4784 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
4785 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4786 monkeypatch.setenv(object_server.PERMISSION_AUDIT_ENV, "true")
4787 correlation_id = "123e4567-e89b-42d3-a456-426614174000"
4788
4789 status, _, payload = request(
4790 "/collections/contacts/records",
4791 method="POST",
4792 body=json.dumps({"id": "c2", "name": "Grace"}).encode("utf-8"),
4793 headers=[("x-dbbasic-correlation-id", correlation_id)],
4794 )
4795
4796 assert status == 403
4797 assert payload == {
4798 "status": "error",
4799 "error": "Collection record writes require DBBASIC_ADMIN_TOKEN.",
4800 }
4801 entry = object_permission_audit.get_permission_audit(data_dir)[-1]
4802 assert entry["action"] == "create"
4803 assert entry["enforced"] is False
4804 assert entry["correlation_id"] == correlation_id
4805
4806
4807def test_collection_records_enforcement_request_with_default_policy_stays_in_shadow_mode(
4808 tmp_path,
4809 monkeypatch,
4810):
4811 data_dir = tmp_path / "data"
4812 write_records(data_dir, "contacts", "id\tname\n1\tAlice\n")
4813 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4814 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4815
4816 status, _, payload = request("/collections/contacts/records")
4817
4818 assert status == 200
4819 assert payload["status"] == "ok"
4820 assert payload["collection"] == "contacts"
4821 assert payload["records"] == [{"id": "1", "name": "Alice"}]
4822 entries = object_permission_audit.get_permission_audit(data_dir)
4823 assert entries[-1]["action"] == "read"
4824 assert entries[-1]["collection"] == "contacts"
4825 assert entries[-1]["object_id"] is None
4826 assert entries[-1]["decision"]["allowed"] is False
4827 assert entries[-1]["enforced"] is False
4828 assert entries[-1]["enforcement_requested"] is True
4829 assert entries[-1]["enforcement_blocked"] is True
4830
4831
4832def test_collection_records_enforcement_can_force_default_policy(tmp_path, monkeypatch):
4833 data_dir = tmp_path / "data"
4834 write_records(data_dir, "contacts", "id\tname\n1\tAlice\n")
4835 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4836 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4837 monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true")
4838
4839 status, _, payload = request("/collections/contacts/records")
4840
4841 assert status == 403
4842 assert payload == {"status": "error", "error": "no matching role rule", "code": "forbidden"}
4843 entries = object_permission_audit.get_permission_audit(data_dir)
4844 assert entries[-1]["action"] == "read"
4845 assert entries[-1]["collection"] == "contacts"
4846 assert entries[-1]["object_id"] is None
4847 assert entries[-1]["decision"]["allowed"] is False
4848 assert entries[-1]["enforced"] is True
4849 assert entries[-1]["enforcement_requested"] is True
4850
4851
4852def test_collection_records_enforcement_filters_rows_for_trusted_subject(tmp_path, monkeypatch):
4853 data_dir = tmp_path / "data"
4854 write_records(
4855 data_dir,
4856 "contacts",
4857 "id\tname\towner_id\tsecret\n1\tAlice\t7\tred\n2\tBob\t8\tblue\n3\tCarol\t7\tgreen\n",
4858 )
4859 save_permission_policy(
4860 data_dir,
4861 {
4862 "access_mode": "role_based",
4863 "rules": [
4864 {
4865 "effect": "allow",
4866 "principal": "role:sales",
4867 "actions": ["read"],
4868 "collection": "contacts",
4869 "row_filter": {"owner_id": "$user_id"},
4870 "denied_fields": ["secret"],
4871 "reason": "sales can read own contacts",
4872 }
4873 ],
4874 },
4875 )
4876 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4877 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4878 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
4879 enable_admin_token(monkeypatch)
4880
4881 status, _, payload = request(
4882 "/collections/contacts/records",
4883 headers=[
4884 ("x-dbbasic-user-id", "7"),
4885 ("x-dbbasic-roles", "sales"),
4886 ],
4887 )
4888
4889 assert status == 200
4890 # 63 ships a rev per returned row; asserted separately so the rest of
4891 # the payload stays an exact-shape comparison.
4892 assert set(payload.pop("revs")) == {"1", "3"}
4893 assert payload == {
4894 "status": "ok",
4895 "collection": "contacts",
4896 "records": [
4897 {"id": "1", "name": "Alice", "owner_id": "7"},
4898 {"id": "3", "name": "Carol", "owner_id": "7"},
4899 ],
4900 "count": 2,
4901 "total": 2,
4902 "limit": 100,
4903 "offset": 0,
4904 "has_more": False,
4905 }
4906 entry = object_permission_audit.get_permission_audit(data_dir)[-1]
4907 assert entry["decision"]["allowed"] is True
4908 assert entry["decision"]["row_filter"] == {"owner_id": "$user_id"}
4909
4910
4911def test_collection_records_enforcement_paginates_after_row_filter(tmp_path, monkeypatch):
4912 data_dir = tmp_path / "data"
4913 write_records(
4914 data_dir,
4915 "contacts",
4916 "id\tname\towner_id\n1\tAlice\t7\n2\tBob\t8\n3\tCarol\t7\n4\tDana\t7\n",
4917 )
4918 save_permission_policy(
4919 data_dir,
4920 {
4921 "access_mode": "role_based",
4922 "rules": [
4923 {
4924 "effect": "allow",
4925 "principal": "role:sales",
4926 "actions": ["read"],
4927 "collection": "contacts",
4928 "row_filter": {"owner_id": "$user_id"},
4929 }
4930 ],
4931 },
4932 )
4933 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4934 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4935 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
4936 enable_admin_token(monkeypatch)
4937
4938 status, _, payload = request(
4939 "/collections/contacts/records",
4940 query_string="limit=1&offset=1",
4941 headers=[
4942 ("x-dbbasic-user-id", "7"),
4943 ("x-dbbasic-roles", "sales"),
4944 ],
4945 )
4946
4947 assert status == 200
4948 assert payload["records"] == [{"id": "3", "name": "Carol", "owner_id": "7"}]
4949 assert payload["count"] == 1
4950 assert payload["total"] == 3
4951 assert payload["has_more"] is True
4952
4953
4954def test_collection_record_detail_enforces_row_filter_and_fields(tmp_path, monkeypatch):
4955 data_dir = tmp_path / "data"
4956 write_records(
4957 data_dir,
4958 "contacts",
4959 "id\tname\towner_id\tsecret\n1\tAlice\t7\tred\n2\tBob\t8\tblue\n",
4960 )
4961 save_permission_policy(
4962 data_dir,
4963 {
4964 "access_mode": "role_based",
4965 "rules": [
4966 {
4967 "effect": "allow",
4968 "principal": "role:sales",
4969 "actions": ["read"],
4970 "collection": "contacts",
4971 "row_filter": {"owner_id": "$user_id"},
4972 "fields": ["id", "name", "owner_id"],
4973 }
4974 ],
4975 },
4976 )
4977 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
4978 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
4979 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
4980 enable_admin_token(monkeypatch)
4981 headers = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]
4982
4983 allowed_status, _, allowed_payload = request(
4984 "/collections/contacts/records/1",
4985 headers=headers,
4986 )
4987 denied_status, _, denied_payload = request(
4988 "/collections/contacts/records/2",
4989 headers=headers,
4990 )
4991
4992 assert allowed_status == 200
4993 # 63: opaque `_rev` sibling on the envelope (computed from the full record
4994 # before field-visibility trimming); body unchanged.
4995 assert isinstance(allowed_payload.pop("_rev"), str)
4996 assert allowed_payload == {
4997 "status": "ok",
4998 "collection": "contacts",
4999 "record": {"id": "1", "name": "Alice", "owner_id": "7"},
5000 }
5001 assert denied_status == 403
5002 assert denied_payload == {"status": "error", "error": "no matching role rule", "code": "forbidden"}
5003
5004
5005def test_collection_records_enforcement_applies_schema_field_permissions(tmp_path, monkeypatch):
5006 data_dir = tmp_path / "data"
5007 write_records(
5008 data_dir,
5009 "invoices",
5010 "id\towner_id\tmemo\tstatus\tcost_price\tmargin\n"
5011 "i1\t7\tHosting\tdraft\t100\t30\n"
5012 "i2\t8\tSupport\tsent\t200\t60\n",
5013 )
5014 schema_file = data_dir / "schemas" / "invoices.json"
5015 schema_file.parent.mkdir(parents=True, exist_ok=True)
5016 schema_file.write_text(
5017 json.dumps(
5018 {
5019 "fields": [
5020 {"name": "id"},
5021 {"name": "owner_id"},
5022 {"name": "memo", "permissions": {"sales": "edit", "admin": "edit"}},
5023 {"name": "status", "permissions": {"sales": "read", "admin": "edit"}},
5024 {"name": "cost_price", "permissions": {"sales": "hidden", "admin": "edit"}},
5025 {"name": "margin", "permissions": {"sales": "hidden", "admin": "edit"}},
5026 ]
5027 }
5028 )
5029 )
5030 save_permission_policy(
5031 data_dir,
5032 {
5033 "access_mode": "role_based",
5034 "rules": [
5035 {
5036 "effect": "allow",
5037 "principal": "role:sales",
5038 "actions": ["read"],
5039 "collection": "invoices",
5040 "row_filter": {"owner_id": "$user_id"},
5041 }
5042 ],
5043 },
5044 )
5045 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5046 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
5047 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
5048 enable_admin_token(monkeypatch)
5049 sales_headers = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]
5050
5051 list_status, _, list_payload = request("/collections/invoices/records", headers=sales_headers)
5052 detail_status, _, detail_payload = request("/collections/invoices/records/i1", headers=sales_headers)
5053 admin_status, _, admin_payload = request("/collections/invoices/records/i1", headers=auth_headers())
5054
5055 assert list_status == 200
5056 assert list_payload["records"] == [
5057 {"id": "i1", "owner_id": "7", "memo": "Hosting", "status": "draft"}
5058 ]
5059 assert detail_status == 200
5060 assert detail_payload["record"] == {
5061 "id": "i1",
5062 "owner_id": "7",
5063 "memo": "Hosting",
5064 "status": "draft",
5065 }
5066 assert admin_status == 200
5067 assert admin_payload["record"] == {
5068 "id": "i1",
5069 "owner_id": "7",
5070 "memo": "Hosting",
5071 "status": "draft",
5072 "cost_price": "100",
5073 "margin": "30",
5074 }
5075
5076
5077# --- 58 query/filter: field filtering on GET /collections/{c}/records -----
5078
5079
5080def test_collection_records_filter_eq_default_operator(tmp_path, monkeypatch):
5081 data_dir = tmp_path / "data"
5082 write_records(
5083 data_dir,
5084 "contacts",
5085 "id\tname\tstatus\nc1\tAda\thot\nc2\tGrace\tcold\nc3\tKatherine\thot\n",
5086 )
5087 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5088 enable_admin_token(monkeypatch)
5089
5090 status, _, payload = request(
5091 "/collections/contacts/records",
5092 query_string="status=hot",
5093 headers=auth_headers(),
5094 )
5095
5096 assert status == 200
5097 assert [r["id"] for r in payload["records"]] == ["c1", "c3"]
5098 assert payload["total"] == 2
5099
5100
5101def test_collection_records_filter_ne_operator(tmp_path, monkeypatch):
5102 data_dir = tmp_path / "data"
5103 write_records(
5104 data_dir,
5105 "contacts",
5106 "id\tname\tstatus\nc1\tAda\thot\nc2\tGrace\tcold\n",
5107 )
5108 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5109 enable_admin_token(monkeypatch)
5110
5111 status, _, payload = request(
5112 "/collections/contacts/records",
5113 query_string="status.ne=hot",
5114 headers=auth_headers(),
5115 )
5116
5117 assert status == 200
5118 assert [r["id"] for r in payload["records"]] == ["c2"]
5119
5120
5121def test_collection_records_filter_in_operator(tmp_path, monkeypatch):
5122 data_dir = tmp_path / "data"
5123 write_records(
5124 data_dir,
5125 "contacts",
5126 "id\tname\tstatus\nc1\tAda\topen\nc2\tGrace\tassigned\nc3\tKatherine\tclosed\n",
5127 )
5128 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5129 enable_admin_token(monkeypatch)
5130
5131 status, _, payload = request(
5132 "/collections/contacts/records",
5133 query_string="status.in=open,assigned",
5134 headers=auth_headers(),
5135 )
5136
5137 assert status == 200
5138 assert [r["id"] for r in payload["records"]] == ["c1", "c2"]
5139
5140
5141def test_collection_records_filter_range_query_ands_same_field(tmp_path, monkeypatch):
5142 data_dir = tmp_path / "data"
5143 write_records(
5144 data_dir,
5145 "postings",
5146 "id\tposted_at\np1\t2026-06-15\np2\t2026-07-10\np3\t2026-08-01\n",
5147 )
5148 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5149 enable_admin_token(monkeypatch)
5150
5151 status, _, payload = request(
5152 "/collections/postings/records",
5153 query_string="posted_at.gte=2026-07-01&posted_at.lte=2026-07-31",
5154 headers=auth_headers(),
5155 )
5156
5157 assert status == 200
5158 assert [r["id"] for r in payload["records"]] == ["p2"]
5159
5160
5161def test_collection_records_filter_gt_lt_operators(tmp_path, monkeypatch):
5162 data_dir = tmp_path / "data"
5163 write_records(data_dir, "deals", "id\tamount\nd1\t50\nd2\t100\nd3\t150\n")
5164 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5165 enable_admin_token(monkeypatch)
5166
5167 gt_status, _, gt_payload = request(
5168 "/collections/deals/records", query_string="amount.gt=100", headers=auth_headers()
5169 )
5170 lt_status, _, lt_payload = request(
5171 "/collections/deals/records", query_string="amount.lt=100", headers=auth_headers()
5172 )
5173
5174 assert gt_status == 200
5175 assert [r["id"] for r in gt_payload["records"]] == ["d3"]
5176 assert lt_status == 200
5177 assert [r["id"] for r in lt_payload["records"]] == ["d1"]
5178
5179
5180def test_collection_records_filter_ignores_reserved_params(tmp_path, monkeypatch):
5181 data_dir = tmp_path / "data"
5182 write_records(
5183 data_dir,
5184 "contacts",
5185 "id\tname\tstatus\nc1\tAda\thot\nc2\tGrace\tcold\n",
5186 )
5187 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5188 enable_admin_token(monkeypatch)
5189
5190 status, _, payload = request(
5191 "/collections/contacts/records",
5192 query_string="status=hot&sort=-name&q=anything&limit=10&offset=0",
5193 headers=auth_headers(),
5194 )
5195
5196 # sort/q/limit/offset keep their own meaning (or are simply not yet
5197 # implemented) rather than being rejected as unknown filter fields.
5198 assert status == 200
5199 assert [r["id"] for r in payload["records"]] == ["c1"]
5200
5201
5202def test_collection_records_filter_matching_nothing_is_empty_not_an_error(tmp_path, monkeypatch):
5203 data_dir = tmp_path / "data"
5204 write_records(data_dir, "contacts", "id\tname\tstatus\nc1\tAda\thot\n")
5205 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5206 enable_admin_token(monkeypatch)
5207
5208 status, _, payload = request(
5209 "/collections/contacts/records",
5210 query_string="status=nonexistent",
5211 headers=auth_headers(),
5212 )
5213
5214 assert status == 200
5215 assert payload["records"] == []
5216 assert payload["total"] == 0
5217
5218
5219def test_collection_records_filter_unknown_field_returns_400(tmp_path, monkeypatch):
5220 data_dir = tmp_path / "data"
5221 write_records(data_dir, "contacts", "id\tname\tstatus\nc1\tAda\thot\n")
5222 schema_file = data_dir / "schemas" / "contacts.json"
5223 schema_file.parent.mkdir(parents=True, exist_ok=True)
5224 schema_file.write_text(
5225 json.dumps({"fields": [{"name": "id"}, {"name": "name"}, {"name": "status"}]})
5226 )
5227 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5228 enable_admin_token(monkeypatch)
5229
5230 status, _, payload = request(
5231 "/collections/contacts/records",
5232 query_string="nickname=Ada",
5233 headers=auth_headers(),
5234 )
5235
5236 assert status == 400
5237 assert payload["status"] == "error"
5238 assert payload["code"] == "invalid_filter"
5239 assert payload["param"] == "nickname"
5240
5241
5242def test_collection_records_filter_unknown_operator_returns_400(tmp_path, monkeypatch):
5243 data_dir = tmp_path / "data"
5244 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
5245 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5246 enable_admin_token(monkeypatch)
5247
5248 status, _, payload = request(
5249 "/collections/contacts/records",
5250 query_string="name.like=Ad",
5251 headers=auth_headers(),
5252 )
5253
5254 assert status == 400
5255 assert payload["code"] == "invalid_filter"
5256 assert payload["param"] == "name.like"
5257
5258
5259def test_collection_records_filter_bad_type_value_returns_400(tmp_path, monkeypatch):
5260 data_dir = tmp_path / "data"
5261 write_records(data_dir, "contacts", "id\tname\ttotal\nc1\tAda\t150\n")
5262 schema_file = data_dir / "schemas" / "contacts.json"
5263 schema_file.parent.mkdir(parents=True, exist_ok=True)
5264 schema_file.write_text(
5265 json.dumps(
5266 {"fields": [{"name": "id"}, {"name": "name"}, {"name": "total", "type": "integer"}]}
5267 )
5268 )
5269 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5270 enable_admin_token(monkeypatch)
5271
5272 status, _, payload = request(
5273 "/collections/contacts/records",
5274 query_string="total=not-a-number",
5275 headers=auth_headers(),
5276 )
5277
5278 assert status == 400
5279 assert payload["code"] == "invalid_filter"
5280 assert payload["param"] == "total"
5281
5282
5283def test_collection_records_filter_ordered_op_on_unsupported_type_returns_400(tmp_path, monkeypatch):
5284 data_dir = tmp_path / "data"
5285 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
5286 schema_file = data_dir / "schemas" / "contacts.json"
5287 schema_file.parent.mkdir(parents=True, exist_ok=True)
5288 schema_file.write_text(json.dumps({"fields": [{"name": "id"}, {"name": "name"}]}))
5289 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5290 enable_admin_token(monkeypatch)
5291
5292 status, _, payload = request(
5293 "/collections/contacts/records",
5294 query_string="name.gte=A",
5295 headers=auth_headers(),
5296 )
5297
5298 assert status == 400
5299 assert payload["code"] == "invalid_filter"
5300 assert payload["param"] == "name.gte"
5301
5302
5303def test_collection_records_filter_in_list_cap_returns_400(tmp_path, monkeypatch):
5304 data_dir = tmp_path / "data"
5305 write_records(data_dir, "contacts", "id\tstatus\nc1\thot\n")
5306 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5307 enable_admin_token(monkeypatch)
5308
5309 too_many = ",".join(f"v{i}" for i in range(object_server.FILTER_IN_MAX_VALUES + 1))
5310 status, _, payload = request(
5311 "/collections/contacts/records",
5312 query_string=f"status.in={too_many}",
5313 headers=auth_headers(),
5314 )
5315
5316 assert status == 400
5317 assert payload["code"] == "invalid_filter"
5318 assert payload["param"] == "status.in"
5319
5320
5321def test_collection_records_filter_in_list_rejects_blank_items(tmp_path, monkeypatch):
5322 data_dir = tmp_path / "data"
5323 write_records(data_dir, "contacts", "id\tstatus\nc1\thot\n")
5324 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5325 enable_admin_token(monkeypatch)
5326
5327 status, _, payload = request(
5328 "/collections/contacts/records",
5329 query_string="status.in=hot,,cold",
5330 headers=auth_headers(),
5331 )
5332
5333 assert status == 400
5334 assert payload["code"] == "invalid_filter"
5335 assert payload["param"] == "status.in"
5336
5337
5338def test_collection_records_filter_disabled_degrades_to_unfiltered(tmp_path, monkeypatch):
5339 data_dir = tmp_path / "data"
5340 write_records(
5341 data_dir,
5342 "contacts",
5343 "id\tname\tstatus\nc1\tAda\thot\nc2\tGrace\tcold\n",
5344 )
5345 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5346 monkeypatch.setenv(object_server.FILTERING_ENABLED_ENV, "false")
5347 enable_admin_token(monkeypatch)
5348
5349 status, _, payload = request(
5350 "/collections/contacts/records",
5351 query_string="status=hot",
5352 headers=auth_headers(),
5353 )
5354
5355 # Degrades to unfiltered (both rows), never a 400 -- 58's Degradation:
5356 # turning the flag off can't break a page that already added a filter.
5357 assert status == 200
5358 assert [r["id"] for r in payload["records"]] == ["c1", "c2"]
5359
5360
5361def test_collection_records_filter_disabled_still_400s_on_unrelated_errors(tmp_path, monkeypatch):
5362 """Filtering-disabled only ignores filter PARAMS; it doesn't relax
5363 unrelated validation like limit/offset."""
5364 data_dir = tmp_path / "data"
5365 write_records(data_dir, "contacts", "id\tname\nc1\tAda\n")
5366 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5367 monkeypatch.setenv(object_server.FILTERING_ENABLED_ENV, "false")
5368 enable_admin_token(monkeypatch)
5369
5370 status, _, payload = request(
5371 "/collections/contacts/records",
5372 query_string="limit=0&status=hot",
5373 headers=auth_headers(),
5374 )
5375
5376 assert status == 400
5377 assert payload["error"] == "Query parameter 'limit' must be at least 1"
5378
5379
5380def test_admin_status_reports_filtering_capability(tmp_path, monkeypatch):
5381 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
5382 enable_admin_token(monkeypatch)
5383
5384 status, _, payload = request("/admin/status", headers=auth_headers())
5385
5386 assert status == 200
5387 assert payload["capabilities"]["filtering"] == {
5388 "enabled": True,
5389 "env": "DBBASIC_ENABLE_FILTERING",
5390 }
5391
5392
5393# --- 58 SECURITY properties: filter can only narrow, never widen ---------
5394
5395
5396def test_collection_records_filter_never_leaks_across_row_filter_boundary(tmp_path, monkeypatch):
5397 """A field filter can only narrow the row-permission-filtered set,
5398 never widen it. Filtering for a value that only exists on a row
5399 outside the subject's row filter (a different owner) must come back
5400 empty -- never that other owner's row -- even though the field itself
5401 (`name`) is fully readable, not hidden."""
5402 data_dir = tmp_path / "data"
5403 write_records(
5404 data_dir,
5405 "contacts",
5406 "id\tname\towner_id\n1\tAlice\t7\n2\tBob\t8\n3\tCarol\t7\n",
5407 )
5408 save_permission_policy(
5409 data_dir,
5410 {
5411 "access_mode": "role_based",
5412 "rules": [
5413 {
5414 "effect": "allow",
5415 "principal": "role:sales",
5416 "actions": ["read"],
5417 "collection": "contacts",
5418 "row_filter": {"owner_id": "$user_id"},
5419 }
5420 ],
5421 },
5422 )
5423 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5424 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
5425 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
5426 enable_admin_token(monkeypatch)
5427 headers = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]
5428
5429 # "Bob" (id 2) belongs to owner_id 8 -- outside subject 7's row filter.
5430 out_of_scope_status, _, out_of_scope_payload = request(
5431 "/collections/contacts/records",
5432 query_string="name=Bob",
5433 headers=headers,
5434 )
5435 # An in-scope filter still works normally for the same subject.
5436 in_scope_status, _, in_scope_payload = request(
5437 "/collections/contacts/records",
5438 query_string="name=Alice",
5439 headers=headers,
5440 )
5441 # And an admin (bypasses row filtering entirely) really can reach Bob,
5442 # proving the row filter -- not some other accident -- is what hid him
5443 # from the sales subject above.
5444 admin_status, _, admin_payload = request(
5445 "/collections/contacts/records",
5446 query_string="name=Bob",
5447 headers=auth_headers(),
5448 )
5449
5450 assert out_of_scope_status == 200
5451 assert out_of_scope_payload["records"] == []
5452 assert out_of_scope_payload["total"] == 0
5453
5454 assert in_scope_status == 200
5455 assert [r["id"] for r in in_scope_payload["records"]] == ["1"]
5456
5457 assert admin_status == 200
5458 assert [r["id"] for r in admin_payload["records"]] == ["2"]
5459
5460
5461def test_collection_records_filter_denied_field_from_matched_rule_returns_400(tmp_path, monkeypatch):
5462 """Filterable fields = readable fields (58's Permissions Posture),
5463 checked against the matched row-permission rule's own denied_fields --
5464 not just schema-level hidden fields."""
5465 data_dir = tmp_path / "data"
5466 write_records(
5467 data_dir,
5468 "contacts",
5469 "id\tname\towner_id\tsecret\n1\tAlice\t7\tred\n2\tBob\t8\tblue\n",
5470 )
5471 save_permission_policy(
5472 data_dir,
5473 {
5474 "access_mode": "role_based",
5475 "rules": [
5476 {
5477 "effect": "allow",
5478 "principal": "role:sales",
5479 "actions": ["read"],
5480 "collection": "contacts",
5481 "row_filter": {"owner_id": "$user_id"},
5482 "denied_fields": ["secret"],
5483 }
5484 ],
5485 },
5486 )
5487 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5488 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
5489 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
5490 enable_admin_token(monkeypatch)
5491 headers = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]
5492
5493 denied_status, _, denied_payload = request(
5494 "/collections/contacts/records",
5495 query_string="secret=red",
5496 headers=headers,
5497 )
5498 allowed_status, _, allowed_payload = request(
5499 "/collections/contacts/records",
5500 query_string="name=Alice",
5501 headers=headers,
5502 )
5503
5504 assert denied_status == 400
5505 assert denied_payload["code"] == "invalid_filter"
5506 assert denied_payload["param"] == "secret"
5507
5508 assert allowed_status == 200
5509 assert [r["id"] for r in allowed_payload["records"]] == ["1"]
5510
5511
5512def test_collection_records_filter_hidden_field_rejected_and_admin_bypasses(tmp_path, monkeypatch):
5513 """58's Permissions Posture, verbatim: a field hidden by schema is not
5514 filterable by a non-privileged subject (400, not a silent empty
5515 result -- the inference-channel guard: probing a hidden field's value
5516 via filter results would otherwise leak it). An admin-role subject
5517 bypasses that gate entirely, exactly like the permission engine's own
5518 row-level admin short-circuit already bypasses rule matching -- even
5519 when the schema grants admin no explicit exception for the field."""
5520 data_dir = tmp_path / "data"
5521 write_records(
5522 data_dir,
5523 "invoices",
5524 "id\towner_id\tmemo\tcost_price\ni1\t7\tHosting\t100\ni2\t7\tDomain\t9\n",
5525 )
5526 schema_file = data_dir / "schemas" / "invoices.json"
5527 schema_file.parent.mkdir(parents=True, exist_ok=True)
5528 schema_file.write_text(
5529 json.dumps(
5530 {
5531 "fields": [
5532 {"name": "id"},
5533 {"name": "owner_id"},
5534 {"name": "memo"},
5535 # Hidden for EVERYONE -- no admin exception carved out.
5536 {"name": "cost_price", "type": "integer", "permissions": {"default": "hidden"}},
5537 ]
5538 }
5539 )
5540 )
5541 save_permission_policy(
5542 data_dir,
5543 {
5544 "access_mode": "role_based",
5545 "rules": [
5546 {
5547 "effect": "allow",
5548 "principal": "role:sales",
5549 "actions": ["read"],
5550 "collection": "invoices",
5551 "row_filter": {"owner_id": "$user_id"},
5552 }
5553 ],
5554 },
5555 )
5556 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5557 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
5558 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
5559 enable_admin_token(monkeypatch)
5560
5561 sales_status, _, sales_payload = request(
5562 "/collections/invoices/records",
5563 query_string="cost_price=100",
5564 headers=[("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")],
5565 )
5566 # role:admin via trusted headers -- no admin TOKEN, no explicit schema
5567 # exception for cost_price, and no rule in the policy for role:admin
5568 # at all: the ONLY thing making this work is check_permission's (and
5569 # now _filterable_field_predicate's) admin-role short-circuit.
5570 admin_status, _, admin_payload = request(
5571 "/collections/invoices/records",
5572 query_string="cost_price=100",
5573 headers=[("x-dbbasic-user-id", "1"), ("x-dbbasic-roles", "admin")],
5574 )
5575
5576 assert sales_status == 400
5577 assert sales_payload["code"] == "invalid_filter"
5578 assert sales_payload["param"] == "cost_price"
5579
5580 assert admin_status == 200
5581 assert [r["id"] for r in admin_payload["records"]] == ["i1"]
5582
5583
5584def test_collection_records_filter_admin_token_bypasses_hidden_field_gate(tmp_path, monkeypatch):
5585 """Same as the role:admin case above, but via the raw admin-token
5586 bearer (which resolves to a subject with role "admin" -- see
5587 _permission_identity) rather than a trusted-header role."""
5588 data_dir = tmp_path / "data"
5589 write_records(data_dir, "invoices", "id\tcost_price\ni1\t100\ni2\t9\n")
5590 schema_file = data_dir / "schemas" / "invoices.json"
5591 schema_file.parent.mkdir(parents=True, exist_ok=True)
5592 schema_file.write_text(
5593 json.dumps(
5594 {
5595 "fields": [
5596 {"name": "id"},
5597 {"name": "cost_price", "type": "integer", "permissions": {"default": "hidden"}},
5598 ]
5599 }
5600 )
5601 )
5602 save_permission_policy(
5603 data_dir,
5604 {"access_mode": "role_based", "rules": []},
5605 )
5606 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5607 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
5608 enable_admin_token(monkeypatch)
5609
5610 status, _, payload = request(
5611 "/collections/invoices/records",
5612 query_string="cost_price=100",
5613 headers=auth_headers(),
5614 )
5615
5616 assert status == 200
5617 assert [r["id"] for r in payload["records"]] == ["i1"]
5618
5619
5620def test_collection_record_update_enforces_schema_edit_permissions(tmp_path, monkeypatch):
5621 data_dir = tmp_path / "data"
5622 write_records(data_dir, "invoices", "id\towner_id\tmemo\tstatus\tmargin\ni1\t7\tHosting\tdraft\t30\n")
5623 schema_file = data_dir / "schemas" / "invoices.json"
5624 schema_file.parent.mkdir(parents=True, exist_ok=True)
5625 schema_file.write_text(
5626 json.dumps(
5627 {
5628 "fields": [
5629 {"name": "id"},
5630 {"name": "owner_id"},
5631 {"name": "memo", "permissions": {"sales": "edit", "admin": "edit"}},
5632 {"name": "status", "permissions": {"sales": "read", "admin": "edit"}},
5633 {"name": "margin", "permissions": {"sales": "hidden", "admin": "edit"}},
5634 ]
5635 }
5636 )
5637 )
5638 save_permission_policy(
5639 data_dir,
5640 {
5641 "access_mode": "role_based",
5642 "rules": [
5643 {
5644 "effect": "allow",
5645 "principal": "role:sales",
5646 "actions": ["update", "read"],
5647 "collection": "invoices",
5648 "row_filter": {"owner_id": "$user_id"},
5649 }
5650 ],
5651 },
5652 )
5653 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5654 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
5655 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
5656 enable_admin_token(monkeypatch)
5657 sales_headers = [("x-dbbasic-user-id", "7"), ("x-dbbasic-roles", "sales")]
5658
5659 allowed_status, _, allowed_payload = request(
5660 "/collections/invoices/records/i1",
5661 method="PUT",
5662 body=json.dumps({"memo": "Managed hosting"}).encode("utf-8"),
5663 headers=sales_headers,
5664 )
5665 read_only_status, _, read_only_payload = request(
5666 "/collections/invoices/records/i1",
5667 method="PUT",
5668 body=json.dumps({"status": "sent"}).encode("utf-8"),
5669 headers=sales_headers,
5670 )
5671 hidden_status, _, hidden_payload = request(
5672 "/collections/invoices/records/i1",
5673 method="PUT",
5674 body=json.dumps({"margin": "45"}).encode("utf-8"),
5675 headers=sales_headers,
5676 )
5677 admin_status, _, admin_payload = request(
5678 "/collections/invoices/records/i1",
5679 method="PUT",
5680 body=json.dumps({"status": "sent", "margin": "45"}).encode("utf-8"),
5681 headers=auth_headers(),
5682 )
5683
5684 assert allowed_status == 200
5685 assert allowed_payload["record"]["memo"] == "Managed hosting"
5686 assert read_only_status == 403
5687 assert read_only_payload == {
5688 "status": "error",
5689 "error": "Record field 'status' is not editable for this subject",
5690 "code": "forbidden",
5691 "denied_fields": ["status"],
5692 }
5693 assert hidden_status == 403
5694 assert hidden_payload == {
5695 "status": "error",
5696 "error": "Record field 'margin' is not editable for this subject",
5697 "code": "forbidden",
5698 "denied_fields": ["margin"],
5699 }
5700 assert admin_status == 200
5701 assert admin_payload["record"]["status"] == "sent"
5702 assert admin_payload["record"]["margin"] == "45"
5703
5704
5705def test_collection_records_enforcement_returns_payment_required(tmp_path, monkeypatch):
5706 data_dir = tmp_path / "data"
5707 write_records(data_dir, "reports", "id\ttitle\n1\tRevenue\n")
5708 save_permission_policy(data_dir, {"access_mode": "subscription"})
5709 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5710 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
5711 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
5712 enable_admin_token(monkeypatch)
5713
5714 status, _, payload = request(
5715 "/collections/reports/records",
5716 headers=[("x-dbbasic-user-id", "7")],
5717 )
5718
5719 assert status == 402
5720 assert payload == {"status": "error", "error": "subscription required", "code": "payment_required"}
5721
5722
5723def test_collection_records_audit_mode_logs_without_filtering(tmp_path, monkeypatch):
5724 data_dir = tmp_path / "data"
5725 write_records(data_dir, "contacts", "id\tname\n1\tAlice\n")
5726 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5727 monkeypatch.setenv(object_server.PERMISSION_AUDIT_ENV, "true")
5728
5729 status, _, payload = request("/collections/contacts/records")
5730
5731 assert status == 200
5732 assert payload["records"] == [{"id": "1", "name": "Alice"}]
5733 entry = object_permission_audit.get_permission_audit(data_dir)[-1]
5734 assert entry["collection"] == "contacts"
5735 assert entry["action"] == "read"
5736 assert entry["decision"]["allowed"] is False
5737 assert entry["enforced"] is False
5738
5739
5740def test_schema_list_requires_admin_token_configuration(tmp_path, monkeypatch):
5741 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
5742 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
5743
5744 status, _, payload = request("/schemas")
5745
5746 assert status == 403
5747 assert payload == {"status": "error", "error": "Schema listing requires DBBASIC_ADMIN_TOKEN."}
5748
5749
5750def test_schema_list_requires_authorization_header(tmp_path, monkeypatch):
5751 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
5752 enable_admin_token(monkeypatch)
5753
5754 status, _, payload = request("/schemas")
5755
5756 assert status == 401
5757 assert payload == {"status": "error", "error": "Unauthorized"}
5758
5759
5760def test_schema_list_returns_manual_and_derived_summaries(tmp_path, monkeypatch):
5761 root = tmp_path / "objects"
5762 data_dir = tmp_path / "data"
5763 write_source(root / "contacts" / "directory.py", "def GET(request):\n return {}\n")
5764 schema_file = data_dir / "schemas" / "invoices.json"
5765 schema_file.parent.mkdir(parents=True, exist_ok=True)
5766 schema_file.write_text(
5767 json.dumps(
5768 {
5769 "title": "Invoices",
5770 "fields": [
5771 {"name": "invoice_date", "type": "date", "required": True},
5772 {"name": "total", "type": "computed"},
5773 ],
5774 }
5775 )
5776 )
5777 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
5778 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5779 enable_admin_token(monkeypatch)
5780
5781 status, _, payload = request("/schemas", headers=auth_headers())
5782
5783 assert status == 200
5784 assert payload == {
5785 "status": "ok",
5786 "schemas": [
5787 {
5788 "name": "contacts",
5789 "title": "Contacts",
5790 "source": "derived",
5791 "version": 1,
5792 "field_count": 0,
5793 },
5794 {
5795 "name": "invoices",
5796 "title": "Invoices",
5797 "source": "manual",
5798 "version": 1,
5799 "field_count": 2,
5800 },
5801 ],
5802 "count": 2,
5803 }
5804
5805
5806def test_schema_detail_returns_manual_schema(tmp_path, monkeypatch):
5807 data_dir = tmp_path / "data"
5808 schema_file = data_dir / "schemas" / "invoices.json"
5809 schema_file.parent.mkdir(parents=True, exist_ok=True)
5810 schema_file.write_text(
5811 json.dumps(
5812 {
5813 "title": "Invoices",
5814 "fields": [
5815 {
5816 "name": "customer_id",
5817 "type": "relation",
5818 "relation": {"collection": "contacts"},
5819 "required": True,
5820 }
5821 ],
5822 }
5823 )
5824 )
5825 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5826 enable_admin_token(monkeypatch)
5827
5828 status, _, payload = request("/schemas/invoices", headers=auth_headers())
5829
5830 assert status == 200
5831 assert payload == {
5832 "status": "ok",
5833 "schema": {
5834 "name": "invoices",
5835 "title": "Invoices",
5836 "source": "manual",
5837 "version": 1,
5838 "fields": [
5839 {
5840 "name": "customer_id",
5841 "type": "relation",
5842 "required": True,
5843 "relation": {"collection": "contacts"},
5844 }
5845 ],
5846 "field_count": 1,
5847 },
5848 }
5849
5850
5851def test_schema_detail_returns_derived_schema_for_collection(tmp_path, monkeypatch):
5852 root = tmp_path / "objects"
5853 data_dir = tmp_path / "data"
5854 write_source(root / "contacts" / "directory.py", "def GET(request):\n return {}\n")
5855 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
5856 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5857 enable_admin_token(monkeypatch)
5858
5859 status, _, payload = request("/schemas/contacts", headers=auth_headers())
5860
5861 assert status == 200
5862 assert payload == {
5863 "status": "ok",
5864 "schema": {
5865 "name": "contacts",
5866 "title": "Contacts",
5867 "source": "derived",
5868 "version": 1,
5869 "fields": [],
5870 "field_count": 0,
5871 },
5872 }
5873
5874
5875def test_schema_put_requires_admin_token_configuration(tmp_path, monkeypatch):
5876 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
5877 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
5878
5879 status, _, payload = request("/schemas/invoices", method="PUT", body=b"{}")
5880
5881 assert status == 403
5882 assert payload == {"status": "error", "error": "Schema writes require DBBASIC_ADMIN_TOKEN."}
5883
5884
5885def test_schema_put_requires_authorization_header(tmp_path, monkeypatch):
5886 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
5887 enable_admin_token(monkeypatch)
5888
5889 status, _, payload = request("/schemas/invoices", method="PUT", body=b"{}")
5890
5891 assert status == 401
5892 assert payload == {"status": "error", "error": "Unauthorized"}
5893
5894
5895def test_schema_put_writes_manual_schema(tmp_path, monkeypatch):
5896 data_dir = tmp_path / "data"
5897 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5898 enable_admin_token(monkeypatch)
5899
5900 body = json.dumps(
5901 {
5902 "title": "Invoices",
5903 "ui": {"default_view": "form"},
5904 "views": [{"name": "invoice_admin", "type": "form"}],
5905 "fields": [
5906 {
5907 "name": "invoice_date",
5908 "type": "date",
5909 "required": True,
5910 "layout": {"column": 1},
5911 },
5912 {
5913 "name": "margin",
5914 "type": "currency",
5915 "permissions": {"admin": "edit", "sales": "hidden"},
5916 },
5917 ],
5918 }
5919 ).encode()
5920
5921 status, _, payload = request(
5922 "/schemas/invoices",
5923 method="PUT",
5924 body=body,
5925 headers=auth_headers(),
5926 )
5927 detail_status, _, detail_payload = request("/schemas/invoices", headers=auth_headers())
5928
5929 assert status == 200
5930 assert payload == {
5931 "status": "ok",
5932 "message": "Schema updated to version 1",
5933 "version_id": 1,
5934 "collection": "invoices",
5935 "schema": {
5936 "name": "invoices",
5937 "title": "Invoices",
5938 "source": "manual",
5939 "version": 1,
5940 "fields": [
5941 {
5942 "name": "invoice_date",
5943 "type": "date",
5944 "required": True,
5945 "layout": {"column": 1},
5946 },
5947 {
5948 "name": "margin",
5949 "type": "currency",
5950 "required": False,
5951 "permissions": {"admin": "edit", "sales": "hidden"},
5952 },
5953 ],
5954 "field_count": 2,
5955 "ui": {"default_view": "form"},
5956 "views": [{"name": "invoice_admin", "type": "form"}],
5957 },
5958 }
5959 assert detail_status == 200
5960 assert detail_payload == {"status": "ok", "schema": payload["schema"]}
5961 assert (data_dir / "schemas" / "invoices.json").exists()
5962 assert (data_dir / "schema_versions" / "invoices" / "v1.json").exists()
5963
5964
5965def test_schema_put_accepts_nested_schema_payload(tmp_path, monkeypatch):
5966 data_dir = tmp_path / "data"
5967 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5968 enable_admin_token(monkeypatch)
5969
5970 status, _, payload = request(
5971 "/schemas/contacts",
5972 method="PUT",
5973 body=json.dumps({"schema": {"fields": [{"name": "email", "type": "email"}]}}).encode(),
5974 headers=auth_headers(),
5975 )
5976
5977 assert status == 200
5978 assert payload["schema"]["name"] == "contacts"
5979 assert payload["schema"]["fields"] == [
5980 {"name": "email", "type": "email", "required": False}
5981 ]
5982
5983
5984def test_schema_versions_endpoint_lists_history_newest_first(tmp_path, monkeypatch):
5985 data_dir = tmp_path / "data"
5986 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
5987 enable_admin_token(monkeypatch)
5988
5989 request(
5990 "/schemas/invoices",
5991 method="PUT",
5992 body=json.dumps(
5993 {
5994 "schema": {"fields": [{"name": "invoice_date", "type": "date"}]},
5995 "author": "admin",
5996 "message": "first schema",
5997 }
5998 ).encode(),
5999 headers=auth_headers(),
6000 )
6001 request(
6002 "/schemas/invoices",
6003 method="PUT",
6004 body=json.dumps(
6005 {
6006 "schema": {"fields": [{"name": "invoice_date", "type": "date"}, {"name": "total"}]},
6007 "author": "admin",
6008 "message": "second schema",
6009 }
6010 ).encode(),
6011 headers=auth_headers(),
6012 )
6013
6014 status, _, payload = request(
6015 "/schemas/invoices",
6016 query_string="versions=true&limit=10",
6017 headers=auth_headers(),
6018 )
6019 limited_status, _, limited_payload = request(
6020 "/schemas/invoices",
6021 query_string="versions=true&limit=1",
6022 headers=auth_headers(),
6023 )
6024
6025 assert status == 200
6026 assert payload["collection"] == "invoices"
6027 assert [version["version_id"] for version in payload["versions"]] == [2, 1]
6028 assert [version["message"] for version in payload["versions"]] == [
6029 "second schema",
6030 "first schema",
6031 ]
6032 assert all("content" not in version for version in payload["versions"])
6033 assert limited_status == 200
6034 assert [version["version_id"] for version in limited_payload["versions"]] == [2]
6035
6036
6037def test_schema_versions_endpoint_requires_authorization_header(tmp_path, monkeypatch):
6038 data_dir = tmp_path / "data"
6039 (data_dir / "schemas").mkdir(parents=True)
6040 (data_dir / "schemas" / "invoices.json").write_text('{"fields": []}\n')
6041 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6042 enable_admin_token(monkeypatch)
6043
6044 status, _, payload = request("/schemas/invoices", query_string="versions=true")
6045
6046 assert status == 401
6047 assert payload == {"status": "error", "error": "Unauthorized"}
6048
6049
6050def test_schema_version_endpoint_returns_content_and_schema(tmp_path, monkeypatch):
6051 data_dir = tmp_path / "data"
6052 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6053 enable_admin_token(monkeypatch)
6054
6055 request(
6056 "/schemas/invoices",
6057 method="PUT",
6058 body=json.dumps(
6059 {
6060 "schema": {
6061 "title": "Invoices",
6062 "fields": [{"name": "invoice_date", "type": "date"}],
6063 },
6064 "author": "admin",
6065 "message": "first schema",
6066 }
6067 ).encode(),
6068 headers=auth_headers(),
6069 )
6070
6071 status, _, payload = request(
6072 "/schemas/invoices",
6073 query_string="version=1",
6074 headers=auth_headers(),
6075 )
6076
6077 assert status == 200
6078 assert payload["collection"] == "invoices"
6079 assert payload["version"]["version_id"] == 1
6080 assert payload["version"]["message"] == "first schema"
6081 assert payload["version"]["schema"]["fields"] == [
6082 {"name": "invoice_date", "type": "date", "required": False}
6083 ]
6084 assert '"invoice_date"' in payload["version"]["content"]
6085
6086
6087def test_schema_rollback_creates_new_latest_version(tmp_path, monkeypatch):
6088 data_dir = tmp_path / "data"
6089 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6090 enable_admin_token(monkeypatch)
6091
6092 request(
6093 "/schemas/invoices",
6094 method="PUT",
6095 body=json.dumps({"fields": [{"name": "invoice_date", "type": "date"}]}).encode(),
6096 headers=auth_headers(),
6097 )
6098 request(
6099 "/schemas/invoices",
6100 method="PUT",
6101 body=json.dumps({"fields": [{"name": "invoice_date", "type": "date"}, {"name": "total"}]}).encode(),
6102 headers=auth_headers(),
6103 )
6104
6105 status, _, payload = request(
6106 "/schemas/invoices",
6107 method="POST",
6108 body=json.dumps(
6109 {
6110 "action": "rollback",
6111 "version_id": 1,
6112 "author": "admin",
6113 "message": "restore first",
6114 }
6115 ).encode(),
6116 headers=auth_headers(),
6117 )
6118 detail_status, _, detail_payload = request("/schemas/invoices", headers=auth_headers())
6119 history_status, _, history_payload = request(
6120 "/schemas/invoices",
6121 query_string="versions=true&limit=10",
6122 headers=auth_headers(),
6123 )
6124
6125 assert status == 200
6126 assert payload["message"] == "Rolled back schema to version 1"
6127 assert payload["version_id"] == 1
6128 assert payload["new_version_id"] == 3
6129 assert payload["schema"]["fields"] == [
6130 {"name": "invoice_date", "type": "date", "required": False}
6131 ]
6132 assert detail_status == 200
6133 assert detail_payload["schema"]["fields"] == payload["schema"]["fields"]
6134 assert history_status == 200
6135 assert [version["version_id"] for version in history_payload["versions"]] == [3, 2, 1]
6136 assert history_payload["versions"][0]["message"] == "restore first"
6137
6138
6139def test_schema_rollback_returns_404_for_missing_version(tmp_path, monkeypatch):
6140 data_dir = tmp_path / "data"
6141 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6142 enable_admin_token(monkeypatch)
6143
6144 status, _, payload = request(
6145 "/schemas/invoices",
6146 method="POST",
6147 body=json.dumps({"action": "rollback", "version_id": 99}).encode(),
6148 headers=auth_headers(),
6149 )
6150
6151 assert status == 404
6152 assert payload == {
6153 "status": "error",
6154 "error": "Version 99 not found for schema invoices",
6155 }
6156
6157
6158def test_schema_put_rejects_invalid_payload(tmp_path, monkeypatch):
6159 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6160 enable_admin_token(monkeypatch)
6161
6162 name_status, _, name_payload = request(
6163 "/schemas/invoices",
6164 method="PUT",
6165 body=json.dumps({"name": "contacts", "fields": []}).encode(),
6166 headers=auth_headers(),
6167 )
6168 field_status, _, field_payload = request(
6169 "/schemas/invoices",
6170 method="PUT",
6171 body=json.dumps({"fields": [{"name": "bad.name"}]}).encode(),
6172 headers=auth_headers(),
6173 )
6174
6175 assert name_status == 400
6176 assert name_payload == {
6177 "status": "error",
6178 "error": "Schema file name does not match schema collection: invoices",
6179 }
6180 assert field_status == 400
6181 assert field_payload == {
6182 "status": "error",
6183 "error": "Schema field has invalid name: invoices",
6184 }
6185
6186
6187def test_schema_detail_rejects_invalid_name(tmp_path, monkeypatch):
6188 enable_admin_token(monkeypatch)
6189
6190 status, _, payload = request("/schemas/bad.name", headers=auth_headers())
6191
6192 assert status == 400
6193 assert payload == {"status": "error", "error": "Invalid schema name: bad.name"}
6194
6195
6196def test_schema_detail_rejects_missing_schema(tmp_path, monkeypatch):
6197 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
6198 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6199 enable_admin_token(monkeypatch)
6200
6201 status, _, payload = request("/schemas/missing", headers=auth_headers())
6202
6203 assert status == 404
6204 assert payload == {"status": "error", "error": "Schema not found: missing"}
6205
6206
6207def test_schema_routes_reject_non_get_methods(tmp_path, monkeypatch):
6208 enable_admin_token(monkeypatch)
6209
6210 list_status, _, list_payload = request("/schemas", method="POST", headers=auth_headers())
6211 detail_status, _, detail_payload = request(
6212 "/schemas/contacts",
6213 method="POST",
6214 headers=auth_headers(),
6215 )
6216
6217 assert list_status == 405
6218 assert detail_status == 405
6219 assert list_payload == {"status": "error", "error": "Method not allowed"}
6220 assert detail_payload == {"status": "error", "error": "Method not allowed"}
6221
6222
6223def test_permissions_policy_requires_admin_token_configuration(tmp_path, monkeypatch):
6224 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6225 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
6226
6227 status, _, payload = request("/permissions/policy")
6228
6229 assert status == 403
6230 assert payload == {"status": "error", "error": "Permissions API requires DBBASIC_ADMIN_TOKEN."}
6231
6232
6233def test_permissions_policy_requires_authorization_header(tmp_path, monkeypatch):
6234 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6235 enable_admin_token(monkeypatch)
6236
6237 status, _, payload = request("/permissions/policy")
6238
6239 assert status == 401
6240 assert payload == {"status": "error", "error": "Unauthorized"}
6241
6242
6243def test_permissions_policy_get_returns_default_policy(tmp_path, monkeypatch):
6244 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6245 enable_admin_token(monkeypatch)
6246
6247 status, _, payload = request("/permissions/policy", headers=auth_headers())
6248
6249 assert status == 200
6250 assert payload == {
6251 "status": "ok",
6252 "policy": {
6253 "access_mode": "role_based",
6254 "roles": {},
6255 "user_roles": {},
6256 "rules": [],
6257 "admin_roles": ["admin", "superuser"],
6258 },
6259 }
6260
6261
6262def test_permissions_status_requires_admin_token_configuration(tmp_path, monkeypatch):
6263 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6264 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
6265
6266 status, _, payload = request("/permissions/status")
6267
6268 assert status == 403
6269 assert payload == {"status": "error", "error": "Permissions API requires DBBASIC_ADMIN_TOKEN."}
6270
6271
6272def test_permissions_status_reports_default_policy_blocker(tmp_path, monkeypatch):
6273 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6274 enable_admin_token(monkeypatch)
6275
6276 status, _, payload = request("/permissions/status", headers=auth_headers())
6277
6278 assert status == 200
6279 assert payload["status"] == "ok"
6280 assert payload["permissions"]["enforcement_enabled"] is False
6281 assert payload["permissions"]["enforcement_requested"] is False
6282 assert payload["permissions"]["enforcement_blocked"] is False
6283 assert payload["permissions"]["allow_unready_enforcement"] is False
6284 assert payload["permissions"]["audit_enabled"] is False
6285 assert payload["permissions"]["trusted_headers_enabled"] is False
6286 assert payload["permissions"]["admin_token_configured"] is True
6287 assert payload["permissions"]["session_login_enabled"] is False
6288 assert payload["permissions"]["session_login_token_configured"] is False
6289 assert payload["identity"]["accounts"] == {"count": 0, "active": 0, "disabled": 0}
6290 assert payload["identity"]["users"] == {"count": 0, "active": 0, "disabled": 0}
6291 assert payload["identity"]["sessions"] == {"count": 0, "active": 0, "revoked": 0}
6292 assert payload["policy"]["access_mode"] == "role_based"
6293 assert payload["policy"]["policy_file_exists"] is False
6294 assert payload["policy"]["rules_count"] == 0
6295 assert payload["readiness"] == {
6296 "can_enable_enforcement": False,
6297 "blockers": [
6298 "Role-based policy has no allow grants; non-admin traffic will be denied.",
6299 "No non-admin identity path is available; enable trusted headers, "
6300 "guarded session login, password login, or create an active session "
6301 "before enforcement.",
6302 ],
6303 }
6304 assert "Permission enforcement is off." in payload["warnings"]
6305 assert "object execution and mutation routes" in payload["coverage"]["policy_checked"]
6306
6307
6308def test_permissions_status_reports_blocked_enforcement_request(tmp_path, monkeypatch):
6309 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6310 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
6311 enable_admin_token(monkeypatch)
6312
6313 status, _, payload = request("/permissions/status", headers=auth_headers())
6314
6315 assert status == 200
6316 assert payload["permissions"]["enforcement_enabled"] is False
6317 assert payload["permissions"]["enforcement_requested"] is True
6318 assert payload["permissions"]["enforcement_blocked"] is True
6319 assert payload["permissions"]["audit_enabled"] is True
6320 assert payload["readiness"] == {
6321 "can_enable_enforcement": False,
6322 "blockers": [
6323 "Role-based policy has no allow grants; non-admin traffic will be denied.",
6324 "No non-admin identity path is available; enable trusted headers, "
6325 "guarded session login, password login, or create an active session "
6326 "before enforcement.",
6327 ],
6328 }
6329 assert (
6330 "Permission enforcement was requested but readiness checks blocked rollout."
6331 in payload["warnings"]
6332 )
6333
6334
6335def test_permissions_status_reports_identity_counts_and_ready_policy(tmp_path, monkeypatch):
6336 data_dir = tmp_path / "data"
6337 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6338 monkeypatch.setenv(object_server.PERMISSION_AUDIT_ENV, "true")
6339 monkeypatch.setenv(object_server.REQUIRE_KNOWN_IDENTITY_USERS_ENV, "true")
6340 enable_admin_token(monkeypatch)
6341 save_permission_policy(
6342 data_dir,
6343 {
6344 "access_mode": "role_based",
6345 "roles": {"sales": {"label": "Sales"}},
6346 "user_roles": {"u_7": ["sales"]},
6347 "rules": [
6348 {
6349 "effect": "allow",
6350 "principal": "role:sales",
6351 "actions": ["read"],
6352 "collection": "contacts",
6353 "row_filter": {"owner_id": "$user_id"},
6354 }
6355 ],
6356 },
6357 )
6358 request(
6359 "/identity/accounts",
6360 method="POST",
6361 body=json.dumps({"account_id": "acme", "name": "Acme"}).encode(),
6362 headers=auth_headers(),
6363 )
6364 request(
6365 "/identity/users",
6366 method="POST",
6367 body=json.dumps({"user_id": "u_7", "account_id": "acme", "roles": ["sales"]}).encode(),
6368 headers=auth_headers(),
6369 )
6370 request(
6371 "/identity/sessions",
6372 method="POST",
6373 body=json.dumps({"user_id": "u_7", "label": "scroll"}).encode(),
6374 headers=auth_headers(),
6375 )
6376
6377 status, _, payload = request("/permissions/status", headers=auth_headers())
6378
6379 assert status == 200
6380 assert payload["permissions"]["audit_enabled"] is True
6381 assert payload["permissions"]["enforcement_enabled"] is False
6382 assert payload["permissions"]["enforcement_requested"] is False
6383 assert payload["permissions"]["enforcement_blocked"] is False
6384 assert payload["permissions"]["require_known_identity_users"] is True
6385 assert payload["identity"]["accounts"] == {"count": 1, "active": 1, "disabled": 0}
6386 assert payload["identity"]["users"] == {"count": 1, "active": 1, "disabled": 0}
6387 assert payload["identity"]["sessions"]["count"] == 1
6388 assert payload["identity"]["sessions"]["active"] == 1
6389 assert payload["policy"]["policy_file_exists"] is True
6390 assert payload["policy"]["rules_count"] == 1
6391 assert payload["policy"]["allow_rules"] == 1
6392 assert payload["policy"]["principals"] == ["role:sales"]
6393 assert payload["policy"]["collections"] == ["contacts"]
6394 assert payload["readiness"] == {"can_enable_enforcement": True, "blockers": []}
6395
6396
6397def test_permissions_status_accepts_guarded_session_login_as_identity_path(
6398 tmp_path,
6399 monkeypatch,
6400):
6401 data_dir = tmp_path / "data"
6402 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6403 monkeypatch.setenv(object_server.SESSION_LOGIN_ENV, "true")
6404 monkeypatch.setenv(object_server.SESSION_LOGIN_TOKEN_ENV, "login-token")
6405 enable_admin_token(monkeypatch)
6406 save_permission_policy(
6407 data_dir,
6408 {
6409 "access_mode": "role_based",
6410 "roles": {"sales": {"label": "Sales"}},
6411 "user_roles": {"u_7": ["sales"]},
6412 "rules": [
6413 {
6414 "effect": "allow",
6415 "principal": "role:sales",
6416 "actions": ["read"],
6417 "collection": "contacts",
6418 }
6419 ],
6420 },
6421 )
6422 request(
6423 "/identity/accounts",
6424 method="POST",
6425 body=json.dumps({"account_id": "acme", "name": "Acme"}).encode(),
6426 headers=auth_headers(),
6427 )
6428 request(
6429 "/identity/users",
6430 method="POST",
6431 body=json.dumps({"user_id": "u_7", "account_id": "acme", "roles": ["sales"]}).encode(),
6432 headers=auth_headers(),
6433 )
6434
6435 status, _, payload = request("/permissions/status", headers=auth_headers())
6436
6437 assert status == 200
6438 assert payload["permissions"]["session_login_enabled"] is True
6439 assert payload["permissions"]["session_login_token_configured"] is True
6440 assert payload["identity"]["sessions"]["active"] == 0
6441 assert payload["readiness"] == {"can_enable_enforcement": True, "blockers": []}
6442 assert (
6443 "Trusted headers are off and no active DBBASIC sessions exist; non-admin requests will be anonymous."
6444 not in payload["warnings"]
6445 )
6446
6447
6448def test_permissions_status_rejects_non_get_methods(tmp_path, monkeypatch):
6449 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6450 enable_admin_token(monkeypatch)
6451
6452 status, _, payload = request("/permissions/status", method="POST", headers=auth_headers())
6453
6454 assert status == 405
6455 assert payload == {"status": "error", "error": "Method not allowed"}
6456
6457
6458def test_permissions_policy_put_persists_policy(tmp_path, monkeypatch):
6459 data_dir = tmp_path / "data"
6460 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6461 enable_admin_token(monkeypatch)
6462 policy = {
6463 "access_mode": "role_based",
6464 "roles": {"sales": {"label": "Sales"}},
6465 "user_roles": {"7": ["sales"]},
6466 "rules": [
6467 {
6468 "effect": "allow",
6469 "principal": "role:sales",
6470 "actions": ["read"],
6471 "collection": "contacts",
6472 "row_filter": {"owner_id": "$user_id"},
6473 "reason": "sales reps only see own contacts",
6474 }
6475 ],
6476 "admin_roles": ["admin"],
6477 }
6478
6479 status, _, payload = request(
6480 "/permissions/policy",
6481 method="PUT",
6482 body=json.dumps({"policy": policy}).encode(),
6483 headers=auth_headers(),
6484 )
6485
6486 assert status == 200
6487 assert payload["status"] == "ok"
6488 assert payload["policy"]["access_mode"] == "role_based"
6489 assert (data_dir / "permissions" / "policy.json").exists()
6490
6491 status, _, payload = request("/permissions/policy", headers=auth_headers())
6492
6493 assert status == 200
6494 assert payload["policy"]["rules"][0]["principal"] == "role:sales"
6495 assert payload["policy"]["rules"][0]["row_filter"] == {"owner_id": "$user_id"}
6496
6497
6498def test_permissions_policy_put_rejects_invalid_policy(tmp_path, monkeypatch):
6499 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6500 enable_admin_token(monkeypatch)
6501
6502 status, _, payload = request(
6503 "/permissions/policy",
6504 method="PUT",
6505 body=json.dumps({"policy": {"access_mode": "unknown"}}).encode(),
6506 headers=auth_headers(),
6507 )
6508
6509 assert status == 400
6510 assert payload["status"] == "error"
6511 assert "Permission access_mode must be one of:" in payload["error"]
6512
6513
6514def test_permissions_check_uses_persisted_policy(tmp_path, monkeypatch):
6515 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6516 enable_admin_token(monkeypatch)
6517 policy = {
6518 "access_mode": "role_based",
6519 "rules": [
6520 {
6521 "effect": "allow",
6522 "principal": "role:sales",
6523 "actions": ["read"],
6524 "collection": "contacts",
6525 "row_filter": {"owner_id": "$user_id"},
6526 "reason": "sales reps only see own contacts",
6527 }
6528 ],
6529 }
6530 request(
6531 "/permissions/policy",
6532 method="PUT",
6533 body=json.dumps({"policy": policy}).encode(),
6534 headers=auth_headers(),
6535 )
6536
6537 status, _, payload = request(
6538 "/permissions/check",
6539 method="POST",
6540 body=json.dumps(
6541 {
6542 "subject": {"user_id": "7", "roles": ["sales"]},
6543 "action": "read",
6544 "collection": "contacts",
6545 }
6546 ).encode(),
6547 headers=auth_headers(),
6548 )
6549
6550 assert status == 200
6551 assert payload == {
6552 "status": "ok",
6553 "decision": {
6554 "allowed": True,
6555 "reason": "sales reps only see own contacts",
6556 "code": "allowed",
6557 "http_status": 200,
6558 "row_filter": {"owner_id": "$user_id"},
6559 "fields": None,
6560 "denied_fields": [],
6561 },
6562 }
6563
6564
6565def test_permissions_check_accepts_inline_policy_for_preview(tmp_path, monkeypatch):
6566 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6567 enable_admin_token(monkeypatch)
6568
6569 status, _, payload = request(
6570 "/permissions/check",
6571 method="POST",
6572 body=json.dumps(
6573 {
6574 "policy": {
6575 "access_mode": "role_based",
6576 "rules": [
6577 {
6578 "effect": "allow",
6579 "principal": "account:customer-acme",
6580 "actions": ["read"],
6581 "collection": "invoices",
6582 "row_filter": {"customer_account_id": "$account_id"},
6583 "fields": ["invoice_id", "total"],
6584 "denied_fields": ["internal_notes"],
6585 }
6586 ],
6587 },
6588 "subject": {"user_id": "9", "account_id": "customer-acme"},
6589 "action": "read",
6590 "collection": "invoices",
6591 "record": {"customer_account_id": "customer-acme", "total": 120},
6592 }
6593 ).encode(),
6594 headers=auth_headers(),
6595 )
6596
6597 assert status == 200
6598 assert payload["decision"]["allowed"] is True
6599 assert payload["decision"]["fields"] == ["invoice_id", "total"]
6600 assert payload["decision"]["denied_fields"] == ["internal_notes"]
6601
6602
6603def test_permissions_check_returns_payment_required_decision(tmp_path, monkeypatch):
6604 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6605 enable_admin_token(monkeypatch)
6606
6607 status, _, payload = request(
6608 "/permissions/check",
6609 method="POST",
6610 body=json.dumps(
6611 {
6612 "policy": {"access_mode": "subscription"},
6613 "subject": {"user_id": "42"},
6614 "action": "read",
6615 "collection": "premium_reports",
6616 }
6617 ).encode(),
6618 headers=auth_headers(),
6619 )
6620
6621 assert status == 200
6622 assert payload["decision"]["allowed"] is False
6623 assert payload["decision"]["code"] == "payment_required"
6624 assert payload["decision"]["http_status"] == 402
6625
6626
6627def test_permissions_audit_requires_admin_token_configuration(tmp_path, monkeypatch):
6628 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6629 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
6630
6631 status, _, payload = request("/permissions/audit")
6632
6633 assert status == 403
6634 assert payload == {"status": "error", "error": "Permissions API requires DBBASIC_ADMIN_TOKEN."}
6635
6636
6637def test_permissions_audit_requires_authorization_header(tmp_path, monkeypatch):
6638 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6639 enable_admin_token(monkeypatch)
6640
6641 status, _, payload = request("/permissions/audit")
6642
6643 assert status == 401
6644 assert payload == {"status": "error", "error": "Unauthorized"}
6645
6646
6647def test_permissions_audit_returns_recent_entries_with_filters(tmp_path, monkeypatch):
6648 data_dir = tmp_path / "data"
6649 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6650 enable_admin_token(monkeypatch)
6651 object_permission_audit.append_permission_audit(
6652 {
6653 "timestamp": "2026-06-29T00:00:00Z",
6654 "action": "execute",
6655 "object_id": "site_home",
6656 "collection": "site",
6657 "enforced": False,
6658 "decision": {"allowed": False},
6659 },
6660 data_dir,
6661 )
6662 object_permission_audit.append_permission_audit(
6663 {
6664 "timestamp": "2026-06-29T00:00:01Z",
6665 "action": "source",
6666 "object_id": "basics_counter",
6667 "collection": "basics",
6668 "enforced": True,
6669 "decision": {"allowed": True},
6670 },
6671 data_dir,
6672 )
6673
6674 status, _, payload = request(
6675 "/permissions/audit",
6676 query_string="action=source&allowed=true&enforced=true&limit=10",
6677 headers=auth_headers(),
6678 )
6679
6680 assert status == 200
6681 assert payload == {
6682 "status": "ok",
6683 "entries": [
6684 {
6685 "timestamp": "2026-06-29T00:00:01Z",
6686 "action": "source",
6687 "object_id": "basics_counter",
6688 "collection": "basics",
6689 "enforced": True,
6690 "decision": {"allowed": True},
6691 }
6692 ],
6693 "count": 1,
6694 }
6695
6696
6697def test_permissions_audit_returns_empty_when_missing(tmp_path, monkeypatch):
6698 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6699 enable_admin_token(monkeypatch)
6700
6701 status, _, payload = request("/permissions/audit", headers=auth_headers())
6702
6703 assert status == 200
6704 assert payload == {"status": "ok", "entries": [], "count": 0}
6705
6706
6707def test_permissions_audit_rejects_bad_query_values(tmp_path, monkeypatch):
6708 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6709 enable_admin_token(monkeypatch)
6710
6711 status, _, payload = request(
6712 "/permissions/audit",
6713 query_string="allowed=maybe",
6714 headers=auth_headers(),
6715 )
6716
6717 assert status == 400
6718 assert payload == {
6719 "status": "error",
6720 "error": "Query parameter 'allowed' must be a boolean",
6721 }
6722
6723
6724def test_permissions_audit_rejects_non_get_methods(tmp_path, monkeypatch):
6725 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6726 enable_admin_token(monkeypatch)
6727
6728 status, _, payload = request("/permissions/audit", method="POST", headers=auth_headers())
6729
6730 assert status == 405
6731 assert payload == {"status": "error", "error": "Method not allowed"}
6732
6733
6734def test_permission_enforcement_is_disabled_by_default(tmp_path, monkeypatch):
6735 root = tmp_path / "objects"
6736 data_dir = tmp_path / "data"
6737 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
6738 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6739 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6740
6741 status, _, payload = request("/objects/site_home")
6742
6743 assert status == 200
6744 assert payload == {"ok": True}
6745 assert object_permission_audit.get_permission_audit(data_dir) == []
6746
6747
6748def test_permission_enforcement_request_with_default_policy_stays_in_shadow_mode(
6749 tmp_path,
6750 monkeypatch,
6751):
6752 root = tmp_path / "objects"
6753 data_dir = tmp_path / "data"
6754 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
6755 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6756 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6757 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
6758
6759 status, _, payload = request("/objects/site_home")
6760
6761 assert status == 200
6762 assert payload == {"ok": True}
6763 entries = object_permission_audit.get_permission_audit(data_dir)
6764 assert entries[-1]["action"] == "execute"
6765 assert entries[-1]["object_id"] == "site_home"
6766 assert entries[-1]["collection"] == "site"
6767 assert entries[-1]["decision"]["allowed"] is False
6768 assert entries[-1]["enforced"] is False
6769 assert entries[-1]["enforcement_requested"] is True
6770 assert entries[-1]["enforcement_blocked"] is True
6771
6772
6773def test_permission_enforcement_can_force_default_policy(tmp_path, monkeypatch):
6774 root = tmp_path / "objects"
6775 data_dir = tmp_path / "data"
6776 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
6777 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6778 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6779 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
6780 monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true")
6781
6782 status, _, payload = request("/objects/site_home")
6783
6784 assert status == 403
6785 assert payload == {"status": "error", "error": "no matching role rule", "code": "forbidden"}
6786 entry = object_permission_audit.get_permission_audit(data_dir)[-1]
6787 assert entry["decision"]["allowed"] is False
6788 assert entry["enforced"] is True
6789 assert entry["enforcement_requested"] is True
6790
6791
6792def test_permission_enforcement_allows_public_policy_execution(tmp_path, monkeypatch):
6793 root = tmp_path / "objects"
6794 data_dir = tmp_path / "data"
6795 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
6796 save_permission_policy(data_dir, {"access_mode": "public"})
6797 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6798 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6799 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
6800
6801 status, _, payload = request("/objects/site_home")
6802
6803 assert status == 200
6804 assert payload == {"ok": True}
6805 assert object_permission_audit.get_permission_audit(data_dir)[-1]["decision"]["allowed"] is True
6806
6807
6808def test_permission_enforcement_admin_token_bypasses_policy(tmp_path, monkeypatch):
6809 root = tmp_path / "objects"
6810 data_dir = tmp_path / "data"
6811 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
6812 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6813 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6814 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
6815 enable_admin_token(monkeypatch)
6816
6817 status, _, payload = request("/objects/site_home", headers=auth_headers())
6818
6819 assert status == 200
6820 assert payload == {"ok": True}
6821 entry = object_permission_audit.get_permission_audit(data_dir)[-1]
6822 assert entry["subject"]["roles"] == ["admin"]
6823 assert entry["decision"]["reason"] == "admin role"
6824
6825
6826def test_permission_enforcement_uses_trusted_subject_headers(tmp_path, monkeypatch):
6827 root = tmp_path / "objects"
6828 data_dir = tmp_path / "data"
6829 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
6830 save_permission_policy(
6831 data_dir,
6832 {
6833 "access_mode": "role_based",
6834 "rules": [
6835 {
6836 "effect": "allow",
6837 "principal": "role:sales",
6838 "actions": ["execute"],
6839 "object_id": "site_home",
6840 "reason": "sales can execute site home",
6841 }
6842 ],
6843 },
6844 )
6845 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6846 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6847 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
6848 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
6849
6850 status, _, payload = request(
6851 "/objects/site_home",
6852 headers=[
6853 ("x-dbbasic-user-id", "7"),
6854 ("x-dbbasic-account-id", "customer-acme"),
6855 ("x-dbbasic-roles", "sales"),
6856 ],
6857 )
6858
6859 assert status == 200
6860 assert payload == {"ok": True}
6861 entry = object_permission_audit.get_permission_audit(data_dir)[-1]
6862 assert entry["subject"]["user_id"] == "7"
6863 assert entry["subject"]["account_id"] == "customer-acme"
6864 assert entry["subject"]["roles"] == ["sales"]
6865 assert entry["decision"]["reason"] == "sales can execute site home"
6866
6867
6868def test_permission_enforcement_without_admin_recovery_token_stays_in_shadow_mode(
6869 tmp_path,
6870 monkeypatch,
6871):
6872 root = tmp_path / "objects"
6873 data_dir = tmp_path / "data"
6874 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
6875 save_permission_policy(
6876 data_dir,
6877 {
6878 "access_mode": "role_based",
6879 "rules": [
6880 {
6881 "effect": "allow",
6882 "principal": "role:sales",
6883 "actions": ["execute"],
6884 "object_id": "site_home",
6885 }
6886 ],
6887 },
6888 )
6889 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6890 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6891 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
6892 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
6893 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
6894
6895 status, _, payload = request(
6896 "/objects/site_home",
6897 headers=[("x-dbbasic-user-id", "8"), ("x-dbbasic-roles", "support")],
6898 )
6899
6900 assert status == 200
6901 assert payload == {"ok": True}
6902 entry = object_permission_audit.get_permission_audit(data_dir)[-1]
6903 assert entry["decision"]["allowed"] is False
6904 assert entry["enforced"] is False
6905 assert entry["enforcement_requested"] is True
6906 assert entry["enforcement_blocked"] is True
6907
6908
6909def test_permission_audit_shadow_mode_logs_without_blocking(tmp_path, monkeypatch):
6910 root = tmp_path / "objects"
6911 data_dir = tmp_path / "data"
6912 write_source(root / "site" / "home.py", "def GET(request):\n return {'ok': True}\n")
6913 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6914 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
6915 monkeypatch.setenv(object_server.PERMISSION_AUDIT_ENV, "true")
6916
6917 status, _, payload = request("/objects/site_home")
6918
6919 assert status == 200
6920 assert payload == {"ok": True}
6921 entry = object_permission_audit.get_permission_audit(data_dir)[-1]
6922 assert entry["decision"]["allowed"] is False
6923 assert entry["enforced"] is False
6924
6925
6926def test_get_source_returns_existing_contract_shape(tmp_path, monkeypatch):
6927 root = tmp_path / "objects"
6928 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 1}\n")
6929 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6930 enable_admin_token(monkeypatch)
6931
6932 status, _, payload = request(
6933 "/objects/basics_counter",
6934 query_string="source=true&format=json",
6935 headers=auth_headers(),
6936 )
6937
6938 assert status == 200
6939 assert payload == {
6940 "status": "ok",
6941 "object_id": "basics_counter",
6942 "source": "def GET(request):\n return {'count': 1}\n",
6943 }
6944
6945
6946def test_get_source_rejects_station_routing_for_now(tmp_path, monkeypatch):
6947 root = tmp_path / "objects"
6948 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
6949 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6950
6951 status, _, payload = request(
6952 "/objects/basics_counter@remote_node",
6953 query_string="source=true&format=json",
6954 )
6955
6956 assert status == 400
6957 assert payload["status"] == "error"
6958 assert "Station routing is not available" in payload["error"]
6959
6960
6961def test_get_source_returns_404_for_missing_object(tmp_path, monkeypatch):
6962 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
6963 enable_admin_token(monkeypatch)
6964
6965 status, _, payload = request(
6966 "/objects/missing_object",
6967 query_string="source=true&format=json",
6968 headers=auth_headers(),
6969 )
6970
6971 assert status == 404
6972 assert payload["status"] == "error"
6973 assert payload["error"] == "Object source not found: missing_object"
6974
6975
6976def test_get_source_requires_authorization_header(tmp_path, monkeypatch):
6977 root = tmp_path / "objects"
6978 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 1}\n")
6979 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6980 enable_admin_token(monkeypatch)
6981
6982 status, _, payload = request(
6983 "/objects/basics_counter",
6984 query_string="source=true&format=json",
6985 )
6986
6987 assert status == 401
6988 assert payload == {"status": "error", "error": "Unauthorized"}
6989
6990
6991def test_get_state_returns_empty_state_for_object_without_state_file(tmp_path, monkeypatch):
6992 root = tmp_path / "objects"
6993 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
6994 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
6995 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
6996 enable_admin_token(monkeypatch)
6997
6998 status, _, payload = request(
6999 "/objects/basics_counter",
7000 query_string="state=true",
7001 headers=auth_headers(),
7002 )
7003
7004 assert status == 200
7005 assert payload == {
7006 "status": "ok",
7007 "object_id": "basics_counter",
7008 "state": {},
7009 }
7010
7011
7012def test_get_state_reads_tsv_state(tmp_path, monkeypatch):
7013 root = tmp_path / "objects"
7014 data_dir = tmp_path / "data"
7015 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
7016 state_file = data_dir / "state" / "basics_counter" / "state.tsv"
7017 state_file.parent.mkdir(parents=True, exist_ok=True)
7018 state_file.write_text(
7019 "key\tvalue\ttimestamp\n"
7020 "count\t3\t1710000000.1\n"
7021 "rate\t2.5\t1710000000.2\n"
7022 "name\tcounter\t1710000000.3\n"
7023 )
7024 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7025 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7026 enable_admin_token(monkeypatch)
7027
7028 status, _, payload = request(
7029 "/objects/basics_counter",
7030 query_string="state=true",
7031 headers=auth_headers(),
7032 )
7033
7034 assert status == 200
7035 assert payload == {
7036 "status": "ok",
7037 "object_id": "basics_counter",
7038 "state": {
7039 "count": 3,
7040 "rate": 2.5,
7041 "name": "counter",
7042 },
7043 }
7044
7045
7046def test_get_state_returns_404_for_missing_object(tmp_path, monkeypatch):
7047 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
7048 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
7049 enable_admin_token(monkeypatch)
7050
7051 status, _, payload = request(
7052 "/objects/missing_object",
7053 query_string="state=true",
7054 headers=auth_headers(),
7055 )
7056
7057 assert status == 404
7058 assert payload == {"status": "error", "error": "Object source not found: missing_object"}
7059
7060
7061def test_get_state_rejects_invalid_object_id(tmp_path, monkeypatch):
7062 root = tmp_path / "objects"
7063 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7064 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
7065 enable_admin_token(monkeypatch)
7066
7067 status, _, payload = request(
7068 "/objects/bad.id",
7069 query_string="state=true",
7070 headers=auth_headers(),
7071 )
7072
7073 assert status == 400
7074 assert payload == {"status": "error", "error": "Invalid object ID: bad.id"}
7075
7076
7077def test_get_logs_returns_empty_logs_for_object_without_log_file(tmp_path, monkeypatch):
7078 root = tmp_path / "objects"
7079 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
7080 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7081 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
7082 enable_admin_token(monkeypatch)
7083
7084 status, _, payload = request(
7085 "/objects/basics_counter",
7086 query_string="logs=true",
7087 headers=auth_headers(),
7088 )
7089
7090 assert status == 200
7091 assert payload == {
7092 "status": "ok",
7093 "object_id": "basics_counter",
7094 "logs": [],
7095 "count": 0,
7096 }
7097
7098
7099def test_get_logs_reads_tsv_logs_with_level_and_limit(tmp_path, monkeypatch):
7100 root = tmp_path / "objects"
7101 data_dir = tmp_path / "data"
7102 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
7103 log_file = data_dir / "logs" / "basics_counter" / "log.tsv"
7104 log_file.parent.mkdir(parents=True, exist_ok=True)
7105 log_file.write_text(
7106 "entry_id\ttimestamp\tlevel\tmessage\tmethod\n"
7107 "a1\t2026-01-01T00:00:00\tINFO\tstarted\tGET\n"
7108 "a2\t2026-01-01T00:00:01\tERROR\tboom\tGET\n"
7109 "a3\t2026-01-01T00:00:02\tERROR\tstill bad\tGET\n"
7110 )
7111 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7112 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7113 enable_admin_token(monkeypatch)
7114
7115 status, _, payload = request(
7116 "/objects/basics_counter",
7117 query_string="logs=true&level=ERROR&limit=1",
7118 headers=auth_headers(),
7119 )
7120
7121 assert status == 200
7122 assert payload == {
7123 "status": "ok",
7124 "object_id": "basics_counter",
7125 "logs": [
7126 {
7127 "entry_id": "a2",
7128 "timestamp": "2026-01-01T00:00:01",
7129 "level": "ERROR",
7130 "message": "boom",
7131 "method": "GET",
7132 }
7133 ],
7134 "count": 1,
7135 }
7136
7137
7138def test_get_logs_rejects_bad_limit(tmp_path, monkeypatch):
7139 root = tmp_path / "objects"
7140 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
7141 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7142 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
7143 enable_admin_token(monkeypatch)
7144
7145 status, _, payload = request(
7146 "/objects/basics_counter",
7147 query_string="logs=true&limit=0",
7148 headers=auth_headers(),
7149 )
7150
7151 assert status == 400
7152 assert payload == {
7153 "status": "error",
7154 "error": "Query parameter 'limit' must be at least 1",
7155 }
7156
7157
7158def test_get_logs_returns_404_for_missing_object(tmp_path, monkeypatch):
7159 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
7160 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
7161 enable_admin_token(monkeypatch)
7162
7163 status, _, payload = request(
7164 "/objects/missing_object",
7165 query_string="logs=true",
7166 headers=auth_headers(),
7167 )
7168
7169 assert status == 404
7170 assert payload == {"status": "error", "error": "Object source not found: missing_object"}
7171
7172
7173def test_get_logs_rejects_invalid_object_id(tmp_path, monkeypatch):
7174 root = tmp_path / "objects"
7175 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7176 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
7177 enable_admin_token(monkeypatch)
7178
7179 status, _, payload = request(
7180 "/objects/bad.id",
7181 query_string="logs=true",
7182 headers=auth_headers(),
7183 )
7184
7185 assert status == 400
7186 assert payload == {"status": "error", "error": "Invalid object ID: bad.id"}
7187
7188
7189def test_get_files_lists_object_owned_files(tmp_path, monkeypatch):
7190 root = tmp_path / "objects"
7191 data_dir = tmp_path / "data"
7192 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7193 file_path = data_dir / "files" / "site_home" / "assets" / "report.txt"
7194 file_path.parent.mkdir(parents=True)
7195 file_path.write_text("hello")
7196 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7197 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7198 enable_admin_token(monkeypatch)
7199
7200 status, _, payload = request(
7201 "/objects/site_home",
7202 query_string="files=true",
7203 headers=auth_headers(),
7204 )
7205
7206 assert status == 200
7207 assert payload["status"] == "ok"
7208 assert payload["object_id"] == "site_home"
7209 assert payload["count"] == 1
7210 assert payload["files"][0]["name"] == "assets/report.txt"
7211 assert payload["files"][0]["size"] == 5
7212
7213
7214def test_get_files_requires_admin_token(tmp_path, monkeypatch):
7215 root = tmp_path / "objects"
7216 data_dir = tmp_path / "data"
7217 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7218 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7219 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7220 enable_admin_token(monkeypatch)
7221
7222 status, _, payload = request("/objects/site_home", query_string="files=true")
7223
7224 assert status == 401
7225 assert payload == {"status": "error", "error": "Unauthorized"}
7226
7227
7228def test_get_file_downloads_object_owned_file(tmp_path, monkeypatch):
7229 root = tmp_path / "objects"
7230 data_dir = tmp_path / "data"
7231 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7232 file_path = data_dir / "files" / "site_home" / "image.png"
7233 file_path.parent.mkdir(parents=True)
7234 file_path.write_bytes(b"\x89PNG")
7235 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7236 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7237 enable_admin_token(monkeypatch)
7238
7239 status, headers, body = raw_request(
7240 "/objects/site_home",
7241 query_string="file=image.png",
7242 headers=auth_headers(),
7243 )
7244
7245 assert status == 200
7246 assert headers[b"content-type"] == b"image/png"
7247 assert headers[b"content-disposition"] == b'inline; filename="image.png"'
7248 assert body == b"\x89PNG"
7249
7250
7251def test_get_file_requires_admin_token(tmp_path, monkeypatch):
7252 root = tmp_path / "objects"
7253 data_dir = tmp_path / "data"
7254 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7255 file_path = data_dir / "files" / "site_home" / "image.png"
7256 file_path.parent.mkdir(parents=True)
7257 file_path.write_bytes(b"\x89PNG")
7258 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7259 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7260 enable_admin_token(monkeypatch)
7261
7262 status, _, payload = request("/objects/site_home", query_string="file=image.png")
7263
7264 assert status == 401
7265 assert payload == {"status": "error", "error": "Unauthorized"}
7266
7267
7268def test_get_file_rejects_path_traversal(tmp_path, monkeypatch):
7269 root = tmp_path / "objects"
7270 data_dir = tmp_path / "data"
7271 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7272 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7273 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7274 enable_admin_token(monkeypatch)
7275
7276 status, _, payload = request(
7277 "/objects/site_home",
7278 query_string="file=../secret.txt",
7279 headers=auth_headers(),
7280 )
7281
7282 assert status == 400
7283 assert payload["status"] == "error"
7284 assert payload["error"].startswith("Invalid filename:")
7285
7286
7287def test_admin_files_lists_object_owned_files(tmp_path, monkeypatch):
7288 root = tmp_path / "objects"
7289 data_dir = tmp_path / "data"
7290 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7291 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
7292 home_file = data_dir / "files" / "site_home" / "assets" / "report.txt"
7293 home_file.parent.mkdir(parents=True)
7294 home_file.write_text("hello")
7295 counter_file = data_dir / "files" / "basics_counter" / "image.png"
7296 counter_file.parent.mkdir(parents=True)
7297 counter_file.write_bytes(b"\x89PNG")
7298 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7299 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7300 enable_admin_token(monkeypatch)
7301
7302 status, _, payload = request(
7303 "/admin/files",
7304 headers=auth_headers(),
7305 )
7306
7307 assert status == 200
7308 assert payload["status"] == "ok"
7309 assert payload["count"] == 2
7310 assert payload["total"] == 2
7311 files = {(item["object_id"], item["name"], item["size"]) for item in payload["files"]}
7312 assert files == {
7313 ("site_home", "assets/report.txt", 5),
7314 ("basics_counter", "image.png", 4),
7315 }
7316
7317
7318def test_admin_files_requires_admin_token(tmp_path, monkeypatch):
7319 data_dir = tmp_path / "data"
7320 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7321 enable_admin_token(monkeypatch)
7322
7323 status, _, payload = request("/admin/files")
7324
7325 assert status == 401
7326 assert payload == {"status": "error", "error": "Unauthorized"}
7327
7328
7329def test_admin_files_filters_by_object_and_paginates(tmp_path, monkeypatch):
7330 root = tmp_path / "objects"
7331 data_dir = tmp_path / "data"
7332 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7333 files_dir = data_dir / "files" / "site_home"
7334 files_dir.mkdir(parents=True)
7335 (files_dir / "a.txt").write_text("a")
7336 (files_dir / "b.txt").write_text("bb")
7337 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7338 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7339 enable_admin_token(monkeypatch)
7340
7341 status, _, payload = request(
7342 "/admin/files",
7343 query_string="object_id=site_home&limit=1&offset=1",
7344 headers=auth_headers(),
7345 )
7346
7347 assert status == 200
7348 assert payload["status"] == "ok"
7349 assert payload["count"] == 1
7350 assert payload["total"] == 2
7351 assert payload["files"][0]["object_id"] == "site_home"
7352
7353
7354def test_admin_object_files_alias_lists_object_owned_files(tmp_path, monkeypatch):
7355 root = tmp_path / "objects"
7356 data_dir = tmp_path / "data"
7357 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7358 file_path = data_dir / "files" / "site_home" / "assets" / "report.txt"
7359 file_path.parent.mkdir(parents=True)
7360 file_path.write_text("hello")
7361 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7362 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7363 enable_admin_token(monkeypatch)
7364
7365 status, _, payload = request(
7366 "/admin/files/site_home",
7367 headers=auth_headers(),
7368 )
7369
7370 assert status == 200
7371 assert payload["status"] == "ok"
7372 assert payload["object_id"] == "site_home"
7373 assert payload["count"] == 1
7374 assert payload["files"][0]["name"] == "assets/report.txt"
7375
7376
7377def test_admin_object_inspection_can_list_files(tmp_path, monkeypatch):
7378 root = tmp_path / "objects"
7379 data_dir = tmp_path / "data"
7380 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7381 file_path = data_dir / "files" / "site_home" / "assets" / "report.txt"
7382 file_path.parent.mkdir(parents=True)
7383 file_path.write_text("hello")
7384 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7385 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7386 enable_admin_token(monkeypatch)
7387
7388 status, _, payload = request(
7389 "/admin/objects/site_home",
7390 query_string="files=true",
7391 headers=auth_headers(),
7392 )
7393
7394 assert status == 200
7395 assert payload["status"] == "ok"
7396 assert payload["object_id"] == "site_home"
7397 assert payload["files"][0]["name"] == "assets/report.txt"
7398
7399
7400def test_admin_file_downloads_object_owned_file(tmp_path, monkeypatch):
7401 root = tmp_path / "objects"
7402 data_dir = tmp_path / "data"
7403 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7404 file_path = data_dir / "files" / "site_home" / "image.png"
7405 file_path.parent.mkdir(parents=True)
7406 file_path.write_bytes(b"\x89PNG")
7407 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7408 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7409 enable_admin_token(monkeypatch)
7410
7411 status, headers, body = raw_request(
7412 "/admin/files/site_home",
7413 query_string="file=image.png",
7414 headers=auth_headers(),
7415 )
7416
7417 assert status == 200
7418 assert headers[b"content-type"] == b"image/png"
7419 assert headers[b"content-disposition"] == b'inline; filename="image.png"'
7420 assert body == b"\x89PNG"
7421
7422
7423def test_admin_file_download_rejects_path_traversal(tmp_path, monkeypatch):
7424 root = tmp_path / "objects"
7425 data_dir = tmp_path / "data"
7426 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7427 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7428 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7429 enable_admin_token(monkeypatch)
7430
7431 status, _, payload = request(
7432 "/admin/files/site_home",
7433 query_string="file=../secret.txt",
7434 headers=auth_headers(),
7435 )
7436
7437 assert status == 400
7438 assert payload["status"] == "error"
7439 assert payload["error"].startswith("Invalid filename:")
7440
7441
7442def test_admin_file_upload_is_disabled_by_default(tmp_path, monkeypatch):
7443 root = tmp_path / "objects"
7444 data_dir = tmp_path / "data"
7445 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7446 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7447 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7448 enable_admin_token(monkeypatch)
7449
7450 status, _, payload = request(
7451 "/admin/files/site_home",
7452 method="POST",
7453 body=json.dumps(
7454 {
7455 "name": "assets/report.txt",
7456 "content_base64": base64.b64encode(b"hello").decode("ascii"),
7457 }
7458 ).encode(),
7459 headers=auth_headers(),
7460 )
7461
7462 assert status == 403
7463 assert payload["status"] == "error"
7464 assert "File writes are disabled" in payload["error"]
7465 assert not (data_dir / "files" / "site_home" / "assets" / "report.txt").exists()
7466
7467
7468def test_admin_file_upload_creates_file_and_log(tmp_path, monkeypatch):
7469 root = tmp_path / "objects"
7470 data_dir = tmp_path / "data"
7471 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7472 enable_file_writes(monkeypatch, root, data_dir)
7473
7474 status, _, payload = request(
7475 "/admin/files/site_home",
7476 method="POST",
7477 body=json.dumps(
7478 {
7479 "name": "assets/report.txt",
7480 "content_base64": base64.b64encode(b"hello").decode("ascii"),
7481 }
7482 ).encode(),
7483 headers=auth_headers(),
7484 )
7485
7486 assert status == 201
7487 assert payload["status"] == "ok"
7488 assert payload["operation"] == "created"
7489 assert payload["file"]["object_id"] == "site_home"
7490 assert payload["file"]["name"] == "assets/report.txt"
7491 assert payload["file"]["size"] == 5
7492 assert payload["change"]["action"] == "file_create"
7493 assert payload["change"]["object_id"] == "site_home"
7494 assert payload["change"]["file_name"] == "assets/report.txt"
7495 assert (data_dir / "files" / "site_home" / "assets" / "report.txt").read_bytes() == b"hello"
7496 logs = object_logs.get_object_logs("site_home", base_dir=data_dir)
7497 assert logs[-1]["message"] == "File created: assets/report.txt"
7498 assert logs[-1]["file_operation"] == "created"
7499 changes = object_file_changes.list_file_changes("site_home", base_dir=data_dir)
7500 assert changes["count"] == 1
7501 assert changes["changes"][0]["change_id"] == payload["change"]["change_id"]
7502
7503
7504def test_admin_file_upload_rejects_duplicate_without_overwrite(tmp_path, monkeypatch):
7505 root = tmp_path / "objects"
7506 data_dir = tmp_path / "data"
7507 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7508 file_path = data_dir / "files" / "site_home" / "assets" / "report.txt"
7509 file_path.parent.mkdir(parents=True)
7510 file_path.write_text("old")
7511 enable_file_writes(monkeypatch, root, data_dir)
7512
7513 status, _, payload = request(
7514 "/admin/files/site_home",
7515 method="POST",
7516 body=json.dumps(
7517 {
7518 "name": "assets/report.txt",
7519 "content_base64": base64.b64encode(b"new").decode("ascii"),
7520 }
7521 ).encode(),
7522 headers=auth_headers(),
7523 )
7524
7525 assert status == 409
7526 assert payload["status"] == "error"
7527 assert "File already exists" in payload["error"]
7528 assert file_path.read_text() == "old"
7529
7530
7531def test_admin_file_update_overwrites_file(tmp_path, monkeypatch):
7532 root = tmp_path / "objects"
7533 data_dir = tmp_path / "data"
7534 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7535 file_path = data_dir / "files" / "site_home" / "assets" / "report.txt"
7536 file_path.parent.mkdir(parents=True)
7537 file_path.write_text("old")
7538 enable_file_writes(monkeypatch, root, data_dir)
7539
7540 status, _, payload = request(
7541 "/admin/files/site_home",
7542 method="PUT",
7543 body=json.dumps(
7544 {
7545 "name": "assets/report.txt",
7546 "content_base64": base64.b64encode(b"new").decode("ascii"),
7547 }
7548 ).encode(),
7549 headers=auth_headers(),
7550 )
7551
7552 assert status == 200
7553 assert payload["status"] == "ok"
7554 assert payload["operation"] == "updated"
7555 assert file_path.read_bytes() == b"new"
7556
7557
7558def test_admin_file_delete_removes_file(tmp_path, monkeypatch):
7559 root = tmp_path / "objects"
7560 data_dir = tmp_path / "data"
7561 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7562 file_path = data_dir / "files" / "site_home" / "assets" / "report.txt"
7563 file_path.parent.mkdir(parents=True)
7564 file_path.write_text("old")
7565 enable_file_writes(monkeypatch, root, data_dir)
7566
7567 status, _, payload = request(
7568 "/admin/files/site_home",
7569 method="DELETE",
7570 query_string="file=assets/report.txt",
7571 headers=auth_headers(),
7572 )
7573
7574 assert status == 200
7575 assert payload["status"] == "ok"
7576 assert payload["operation"] == "deleted"
7577 assert payload["file"]["name"] == "assets/report.txt"
7578 assert not file_path.exists()
7579 assert not file_path.parent.exists()
7580
7581
7582def test_admin_file_upload_enforces_file_size_limit(tmp_path, monkeypatch):
7583 root = tmp_path / "objects"
7584 data_dir = tmp_path / "data"
7585 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
7586 enable_file_writes(monkeypatch, root, data_dir)
7587 monkeypatch.setenv(object_server.MAX_OBJECT_FILE_BYTES_ENV, "4")
7588
7589 status, _, payload = request(
7590 "/admin/files/site_home",
7591 method="POST",
7592 body=json.dumps(
7593 {
7594 "name": "assets/report.txt",
7595 "content_base64": base64.b64encode(b"hello").decode("ascii"),
7596 }
7597 ).encode(),
7598 headers=auth_headers(),
7599 )
7600
7601 assert status == 413
7602 assert payload["status"] == "error"
7603 assert "exceeds max size" in payload["error"]
7604
7605
7606def test_admin_file_upload_requires_existing_object(tmp_path, monkeypatch):
7607 root = tmp_path / "objects"
7608 data_dir = tmp_path / "data"
7609 enable_file_writes(monkeypatch, root, data_dir)
7610
7611 status, _, payload = request(
7612 "/admin/files/site_home",
7613 method="POST",
7614 body=json.dumps(
7615 {
7616 "name": "assets/report.txt",
7617 "content_base64": base64.b64encode(b"hello").decode("ascii"),
7618 }
7619 ).encode(),
7620 headers=auth_headers(),
7621 )
7622
7623 assert status == 404
7624 assert payload["status"] == "error"
7625
7626
7627def test_get_metadata_summarizes_object_storage(tmp_path, monkeypatch):
7628 root = tmp_path / "objects"
7629 data_dir = tmp_path / "data"
7630 source = write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
7631 state_file = data_dir / "state" / "basics_counter" / "state.tsv"
7632 state_file.parent.mkdir(parents=True, exist_ok=True)
7633 state_file.write_text("key\tvalue\ttimestamp\ncount\t3\t1710000000.1\n")
7634 log_file = data_dir / "logs" / "basics_counter" / "log.tsv"
7635 log_file.parent.mkdir(parents=True, exist_ok=True)
7636 log_file.write_text(
7637 "entry_id\ttimestamp\tlevel\tmessage\n"
7638 "a1\t2026-01-01T00:00:00\tINFO\tstarted\n"
7639 )
7640 object_versions.VersionManager(data_dir).save_version(
7641 "basics_counter",
7642 "def GET(request):\n return {}\n",
7643 author="test",
7644 message="first",
7645 )
7646 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7647 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7648 enable_admin_token(monkeypatch)
7649
7650 status, _, payload = request(
7651 "/objects/basics_counter",
7652 query_string="metadata=true",
7653 headers=auth_headers(),
7654 )
7655
7656 assert status == 200
7657 assert payload == {
7658 "status": "ok",
7659 "object_id": "basics_counter",
7660 "metadata": {
7661 "object_id": "basics_counter",
7662 "source_path": "basics/counter.py",
7663 "owner": "system",
7664 "kind": "system",
7665 "last_modified": source.stat().st_mtime,
7666 "state_count": 1,
7667 "state_keys": ["count"],
7668 "log_count": 1,
7669 "file_count": 0,
7670 "version_count": 1,
7671 },
7672 }
7673
7674
7675def test_get_metadata_returns_404_for_missing_object(tmp_path, monkeypatch):
7676 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
7677 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
7678 enable_admin_token(monkeypatch)
7679
7680 status, _, payload = request(
7681 "/objects/missing_object",
7682 query_string="metadata=true",
7683 headers=auth_headers(),
7684 )
7685
7686 assert status == 404
7687 assert payload == {"status": "error", "error": "Object source not found: missing_object"}
7688
7689
7690def test_get_metadata_rejects_invalid_object_id(tmp_path, monkeypatch):
7691 root = tmp_path / "objects"
7692 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7693 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
7694 enable_admin_token(monkeypatch)
7695
7696 status, _, payload = request(
7697 "/objects/bad.id",
7698 query_string="metadata=true",
7699 headers=auth_headers(),
7700 )
7701
7702 assert status == 400
7703 assert payload == {"status": "error", "error": "Invalid object ID: bad.id"}
7704
7705
7706def test_source_update_is_disabled_by_default(tmp_path, monkeypatch):
7707 root = tmp_path / "objects"
7708 source_path = write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
7709 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7710 monkeypatch.delenv("DBBASIC_ENABLE_SOURCE_WRITES", raising=False)
7711 enable_admin_token(monkeypatch)
7712
7713 status, _, payload = request(
7714 "/objects/basics_counter",
7715 method="PUT",
7716 query_string="source=true",
7717 body=json.dumps({"code": "def GET(request):\n return {'count': 1}\n"}).encode(),
7718 headers=auth_headers(),
7719 )
7720
7721 assert status == 403
7722 assert payload["status"] == "error"
7723 assert payload["error"].startswith("Source writes are disabled")
7724 assert source_path.read_text() == "def GET(request):\n return {}\n"
7725
7726
7727def test_source_update_requires_admin_token_configuration(tmp_path, monkeypatch):
7728 root = tmp_path / "objects"
7729 source_path = write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
7730 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7731 monkeypatch.setenv("DBBASIC_ENABLE_SOURCE_WRITES", "true")
7732 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
7733
7734 status, _, payload = request(
7735 "/objects/basics_counter",
7736 method="PUT",
7737 query_string="source=true",
7738 body=json.dumps({"code": "def GET(request):\n return {'count': 1}\n"}).encode(),
7739 )
7740
7741 assert status == 403
7742 assert payload == {"status": "error", "error": "Source writes require DBBASIC_ADMIN_TOKEN."}
7743 assert source_path.read_text() == "def GET(request):\n return {}\n"
7744
7745
7746def test_source_update_requires_authorization_header(tmp_path, monkeypatch):
7747 root = tmp_path / "objects"
7748 source_path = write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
7749 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7750 monkeypatch.setenv("DBBASIC_ENABLE_SOURCE_WRITES", "true")
7751 enable_admin_token(monkeypatch)
7752
7753 status, _, payload = request(
7754 "/objects/basics_counter",
7755 method="PUT",
7756 query_string="source=true",
7757 body=json.dumps({"code": "def GET(request):\n return {'count': 1}\n"}).encode(),
7758 )
7759
7760 assert status == 401
7761 assert payload == {"status": "error", "error": "Unauthorized"}
7762 assert source_path.read_text() == "def GET(request):\n return {}\n"
7763
7764
7765def test_object_create_is_disabled_by_default(tmp_path, monkeypatch):
7766 root = tmp_path / "objects"
7767 data_dir = tmp_path / "data"
7768 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7769 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7770 monkeypatch.delenv("DBBASIC_ENABLE_SOURCE_WRITES", raising=False)
7771 enable_admin_token(monkeypatch)
7772
7773 status, _, payload = request(
7774 "/objects",
7775 method="POST",
7776 body=json.dumps(
7777 {
7778 "object_id": "site_home",
7779 "code": "def GET(request):\n return {'created': True}\n",
7780 }
7781 ).encode(),
7782 headers=auth_headers(),
7783 )
7784
7785 assert status == 403
7786 assert payload["status"] == "error"
7787 assert payload["error"].startswith("Source writes are disabled")
7788 assert not (root / "site" / "home.py").exists()
7789
7790
7791def test_object_create_creates_source_version_and_runs_new_code(tmp_path, monkeypatch):
7792 root = tmp_path / "objects"
7793 data_dir = tmp_path / "data"
7794 enable_source_writes(monkeypatch, root, data_dir)
7795 code = "def GET(request):\n return {'created': True}\n"
7796 correlation_id = "123e4567-e89b-42d3-a456-426614174001"
7797
7798 status, _, payload = request(
7799 "/objects",
7800 method="POST",
7801 body=json.dumps(
7802 {
7803 "object_id": "site_home",
7804 "code": code,
7805 "author": "test-api",
7806 "message": "Create home",
7807 "description": "Home page object",
7808 }
7809 ).encode(),
7810 headers=[*auth_headers(), ("x-dbbasic-correlation-id", correlation_id)],
7811 )
7812
7813 assert status == 201
7814 assert payload == {
7815 "status": "ok",
7816 "message": "Object created: site_home",
7817 "object_id": "site_home",
7818 "version_id": 1,
7819 "methods": ["GET"],
7820 "warnings": [],
7821 "correlation_id": correlation_id,
7822 }
7823 assert (root / "site" / "home.py").read_text() == code
7824
7825 manager = object_versions.VersionManager(data_dir)
7826 saved = manager.get_version("site_home", 1)
7827 assert saved is not None
7828 assert saved["content"] == code
7829 assert saved["author"] == "test-api"
7830 assert saved["message"] == "Create home"
7831 assert saved["correlation_id"] == correlation_id
7832
7833 source_changes = object_source_changes.list_source_changes("site_home", base_dir=data_dir)
7834 assert source_changes["count"] == 1
7835 assert source_changes["changes"][0]["action"] == "source_create"
7836 assert source_changes["changes"][0]["actor"] == "test-api"
7837 assert source_changes["changes"][0]["message"] == "Create home"
7838 assert source_changes["changes"][0]["version_id"] == 1
7839 assert source_changes["changes"][0]["correlation_id"] == correlation_id
7840 assert source_changes["changes"][0]["details"] == {"description": "Home page object"}
7841
7842 status, _, payload = request("/objects/site_home")
7843
7844 assert status == 200
7845 assert payload == {"created": True}
7846
7847
7848def test_admin_object_create_alias_requires_authorization_header(tmp_path, monkeypatch):
7849 root = tmp_path / "objects"
7850 data_dir = tmp_path / "data"
7851 enable_source_writes(monkeypatch, root, data_dir)
7852
7853 status, _, payload = request(
7854 "/admin/objects",
7855 method="POST",
7856 body=json.dumps(
7857 {
7858 "object_id": "site_home",
7859 "code": "def GET(request):\n return {'created': True}\n",
7860 }
7861 ).encode(),
7862 )
7863
7864 assert status == 401
7865 assert payload == {"status": "error", "error": "Unauthorized"}
7866 assert not (root / "site" / "home.py").exists()
7867
7868
7869def test_admin_object_create_alias_respects_source_write_flag(tmp_path, monkeypatch):
7870 root = tmp_path / "objects"
7871 data_dir = tmp_path / "data"
7872 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
7873 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
7874 monkeypatch.delenv("DBBASIC_ENABLE_SOURCE_WRITES", raising=False)
7875 enable_admin_token(monkeypatch)
7876
7877 status, _, payload = request(
7878 "/admin/objects",
7879 method="POST",
7880 body=json.dumps(
7881 {
7882 "object_id": "site_home",
7883 "code": "def GET(request):\n return {'created': True}\n",
7884 }
7885 ).encode(),
7886 headers=auth_headers(),
7887 )
7888
7889 assert status == 403
7890 assert payload["status"] == "error"
7891 assert payload["error"].startswith("Source writes are disabled")
7892 assert not (root / "site" / "home.py").exists()
7893
7894
7895def test_admin_object_create_alias_creates_source_version(tmp_path, monkeypatch):
7896 root = tmp_path / "objects"
7897 data_dir = tmp_path / "data"
7898 enable_source_writes(monkeypatch, root, data_dir)
7899 code = "def GET(request):\n return {'created_from': 'admin'}\n"
7900
7901 status, _, payload = request(
7902 "/admin/objects",
7903 method="POST",
7904 body=json.dumps(
7905 {
7906 "object_id": "site_home",
7907 "code": code,
7908 "author": "scroll",
7909 "message": "Create from Scroll",
7910 }
7911 ).encode(),
7912 headers=auth_headers(),
7913 )
7914
7915 assert status == 201
7916 assert payload["status"] == "ok"
7917 assert payload["object_id"] == "site_home"
7918 assert payload["version_id"] == 1
7919 assert (root / "site" / "home.py").read_text() == code
7920
7921 source_changes = object_source_changes.list_source_changes("site_home", base_dir=data_dir)
7922 assert source_changes["changes"][0]["actor"] == "scroll"
7923 assert source_changes["changes"][0]["message"] == "Create from Scroll"
7924
7925
7926def test_object_create_accepts_legacy_name_owner_shape(tmp_path, monkeypatch):
7927 root = tmp_path / "objects"
7928 data_dir = tmp_path / "data"
7929 enable_source_writes(monkeypatch, root, data_dir)
7930 code = "def GET(request):\n return {'owner': '42'}\n"
7931
7932 status, _, payload = request(
7933 "/objects",
7934 method="POST",
7935 body=json.dumps(
7936 {
7937 "name": "deals",
7938 "owner_user_id": "42",
7939 "code": code,
7940 }
7941 ).encode(),
7942 headers=auth_headers(),
7943 )
7944
7945 assert status == 201
7946 assert payload["object_id"] == "u_42_deals"
7947 assert (root / "users" / "42" / "deals.py").read_text() == code
7948
7949 status, _, payload = request("/objects/u_42_deals")
7950
7951 assert status == 200
7952 assert payload == {"owner": "42"}
7953
7954
7955def test_object_create_uses_admin_session_user_scope_when_enabled(tmp_path, monkeypatch):
7956 root = tmp_path / "objects"
7957 data_dir = tmp_path / "data"
7958 enable_source_writes(monkeypatch, root, data_dir)
7959 monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true")
7960 token, _ = create_identity_session({"user_id": "42", "roles": ["admin"]})
7961 code = "def GET(request):\n return {'session_user': '42'}\n"
7962
7963 status, _, payload = request(
7964 "/objects",
7965 method="POST",
7966 body=json.dumps({"name": "deals", "code": code}).encode(),
7967 headers=session_headers(token),
7968 )
7969
7970 assert status == 201
7971 assert payload["object_id"] == "u_42_deals"
7972 assert (root / "users" / "42" / "deals.py").read_text() == code
7973
7974
7975def test_object_create_rejects_non_admin_session_when_session_admin_gates_enabled(
7976 tmp_path,
7977 monkeypatch,
7978):
7979 root = tmp_path / "objects"
7980 data_dir = tmp_path / "data"
7981 enable_source_writes(monkeypatch, root, data_dir)
7982 monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true")
7983 token, _ = create_identity_session({"user_id": "42", "roles": ["sales"]})
7984
7985 status, _, payload = request(
7986 "/objects",
7987 method="POST",
7988 body=json.dumps(
7989 {
7990 "name": "deals",
7991 "code": "def GET(request):\n return {}\n",
7992 }
7993 ).encode(),
7994 headers=session_headers(token),
7995 )
7996
7997 assert status == 401
7998 assert payload == {"status": "error", "error": "Unauthorized"}
7999 assert not (root / "users" / "42" / "deals.py").exists()
8000
8001
8002def test_object_create_rejects_existing_object(tmp_path, monkeypatch):
8003 root = tmp_path / "objects"
8004 data_dir = tmp_path / "data"
8005 source_path = write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
8006 enable_source_writes(monkeypatch, root, data_dir)
8007
8008 status, _, payload = request(
8009 "/objects",
8010 method="POST",
8011 body=json.dumps(
8012 {
8013 "object_id": "site_home",
8014 "code": "def GET(request):\n return {'created': True}\n",
8015 }
8016 ).encode(),
8017 headers=auth_headers(),
8018 )
8019
8020 assert status == 409
8021 assert payload == {"status": "error", "error": "Object source already exists: site_home"}
8022 assert source_path.read_text() == "def GET(request):\n return {}\n"
8023
8024
8025def test_source_update_accepts_admin_session_when_session_admin_gates_enabled(
8026 tmp_path,
8027 monkeypatch,
8028):
8029 root = tmp_path / "objects"
8030 source_path = write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
8031 data_dir = tmp_path / "data"
8032 enable_source_writes(monkeypatch, root, data_dir)
8033 monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true")
8034 token, _ = create_identity_session({"user_id": "admin-user", "roles": ["admin"]})
8035 new_code = "def GET(request):\n return {'count': 1}\n"
8036
8037 status, _, payload = request(
8038 "/objects/basics_counter",
8039 method="PUT",
8040 query_string="source=true",
8041 body=json.dumps({"code": new_code}).encode(),
8042 headers=session_headers(token),
8043 )
8044
8045 assert status == 200
8046 assert payload["status"] == "ok"
8047 assert payload["object_id"] == "basics_counter"
8048 assert source_path.read_text() == new_code
8049
8050
8051def test_source_update_rejects_non_admin_session_when_session_admin_gates_enabled(
8052 tmp_path,
8053 monkeypatch,
8054):
8055 root = tmp_path / "objects"
8056 source_path = write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
8057 data_dir = tmp_path / "data"
8058 enable_source_writes(monkeypatch, root, data_dir)
8059 monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true")
8060 token, _ = create_identity_session({"user_id": "sales-user", "roles": ["sales"]})
8061
8062 status, _, payload = request(
8063 "/objects/basics_counter",
8064 method="PUT",
8065 query_string="source=true",
8066 body=json.dumps({"code": "def GET(request):\n return {'count': 1}\n"}).encode(),
8067 headers=session_headers(token),
8068 )
8069
8070 assert status == 401
8071 assert payload == {"status": "error", "error": "Unauthorized"}
8072 assert source_path.read_text() == "def GET(request):\n return {}\n"
8073
8074
8075def test_source_update_rejects_invalid_json_body(tmp_path, monkeypatch):
8076 root = tmp_path / "objects"
8077 source_path = write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
8078 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8079 monkeypatch.setenv("DBBASIC_ENABLE_SOURCE_WRITES", "true")
8080 enable_admin_token(monkeypatch)
8081
8082 status, _, payload = request(
8083 "/objects/basics_counter",
8084 method="PUT",
8085 query_string="source=true",
8086 body=b"{",
8087 headers=auth_headers(),
8088 )
8089
8090 assert status == 400
8091 assert payload == {"status": "error", "error": "Invalid JSON body"}
8092 assert source_path.read_text() == "def GET(request):\n return {}\n"
8093
8094
8095def test_source_update_requires_code_string(tmp_path, monkeypatch):
8096 root = tmp_path / "objects"
8097 write_source(root / "basics" / "counter.py", "def GET(request):\n return {}\n")
8098 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8099 monkeypatch.setenv("DBBASIC_ENABLE_SOURCE_WRITES", "true")
8100 enable_admin_token(monkeypatch)
8101
8102 status, _, payload = request(
8103 "/objects/basics_counter",
8104 method="PUT",
8105 query_string="source=true",
8106 body=json.dumps({"source": "wrong field"}).encode(),
8107 headers=auth_headers(),
8108 )
8109
8110 assert status == 400
8111 assert payload == {
8112 "status": "error",
8113 "error": "Request JSON field 'code' must be a string",
8114 }
8115
8116
8117def test_source_update_versions_source_and_immediately_runs_new_code(tmp_path, monkeypatch):
8118 root = tmp_path / "objects"
8119 source_path = write_source(
8120 root / "basics" / "counter.py",
8121 "def GET(request):\n return {'count': 1}\n",
8122 )
8123 data_dir = tmp_path / "data"
8124 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8125 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
8126 monkeypatch.setenv("DBBASIC_ENABLE_SOURCE_WRITES", "true")
8127 enable_admin_token(monkeypatch)
8128 new_code = "def GET(request):\n return {'count': 2}\n"
8129 correlation_id = "123e4567-e89b-42d3-a456-426614174000"
8130
8131 status, _, payload = request(
8132 "/objects/basics_counter",
8133 method="PUT",
8134 query_string="source=true",
8135 body=json.dumps(
8136 {
8137 "code": new_code,
8138 "author": "test-api",
8139 "message": "Update counter",
8140 }
8141 ).encode(),
8142 headers=[*auth_headers(), ("x-dbbasic-correlation-id", correlation_id)],
8143 )
8144
8145 assert status == 200
8146 assert payload == {
8147 "status": "ok",
8148 "message": "Code updated to version 1",
8149 "version_id": 1,
8150 "object_id": "basics_counter",
8151 "methods": ["GET"],
8152 "warnings": [],
8153 "correlation_id": correlation_id,
8154 }
8155 assert source_path.read_text() == new_code
8156
8157 manager = object_versions.VersionManager(data_dir)
8158 saved = manager.get_version("basics_counter", 1)
8159 assert saved is not None
8160 assert saved["content"] == new_code
8161 assert saved["author"] == "test-api"
8162 assert saved["message"] == "Update counter"
8163 assert saved["correlation_id"] == correlation_id
8164
8165 logs = object_logs.get_object_logs("basics_counter", base_dir=data_dir)
8166 assert logs[0]["action"] == "source_update"
8167 assert logs[0]["version_id"] == "1"
8168 assert logs[0]["correlation_id"] == correlation_id
8169
8170 source_changes = object_source_changes.list_source_changes(
8171 "basics_counter",
8172 base_dir=data_dir,
8173 )
8174 assert source_changes["count"] == 1
8175 assert source_changes["changes"][0]["action"] == "source_update"
8176 assert source_changes["changes"][0]["actor"] == "test-api"
8177 assert source_changes["changes"][0]["message"] == "Update counter"
8178 assert source_changes["changes"][0]["version_id"] == 1
8179 assert source_changes["changes"][0]["from_version_id"] is None
8180 assert source_changes["changes"][0]["correlation_id"] == correlation_id
8181
8182 status, _, payload = request("/objects/basics_counter")
8183
8184 assert status == 200
8185 assert payload == {"count": 2}
8186
8187
8188def test_admin_object_source_update_alias_requires_authorization_header(tmp_path, monkeypatch):
8189 root = tmp_path / "objects"
8190 source_path = write_source(
8191 root / "basics" / "counter.py",
8192 "def GET(request):\n return {'count': 1}\n",
8193 )
8194 data_dir = tmp_path / "data"
8195 enable_source_writes(monkeypatch, root, data_dir)
8196
8197 status, _, payload = request(
8198 "/admin/objects/basics_counter",
8199 method="PUT",
8200 query_string="source=true",
8201 body=json.dumps(
8202 {"code": "def GET(request):\n return {'count': 2}\n"}
8203 ).encode(),
8204 )
8205
8206 assert status == 401
8207 assert payload == {"status": "error", "error": "Unauthorized"}
8208 assert source_path.read_text() == "def GET(request):\n return {'count': 1}\n"
8209
8210
8211def test_admin_object_source_update_alias_versions_source(tmp_path, monkeypatch):
8212 root = tmp_path / "objects"
8213 source_path = write_source(
8214 root / "basics" / "counter.py",
8215 "def GET(request):\n return {'count': 1}\n",
8216 )
8217 data_dir = tmp_path / "data"
8218 enable_source_writes(monkeypatch, root, data_dir)
8219 new_code = "def GET(request):\n return {'count': 2}\n"
8220
8221 status, _, payload = request(
8222 "/admin/objects/basics_counter",
8223 method="PUT",
8224 query_string="source=true",
8225 body=json.dumps(
8226 {
8227 "code": new_code,
8228 "author": "scroll",
8229 "message": "Update from Scroll",
8230 }
8231 ).encode(),
8232 headers=auth_headers(),
8233 )
8234
8235 assert status == 200
8236 assert payload["status"] == "ok"
8237 assert payload["object_id"] == "basics_counter"
8238 assert payload["version_id"] == 1
8239 assert source_path.read_text() == new_code
8240
8241 manager = object_versions.VersionManager(data_dir)
8242 saved = manager.get_version("basics_counter", 1)
8243 assert saved is not None
8244 assert saved["content"] == new_code
8245 assert saved["author"] == "scroll"
8246 assert saved["message"] == "Update from Scroll"
8247
8248 source_changes = object_source_changes.list_source_changes(
8249 "basics_counter",
8250 base_dir=data_dir,
8251 )
8252 assert source_changes["changes"][0]["actor"] == "scroll"
8253 assert source_changes["changes"][0]["action"] == "source_update"
8254
8255
8256def test_admin_object_put_without_source_query_does_not_execute_object(tmp_path, monkeypatch):
8257 root = tmp_path / "objects"
8258 data_dir = tmp_path / "data"
8259 source_path = write_source(
8260 root / "basics" / "counter.py",
8261 "def PUT(request):\n return {'executed': True}\n",
8262 )
8263 enable_source_writes(monkeypatch, root, data_dir)
8264
8265 status, _, payload = request(
8266 "/admin/objects/basics_counter",
8267 method="PUT",
8268 body=json.dumps({"value": 1}).encode(),
8269 headers=auth_headers(),
8270 )
8271
8272 assert status == 405
8273 assert payload == {"status": "error", "error": "Method not allowed"}
8274 assert source_path.read_text() == "def PUT(request):\n return {'executed': True}\n"
8275
8276
8277def test_versions_endpoint_lists_history_newest_first_without_content(tmp_path, monkeypatch):
8278 root = tmp_path / "objects"
8279 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 0}\n")
8280 data_dir = tmp_path / "data"
8281 enable_source_writes(monkeypatch, root, data_dir)
8282
8283 update_source(
8284 "basics_counter",
8285 "def GET(request):\n return {'count': 1}\n",
8286 message="first",
8287 )
8288 update_source(
8289 "basics_counter",
8290 "def GET(request):\n return {'count': 2}\n",
8291 message="second",
8292 )
8293
8294 status, _, payload = request(
8295 "/objects/basics_counter",
8296 query_string="versions=true&limit=10",
8297 headers=auth_headers(),
8298 )
8299
8300 assert status == 200
8301 assert payload["status"] == "ok"
8302 assert payload["object_id"] == "basics_counter"
8303 assert payload["count"] == 2
8304 assert [version["version_id"] for version in payload["versions"]] == [2, 1]
8305 assert [version["message"] for version in payload["versions"]] == ["second", "first"]
8306 assert all("content" not in version for version in payload["versions"])
8307
8308 status, _, payload = request(
8309 "/objects/basics_counter",
8310 query_string="versions=true&limit=1",
8311 headers=auth_headers(),
8312 )
8313
8314 assert status == 200
8315 assert payload["count"] == 1
8316 assert [version["version_id"] for version in payload["versions"]] == [2]
8317
8318
8319def test_versions_endpoint_rejects_bad_limit(tmp_path, monkeypatch):
8320 root = tmp_path / "objects"
8321 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 0}\n")
8322 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8323 enable_admin_token(monkeypatch)
8324
8325 status, _, payload = request(
8326 "/objects/basics_counter",
8327 query_string="versions=true&limit=0",
8328 headers=auth_headers(),
8329 )
8330
8331 assert status == 400
8332 assert payload == {"status": "error", "error": "Query parameter 'limit' must be at least 1"}
8333
8334
8335def test_source_changes_endpoint_lists_history_newest_first(tmp_path, monkeypatch):
8336 root = tmp_path / "objects"
8337 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 0}\n")
8338 data_dir = tmp_path / "data"
8339 enable_source_writes(monkeypatch, root, data_dir)
8340 first_correlation_id = "123e4567-e89b-42d3-a456-426614174000"
8341 second_correlation_id = "123e4567-e89b-42d3-a456-426614174001"
8342
8343 status, _, _ = request(
8344 "/objects/basics_counter",
8345 method="PUT",
8346 query_string="source=true",
8347 body=json.dumps(
8348 {
8349 "code": "def GET(request):\n return {'count': 1}\n",
8350 "author": "first-author",
8351 "message": "first edit",
8352 }
8353 ).encode(),
8354 headers=[*auth_headers(), ("x-dbbasic-correlation-id", first_correlation_id)],
8355 )
8356 assert status == 200
8357 status, _, _ = request(
8358 "/objects/basics_counter",
8359 method="PUT",
8360 query_string="source=true",
8361 body=json.dumps(
8362 {
8363 "code": "def GET(request):\n return {'count': 2}\n",
8364 "author": "second-author",
8365 "message": "second edit",
8366 }
8367 ).encode(),
8368 headers=[*auth_headers(), ("x-dbbasic-correlation-id", second_correlation_id)],
8369 )
8370 assert status == 200
8371
8372 status, _, payload = request(
8373 "/objects/basics_counter",
8374 query_string="source_changes=true&limit=1",
8375 headers=auth_headers(),
8376 )
8377
8378 assert status == 200
8379 assert payload["status"] == "ok"
8380 assert payload["object_id"] == "basics_counter"
8381 assert payload["count"] == 1
8382 assert payload["total"] == 2
8383 assert payload["has_more"] is True
8384 assert payload["changes"][0]["action"] == "source_update"
8385 assert payload["changes"][0]["actor"] == "second-author"
8386 assert payload["changes"][0]["message"] == "second edit"
8387 assert payload["changes"][0]["version_id"] == 2
8388 assert payload["changes"][0]["correlation_id"] == second_correlation_id
8389
8390
8391def test_source_changes_endpoint_requires_authorization_header(tmp_path, monkeypatch):
8392 root = tmp_path / "objects"
8393 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 0}\n")
8394 data_dir = tmp_path / "data"
8395 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8396 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
8397 enable_admin_token(monkeypatch)
8398
8399 status, _, payload = request(
8400 "/objects/basics_counter",
8401 query_string="source_changes=true",
8402 )
8403
8404 assert status == 401
8405 assert payload == {"status": "error", "error": "Unauthorized"}
8406
8407
8408def test_admin_changes_lists_normalized_history(tmp_path, monkeypatch):
8409 root = tmp_path / "objects"
8410 data_dir = tmp_path / "data"
8411 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
8412 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8413 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
8414 enable_admin_token(monkeypatch)
8415
8416 source_change = object_source_changes.append_source_change(
8417 object_id="site_home",
8418 action="source_update",
8419 version_id=1,
8420 actor="source-admin",
8421 correlation_id="source-correlation",
8422 base_dir=data_dir,
8423 )
8424 file_change = object_file_changes.append_file_change(
8425 object_id="site_home",
8426 action="file_create",
8427 file_name="assets/report.txt",
8428 file_size=5,
8429 actor="file-admin",
8430 correlation_id="file-correlation",
8431 base_dir=data_dir,
8432 )
8433 record_change = object_record_changes.append_record_change(
8434 collection="contacts",
8435 record_id="rec_1",
8436 action="create",
8437 before=None,
8438 after={"id": "rec_1", "name": "Alice"},
8439 actor="record-admin",
8440 base_dir=data_dir,
8441 )
8442 package_change = object_package_changes.append_package_change(
8443 package_id="hello-world",
8444 action="dry_run",
8445 package_version="0.1.0",
8446 actor="package-admin",
8447 base_dir=data_dir,
8448 )
8449
8450 status, _, payload = request("/admin/changes", headers=auth_headers())
8451
8452 assert status == 200
8453 assert payload["status"] == "ok"
8454 assert payload["count"] == 4
8455 assert payload["total"] == 4
8456 by_kind = {entry["kind"]: entry for entry in payload["changes"]}
8457 assert by_kind["source"]["change_id"] == source_change["change_id"]
8458 assert by_kind["source"]["target"]["object_id"] == "site_home"
8459 assert by_kind["source"]["correlation_id"] == "source-correlation"
8460 assert by_kind["file"]["change_id"] == file_change["change_id"]
8461 assert by_kind["file"]["target"]["file_name"] == "assets/report.txt"
8462 assert by_kind["file"]["correlation_id"] == "file-correlation"
8463 assert by_kind["record"]["change_id"] == record_change["change_id"]
8464 assert by_kind["record"]["target"]["collection"] == "contacts"
8465 assert by_kind["record"]["target"]["record_id"] == "rec_1"
8466 assert by_kind["package"]["change_id"] == package_change["change_id"]
8467 assert by_kind["package"]["target"]["package_id"] == "hello-world"
8468
8469
8470def test_admin_changes_filters_by_kind_object_and_file(tmp_path, monkeypatch):
8471 root = tmp_path / "objects"
8472 data_dir = tmp_path / "data"
8473 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
8474 write_source(root / "site" / "about.py", "def GET(request):\n return {}\n")
8475 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8476 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
8477 enable_admin_token(monkeypatch)
8478
8479 object_file_changes.append_file_change(
8480 object_id="site_home",
8481 action="file_create",
8482 file_name="assets/report.txt",
8483 base_dir=data_dir,
8484 )
8485 object_file_changes.append_file_change(
8486 object_id="site_about",
8487 action="file_create",
8488 file_name="assets/report.txt",
8489 base_dir=data_dir,
8490 )
8491 object_source_changes.append_source_change(
8492 object_id="site_home",
8493 action="source_update",
8494 version_id=1,
8495 base_dir=data_dir,
8496 )
8497
8498 status, _, payload = request(
8499 "/admin/changes",
8500 query_string="kind=file&object_id=site_home&file=assets/report.txt",
8501 headers=auth_headers(),
8502 )
8503
8504 assert status == 200
8505 assert payload["count"] == 1
8506 assert payload["filters"]["kind"] == "file"
8507 assert payload["filters"]["object_id"] == "site_home"
8508 assert payload["changes"][0]["kind"] == "file"
8509 assert payload["changes"][0]["target"]["object_id"] == "site_home"
8510 assert payload["changes"][0]["target"]["file_name"] == "assets/report.txt"
8511
8512
8513def test_admin_changes_requires_authorization_header(tmp_path, monkeypatch):
8514 data_dir = tmp_path / "data"
8515 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
8516 enable_admin_token(monkeypatch)
8517
8518 status, _, payload = request("/admin/changes")
8519
8520 assert status == 401
8521 assert payload == {"status": "error", "error": "Unauthorized"}
8522
8523
8524def test_object_changes_endpoint_lists_source_and_file_history(tmp_path, monkeypatch):
8525 root = tmp_path / "objects"
8526 data_dir = tmp_path / "data"
8527 write_source(root / "site" / "home.py", "def GET(request):\n return {}\n")
8528 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8529 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
8530 enable_admin_token(monkeypatch)
8531 object_source_changes.append_source_change(
8532 object_id="site_home",
8533 action="source_update",
8534 version_id=1,
8535 base_dir=data_dir,
8536 )
8537 object_file_changes.append_file_change(
8538 object_id="site_home",
8539 action="file_create",
8540 file_name="assets/report.txt",
8541 base_dir=data_dir,
8542 )
8543
8544 status, _, payload = request(
8545 "/admin/objects/site_home",
8546 query_string="changes=true",
8547 headers=auth_headers(),
8548 )
8549
8550 assert status == 200
8551 assert payload["status"] == "ok"
8552 assert payload["object_id"] == "site_home"
8553 assert payload["count"] == 2
8554 assert {entry["kind"] for entry in payload["changes"]} == {"source", "file"}
8555
8556
8557def test_specific_version_endpoint_returns_content(tmp_path, monkeypatch):
8558 root = tmp_path / "objects"
8559 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 0}\n")
8560 data_dir = tmp_path / "data"
8561 enable_source_writes(monkeypatch, root, data_dir)
8562 v1_code = "def GET(request):\n return {'count': 1}\n"
8563
8564 update_source("basics_counter", v1_code, message="first")
8565
8566 status, _, payload = request(
8567 "/objects/basics_counter",
8568 query_string="version=1",
8569 headers=auth_headers(),
8570 )
8571
8572 assert status == 200
8573 assert payload["status"] == "ok"
8574 assert payload["object_id"] == "basics_counter"
8575 assert payload["version"]["version_id"] == 1
8576 assert payload["version"]["content"] == v1_code
8577 assert payload["version"]["message"] == "first"
8578
8579
8580def test_specific_version_endpoint_returns_404_for_missing_version(tmp_path, monkeypatch):
8581 root = tmp_path / "objects"
8582 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 0}\n")
8583 data_dir = tmp_path / "data"
8584 enable_source_writes(monkeypatch, root, data_dir)
8585
8586 status, _, payload = request(
8587 "/objects/basics_counter",
8588 query_string="version=99",
8589 headers=auth_headers(),
8590 )
8591
8592 assert status == 404
8593 assert payload == {
8594 "status": "error",
8595 "error": "Version 99 not found for object basics_counter",
8596 }
8597
8598
8599def test_specific_version_endpoint_rejects_bad_version_id(tmp_path, monkeypatch):
8600 root = tmp_path / "objects"
8601 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 0}\n")
8602 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8603 enable_admin_token(monkeypatch)
8604
8605 status, _, payload = request(
8606 "/objects/basics_counter",
8607 query_string="version=bad",
8608 headers=auth_headers(),
8609 )
8610
8611 assert status == 400
8612 assert payload == {"status": "error", "error": "Query parameter 'version' must be an integer"}
8613
8614
8615def test_rollback_requires_source_write_gate(tmp_path, monkeypatch):
8616 root = tmp_path / "objects"
8617 source_path = write_source(
8618 root / "basics" / "counter.py",
8619 "def GET(request):\n return {'count': 0}\n",
8620 )
8621 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8622 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
8623 monkeypatch.delenv("DBBASIC_ENABLE_SOURCE_WRITES", raising=False)
8624 enable_admin_token(monkeypatch)
8625
8626 status, _, payload = request(
8627 "/objects/basics_counter",
8628 method="POST",
8629 body=json.dumps({"action": "rollback", "version_id": 1}).encode(),
8630 headers=auth_headers(),
8631 )
8632
8633 assert status == 403
8634 assert payload["status"] == "error"
8635 assert payload["error"].startswith("Source writes are disabled")
8636 assert source_path.read_text() == "def GET(request):\n return {'count': 0}\n"
8637
8638
8639def test_rollback_versions_source_and_immediately_runs_old_code(tmp_path, monkeypatch):
8640 root = tmp_path / "objects"
8641 source_path = write_source(
8642 root / "basics" / "counter.py",
8643 "def GET(request):\n return {'count': 0}\n",
8644 )
8645 data_dir = tmp_path / "data"
8646 enable_source_writes(monkeypatch, root, data_dir)
8647 v1_code = "def GET(request):\n return {'count': 1}\n"
8648 v2_code = "def GET(request):\n return {'count': 2}\n"
8649 correlation_id = "123e4567-e89b-42d3-a456-426614174000"
8650
8651 update_source("basics_counter", v1_code, message="first")
8652 update_source("basics_counter", v2_code, message="second")
8653
8654 status, _, payload = request("/objects/basics_counter")
8655
8656 assert status == 200
8657 assert payload == {"count": 2}
8658
8659 status, _, payload = request(
8660 "/objects/basics_counter",
8661 method="POST",
8662 body=json.dumps(
8663 {
8664 "action": "rollback",
8665 "version_id": 1,
8666 "author": "test-api",
8667 "message": "Rollback to first",
8668 }
8669 ).encode(),
8670 headers=[*auth_headers(), ("x-dbbasic-correlation-id", correlation_id)],
8671 )
8672
8673 assert status == 200
8674 assert payload == {
8675 "status": "ok",
8676 "message": "Rolled back to version 1",
8677 "version_id": 1,
8678 "new_version_id": 3,
8679 "object_id": "basics_counter",
8680 "correlation_id": correlation_id,
8681 }
8682 assert source_path.read_text() == v1_code
8683
8684 status, _, payload = request("/objects/basics_counter")
8685
8686 assert status == 200
8687 assert payload == {"count": 1}
8688
8689 manager = object_versions.VersionManager(data_dir)
8690 assert [row["version_id"] for row in manager.get_history("basics_counter")] == [3, 2, 1]
8691 latest = manager.get_version("basics_counter")
8692 assert latest is not None
8693 assert latest["content"] == v1_code
8694 assert latest["message"] == "Rollback to first"
8695 assert latest["correlation_id"] == correlation_id
8696
8697 logs = object_logs.get_object_logs("basics_counter", base_dir=data_dir)
8698 rollback_logs = [entry for entry in logs if entry.get("action") == "source_rollback"]
8699 assert rollback_logs[-1]["correlation_id"] == correlation_id
8700 assert rollback_logs[-1]["version_id"] == "3"
8701 assert rollback_logs[-1]["from_version_id"] == "1"
8702
8703 source_changes = object_source_changes.list_source_changes(
8704 "basics_counter",
8705 base_dir=data_dir,
8706 )
8707 assert source_changes["changes"][0]["action"] == "source_rollback"
8708 assert source_changes["changes"][0]["actor"] == "test-api"
8709 assert source_changes["changes"][0]["message"] == "Rollback to first"
8710 assert source_changes["changes"][0]["version_id"] == 3
8711 assert source_changes["changes"][0]["from_version_id"] == 1
8712 assert source_changes["changes"][0]["correlation_id"] == correlation_id
8713
8714
8715def test_rollback_returns_404_for_missing_version(tmp_path, monkeypatch):
8716 root = tmp_path / "objects"
8717 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 0}\n")
8718 data_dir = tmp_path / "data"
8719 enable_source_writes(monkeypatch, root, data_dir)
8720
8721 status, _, payload = request(
8722 "/objects/basics_counter",
8723 method="POST",
8724 body=json.dumps({"action": "rollback", "version_id": 99}).encode(),
8725 headers=auth_headers(),
8726 )
8727
8728 assert status == 404
8729 assert payload == {
8730 "status": "error",
8731 "error": "Version 99 not found for object basics_counter",
8732 }
8733
8734
8735def test_post_object_execution_runs_post_method_with_json_body_and_query_merge(
8736 tmp_path,
8737 monkeypatch,
8738):
8739 root = tmp_path / "objects"
8740 write_source(
8741 root / "basics" / "echo.py",
8742 "def POST(request):\n return {'request': request}\n",
8743 )
8744 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8745
8746 status, _, payload = request(
8747 "/objects/basics_echo",
8748 method="POST",
8749 query_string="name=query&mode=test",
8750 body=json.dumps({"name": "body", "count": 2}).encode(),
8751 )
8752
8753 assert status == 200
8754 assert payload == {"request": {"name": "body", "count": 2, "mode": "test", "_identity": ANONYMOUS_IDENTITY}}
8755
8756
8757def test_post_object_execution_parses_form_encoded_bodies(tmp_path, monkeypatch):
8758 root = tmp_path / "objects"
8759 write_source(
8760 root / "basics" / "form.py",
8761 "def POST(request):\n return {'request': request}\n",
8762 )
8763 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8764
8765 status, _, payload = request(
8766 "/objects/basics_form",
8767 method="POST",
8768 query_string="mode=test",
8769 body=urllib.parse.urlencode({"note": "hello world", "tags": "a,b"}).encode(),
8770 headers=[("content-type", "application/x-www-form-urlencoded; charset=utf-8")],
8771 )
8772
8773 assert status == 200
8774 assert payload == {
8775 "request": {
8776 "note": "hello world",
8777 "tags": "a,b",
8778 "mode": "test",
8779 "_identity": ANONYMOUS_IDENTITY,
8780 }
8781 }
8782
8783
8784def test_put_object_execution_parses_form_encoded_bodies(tmp_path, monkeypatch):
8785 root = tmp_path / "objects"
8786 write_source(
8787 root / "basics" / "form.py",
8788 "def PUT(request):\n return {'request': request}\n",
8789 )
8790 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8791
8792 status, _, payload = request(
8793 "/objects/basics_form",
8794 method="PUT",
8795 body=urllib.parse.urlencode({"name": "Alice"}).encode(),
8796 headers=[("content-type", "application/x-www-form-urlencoded")],
8797 )
8798
8799 assert status == 200
8800 assert payload == {"request": {"name": "Alice", "_identity": ANONYMOUS_IDENTITY}}
8801
8802
8803def test_post_object_execution_passes_raw_body_for_non_json(tmp_path, monkeypatch):
8804 root = tmp_path / "objects"
8805 write_source(
8806 root / "basics" / "raw.py",
8807 "def POST(request):\n"
8808 " return {'body_size': len(request['body']), 'mode': request['mode']}\n",
8809 )
8810 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8811
8812 status, _, payload = request(
8813 "/objects/basics_raw",
8814 method="POST",
8815 query_string="mode=raw",
8816 body=b"not-json",
8817 )
8818
8819 assert status == 200
8820 assert payload == {"body_size": 8, "mode": "raw"}
8821
8822
8823def test_request_body_limit_allows_body_at_configured_limit(tmp_path, monkeypatch):
8824 root = tmp_path / "objects"
8825 write_source(
8826 root / "basics" / "echo.py",
8827 "def POST(request):\n return {'request': request}\n",
8828 )
8829 body = json.dumps({"name": "body"}).encode()
8830 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8831 monkeypatch.setenv(object_server.MAX_REQUEST_BYTES_ENV, str(len(body)))
8832
8833 status, _, payload = request("/objects/basics_echo", method="POST", body=body)
8834
8835 assert status == 200
8836 assert payload == {"request": {"name": "body", "_identity": ANONYMOUS_IDENTITY}}
8837
8838
8839def test_request_body_limit_rejects_oversized_json_body(tmp_path, monkeypatch):
8840 root = tmp_path / "objects"
8841 write_source(root / "basics" / "echo.py", "def POST(request):\n return {'ok': True}\n")
8842 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8843 monkeypatch.setenv(object_server.MAX_REQUEST_BYTES_ENV, "7")
8844
8845 status, _, payload = request(
8846 "/objects/basics_echo",
8847 method="POST",
8848 body=json.dumps({"name": "body"}).encode(),
8849 )
8850
8851 assert status == 413
8852 assert payload == {
8853 "status": "error",
8854 "error": "Request body too large",
8855 "max_bytes": 7,
8856 }
8857
8858
8859def test_request_body_limit_rejects_large_content_length(monkeypatch):
8860 monkeypatch.setenv(object_server.MAX_REQUEST_BYTES_ENV, "2")
8861
8862 status, _, payload = request(
8863 "/objects/basics_echo",
8864 method="POST",
8865 body=b"{}",
8866 headers=[("content-length", "3")],
8867 )
8868
8869 assert status == 413
8870 assert payload == {
8871 "status": "error",
8872 "error": "Request body too large",
8873 "max_bytes": 2,
8874 }
8875
8876
8877def test_request_body_limit_rejects_oversized_chunked_body(tmp_path, monkeypatch):
8878 root = tmp_path / "objects"
8879 write_source(root / "basics" / "raw.py", "def POST(request):\n return {'ok': True}\n")
8880 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8881 monkeypatch.setenv(object_server.MAX_REQUEST_BYTES_ENV, "8")
8882
8883 status, _, payload = request(
8884 "/objects/basics_raw",
8885 method="POST",
8886 body_chunks=[b"not-json", b"-oversized"],
8887 )
8888
8889 assert status == 413
8890 assert payload == {
8891 "status": "error",
8892 "error": "Request body too large",
8893 "max_bytes": 8,
8894 }
8895
8896
8897def test_post_object_execution_rejects_non_object_json(tmp_path, monkeypatch):
8898 root = tmp_path / "objects"
8899 write_source(root / "basics" / "poster.py", "def POST(request):\n return {}\n")
8900 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8901
8902 status, _, payload = request(
8903 "/objects/basics_poster",
8904 method="POST",
8905 body=json.dumps(["not", "an", "object"]).encode(),
8906 )
8907
8908 assert status == 400
8909 assert payload == {"status": "error", "error": "JSON body must be an object"}
8910
8911
8912def test_post_object_execution_returns_405_when_post_is_missing(tmp_path, monkeypatch):
8913 root = tmp_path / "objects"
8914 write_source(root / "basics" / "getter.py", "def GET(request):\n return {'ok': True}\n")
8915 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8916
8917 status, _, payload = request("/objects/basics_getter", method="POST", body=b"{}")
8918
8919 assert status == 405
8920 assert payload["status"] == "error"
8921 assert payload["error"].startswith("Execution failed: Method POST not supported")
8922
8923
8924def test_put_object_execution_runs_put_method_with_json_body(tmp_path, monkeypatch):
8925 root = tmp_path / "objects"
8926 write_source(
8927 root / "basics" / "profile.py",
8928 "def PUT(request):\n return {'request': request}\n",
8929 )
8930 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8931
8932 status, _, payload = request(
8933 "/objects/basics_profile",
8934 method="PUT",
8935 query_string="query_value=ignored",
8936 body=json.dumps({"name": "Alice"}).encode(),
8937 )
8938
8939 assert status == 200
8940 assert payload == {"request": {"name": "Alice", "_identity": ANONYMOUS_IDENTITY}}
8941
8942
8943def test_put_object_execution_uses_query_params_when_body_is_empty(tmp_path, monkeypatch):
8944 root = tmp_path / "objects"
8945 write_source(
8946 root / "basics" / "profile.py",
8947 "def PUT(request):\n return {'request': request}\n",
8948 )
8949 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8950
8951 status, _, payload = request(
8952 "/objects/basics_profile",
8953 method="PUT",
8954 query_string="name=Alice",
8955 )
8956
8957 assert status == 200
8958 assert payload == {"request": {"name": "Alice", "_identity": ANONYMOUS_IDENTITY}}
8959
8960
8961def test_put_object_execution_rejects_invalid_json(tmp_path, monkeypatch):
8962 root = tmp_path / "objects"
8963 write_source(root / "basics" / "profile.py", "def PUT(request):\n return {}\n")
8964 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8965
8966 status, _, payload = request("/objects/basics_profile", method="PUT", body=b"{")
8967
8968 assert status == 400
8969 assert payload == {"status": "error", "error": "Invalid JSON body"}
8970
8971
8972def test_delete_object_execution_runs_delete_method_with_json_body(tmp_path, monkeypatch):
8973 root = tmp_path / "objects"
8974 write_source(
8975 root / "basics" / "items.py",
8976 "def DELETE(request):\n return {'deleted': request['id']}\n",
8977 )
8978 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8979
8980 status, _, payload = request(
8981 "/objects/basics_items",
8982 method="DELETE",
8983 body=json.dumps({"id": "item-1"}).encode(),
8984 )
8985
8986 assert status == 200
8987 assert payload == {"deleted": "item-1"}
8988
8989
8990def test_delete_object_execution_rejects_invalid_json(tmp_path, monkeypatch):
8991 root = tmp_path / "objects"
8992 write_source(root / "basics" / "items.py", "def DELETE(request):\n return {}\n")
8993 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
8994
8995 status, _, payload = request("/objects/basics_items", method="DELETE", body=b"{")
8996
8997 assert status == 400
8998 assert payload == {"status": "error", "error": "Invalid JSON body"}
8999
9000
9001def test_object_execution_runs_get_method(tmp_path, monkeypatch):
9002 root = tmp_path / "objects"
9003 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 1}\n")
9004 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9005
9006 status, _, payload = request("/objects/basics_counter")
9007
9008 assert status == 200
9009 assert payload == {"count": 1}
9010
9011
9012def test_object_execution_returns_html_content_type_response(tmp_path, monkeypatch):
9013 root = tmp_path / "objects"
9014 write_source(
9015 root / "site" / "home.py",
9016 "def GET(request):\n"
9017 " return {\n"
9018 " 'content_type': 'text/html; charset=utf-8',\n"
9019 " 'body': '<!doctype html><h1>DBBASIC</h1>',\n"
9020 " }\n",
9021 )
9022 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9023
9024 status, headers, body = raw_request("/objects/site_home")
9025
9026 assert status == 200
9027 assert headers[b"content-type"] == b"text/html; charset=utf-8"
9028 assert body == b"<!doctype html><h1>DBBASIC</h1>"
9029
9030
9031def test_object_execution_returns_binary_content_type_response(tmp_path, monkeypatch):
9032 root = tmp_path / "objects"
9033 write_source(
9034 root / "basics" / "image.py",
9035 "def GET(request):\n"
9036 " return {\n"
9037 " 'content_type': 'image/png',\n"
9038 " 'body': b'\\x89PNG',\n"
9039 " }\n",
9040 )
9041 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9042
9043 status, headers, body = raw_request("/objects/basics_image")
9044
9045 assert status == 200
9046 assert headers[b"content-type"] == b"image/png"
9047 assert body == b"\x89PNG"
9048
9049
9050def test_object_execution_returns_response_tuple(tmp_path, monkeypatch):
9051 root = tmp_path / "objects"
9052 write_source(
9053 root / "basics" / "created.py",
9054 "def POST(request):\n"
9055 " return (201, [('Content-Type', 'text/plain'), ('X-Object', 'created')], [b'ok'])\n",
9056 )
9057 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9058
9059 status, headers, body = raw_request("/objects/basics_created", method="POST")
9060
9061 assert status == 201
9062 assert headers[b"content-type"] == b"text/plain"
9063 assert headers[b"x-object"] == b"created"
9064 assert body == b"ok"
9065
9066
9067def test_object_execution_returns_plain_string_as_html(tmp_path, monkeypatch):
9068 root = tmp_path / "objects"
9069 write_source(root / "site" / "home.py", "def GET(request):\n return '<h1>DBBASIC</h1>'\n")
9070 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9071
9072 status, headers, body = raw_request("/objects/site_home")
9073
9074 assert status == 200
9075 assert headers[b"content-type"] == b"text/html; charset=utf-8"
9076 assert body == b"<h1>DBBASIC</h1>"
9077
9078
9079def test_object_execution_appends_success_log(tmp_path, monkeypatch):
9080 root = tmp_path / "objects"
9081 data_dir = tmp_path / "data"
9082 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'count': 1}\n")
9083 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9084 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9085 enable_admin_token(monkeypatch)
9086
9087 status, _, payload = request("/objects/basics_counter")
9088 assert status == 200
9089 assert payload == {"count": 1}
9090
9091 status, _, payload = request(
9092 "/objects/basics_counter",
9093 query_string="logs=true",
9094 headers=auth_headers(),
9095 )
9096
9097 assert status == 200
9098 assert payload["count"] == 1
9099 log = payload["logs"][0]
9100 assert log["level"] == "DEBUG"
9101 assert log["message"] == "GET completed successfully"
9102 assert log["method"] == "GET"
9103 assert log["status"] == "success"
9104 assert float(log["duration_ms"]) >= 0
9105
9106
9107def test_object_execution_state_manager_persists_state(tmp_path, monkeypatch):
9108 root = tmp_path / "objects"
9109 data_dir = tmp_path / "data"
9110 write_source(
9111 root / "basics" / "counter.py",
9112 "_state_manager = None\n"
9113 "def GET(request):\n"
9114 " count = _state_manager.get('count', 0) + 1\n"
9115 " _state_manager.set('count', count)\n"
9116 " return {'count': count}\n",
9117 )
9118 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9119 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9120 enable_admin_token(monkeypatch)
9121
9122 assert request("/objects/basics_counter")[2] == {"count": 1}
9123 assert request("/objects/basics_counter")[2] == {"count": 2}
9124
9125 status, _, payload = request(
9126 "/objects/basics_counter",
9127 query_string="state=true",
9128 headers=auth_headers(),
9129 )
9130
9131 assert status == 200
9132 assert payload == {
9133 "status": "ok",
9134 "object_id": "basics_counter",
9135 "state": {"count": 2},
9136 }
9137
9138
9139def test_object_execution_logger_writes_object_logs(tmp_path, monkeypatch):
9140 root = tmp_path / "objects"
9141 data_dir = tmp_path / "data"
9142 write_source(
9143 root / "basics" / "counter.py",
9144 "_logger = None\n"
9145 "def GET(request):\n"
9146 " _logger.info('Counter was read', event='counter_read')\n"
9147 " return {'ok': True}\n",
9148 )
9149 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9150 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9151 enable_admin_token(monkeypatch)
9152 correlation_id = "123e4567-e89b-42d3-a456-426614174000"
9153
9154 status, _, payload = request(
9155 "/objects/basics_counter",
9156 headers=[("x-dbbasic-correlation-id", correlation_id)],
9157 )
9158
9159 assert status == 200
9160 assert payload == {"ok": True}
9161
9162 status, _, payload = request(
9163 "/objects/basics_counter",
9164 query_string="logs=true",
9165 headers=auth_headers(),
9166 )
9167
9168 assert status == 200
9169 messages = [entry["message"] for entry in payload["logs"]]
9170 assert "Counter was read" in messages
9171 assert "GET completed successfully" in messages
9172 assert {
9173 entry["correlation_id"]
9174 for entry in payload["logs"]
9175 if entry["message"] in {"Counter was read", "GET completed successfully"}
9176 } == {correlation_id}
9177
9178
9179def test_object_execution_passes_query_params_as_payload(tmp_path, monkeypatch):
9180 root = tmp_path / "objects"
9181 write_source(
9182 root / "basics" / "echo.py",
9183 "def GET(request):\n return {'query': request}\n",
9184 )
9185 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9186
9187 status, _, payload = request("/objects/basics_echo", query_string="name=dan&mode=test")
9188
9189 assert status == 200
9190 assert payload == {"query": {"name": "dan", "mode": "test", "_identity": ANONYMOUS_IDENTITY}}
9191
9192
9193def test_object_execution_returns_404_for_missing_object(tmp_path, monkeypatch):
9194 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects"))
9195
9196 status, _, payload = request("/objects/missing_object")
9197
9198 assert status == 404
9199 assert payload["status"] == "error"
9200 assert payload["error"] == "Object not found: missing_object"
9201 assert object_correlation.normalize_correlation_id(payload["correlation_id"]) == payload[
9202 "correlation_id"
9203 ]
9204
9205
9206def test_execution_concurrency_limit_returns_503_when_full(tmp_path, monkeypatch):
9207 root = tmp_path / "objects"
9208 write_source(root / "basics" / "counter.py", "def GET(request):\n return {'ok': True}\n")
9209 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9210 monkeypatch.setenv(object_server.MAX_CONCURRENT_EXECUTIONS_ENV, "1")
9211 token = claim_limit_slot(object_server._execution_limiter, 1)
9212 try:
9213 status, _, payload = request("/objects/basics_counter")
9214 finally:
9215 token.release()
9216
9217 assert status == 503
9218 assert payload == {
9219 "status": "error",
9220 "error": "Server is busy",
9221 "limit": "object_executions",
9222 "max_concurrent": 1,
9223 }
9224
9225
9226def test_object_execution_returns_json_error_for_object_exception(tmp_path, monkeypatch):
9227 root = tmp_path / "objects"
9228 write_source(
9229 root / "basics" / "broken.py",
9230 "def GET(request):\n raise RuntimeError('boom')\n",
9231 )
9232 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9233
9234 status, _, payload = request("/objects/basics_broken")
9235
9236 assert status == 500
9237 assert payload["status"] == "error"
9238 assert payload["error"].startswith("Execution failed: GET failed for object basics_broken")
9239 assert "RuntimeError: boom" in payload["error"]
9240
9241
9242def test_object_execution_timeout_returns_504_and_logs(tmp_path, monkeypatch):
9243 root = tmp_path / "objects"
9244 data_dir = tmp_path / "data"
9245 write_source(
9246 root / "basics" / "slow.py",
9247 "import time\n\ndef GET(request):\n time.sleep(5)\n return {'ok': True}\n",
9248 )
9249 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9250 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9251 monkeypatch.setenv(object_server.OBJECT_TIMEOUT_SECONDS_ENV, "0.5")
9252 enable_admin_token(monkeypatch)
9253
9254 status, _, payload = request("/objects/basics_slow")
9255
9256 assert status == 504
9257 assert payload["status"] == "error"
9258 assert payload["error"] == "Execution failed: GET timed out for object basics_slow after 0.5 seconds"
9259 assert object_correlation.normalize_correlation_id(payload["correlation_id"]) == payload[
9260 "correlation_id"
9261 ]
9262
9263 status, _, payload = request(
9264 "/objects/basics_slow",
9265 query_string="logs=true",
9266 headers=auth_headers(),
9267 )
9268
9269 assert status == 200
9270 assert payload["count"] == 1
9271 assert payload["logs"][0]["level"] == "ERROR"
9272 assert payload["logs"][0]["error_type"] == object_execution.TIMEOUT_ERROR_TYPE
9273 assert payload["logs"][0]["status"] == "error"
9274
9275
9276def test_timeout_enabled_uses_subprocess_for_untrusted_objects(tmp_path, monkeypatch):
9277 root = tmp_path / "objects"
9278 write_source(
9279 root / "basics" / "fast.py",
9280 "def GET(request):\n return {'mode': 'object_source'}\n",
9281 )
9282 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9283 monkeypatch.setenv(object_server.OBJECT_TIMEOUT_SECONDS_ENV, "5")
9284 calls = []
9285
9286 def fake_subprocess(request, roots=None, *, timeout_seconds, raise_on_error=False):
9287 calls.append((request.object_id, timeout_seconds))
9288 return object_execution.ObjectExecutionResult(
9289 object_id=request.object_id,
9290 method=request.normalized_method(),
9291 path=request.path,
9292 ok=True,
9293 result={"mode": "subprocess"},
9294 error=None,
9295 started_at="2026-01-01T00:00:00Z",
9296 finished_at="2026-01-01T00:00:00Z",
9297 duration_ms=1.0,
9298 )
9299
9300 monkeypatch.setattr(
9301 object_execution,
9302 "execute_python_object_subprocess",
9303 fake_subprocess,
9304 )
9305
9306 status, _, payload = request("/objects/basics_fast")
9307
9308 assert status == 200
9309 assert payload == {"mode": "subprocess"}
9310 assert calls == [("basics_fast", 5.0)]
9311
9312
9313def test_trusted_in_process_object_bypasses_subprocess_timeout_path(tmp_path, monkeypatch):
9314 root = tmp_path / "objects"
9315 write_source(
9316 root / "basics" / "fast.py",
9317 "def GET(request):\n return {'mode': 'in_process'}\n",
9318 )
9319 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9320 monkeypatch.setenv(object_server.OBJECT_TIMEOUT_SECONDS_ENV, "5")
9321 monkeypatch.setenv(object_server.TRUSTED_IN_PROCESS_OBJECTS_ENV, "basics_fast")
9322
9323 def fail_subprocess(*args, **kwargs):
9324 raise AssertionError("trusted object should not use subprocess execution")
9325
9326 monkeypatch.setattr(
9327 object_execution,
9328 "execute_python_object_subprocess",
9329 fail_subprocess,
9330 )
9331
9332 status, _, payload = request("/objects/basics_fast")
9333
9334 assert status == 200
9335 assert payload == {"mode": "in_process"}
9336
9337
9338def test_execution_concurrency_limit_releases_after_object_error(tmp_path, monkeypatch):
9339 root = tmp_path / "objects"
9340 write_source(
9341 root / "basics" / "broken.py",
9342 "def GET(request):\n raise RuntimeError('boom')\n",
9343 )
9344 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9345 monkeypatch.setenv(object_server.MAX_CONCURRENT_EXECUTIONS_ENV, "1")
9346
9347 first_status, _, first_payload = request("/objects/basics_broken")
9348 second_status, _, second_payload = request("/objects/basics_broken")
9349
9350 assert first_status == 500
9351 assert "RuntimeError: boom" in first_payload["error"]
9352 assert second_status == 500
9353 assert "RuntimeError: boom" in second_payload["error"]
9354
9355
9356def test_object_execution_appends_error_log(tmp_path, monkeypatch):
9357 root = tmp_path / "objects"
9358 data_dir = tmp_path / "data"
9359 write_source(
9360 root / "basics" / "broken.py",
9361 "def GET(request):\n raise RuntimeError('boom')\n",
9362 )
9363 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
9364 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9365 enable_admin_token(monkeypatch)
9366
9367 status, _, payload = request("/objects/basics_broken")
9368 assert status == 500
9369 assert "RuntimeError: boom" in payload["error"]
9370
9371 status, _, payload = request(
9372 "/objects/basics_broken",
9373 query_string="logs=true",
9374 headers=auth_headers(),
9375 )
9376
9377 assert status == 200
9378 assert payload["count"] == 1
9379 log = payload["logs"][0]
9380 assert log["level"] == "ERROR"
9381 assert log["message"].startswith("GET failed:")
9382 assert log["method"] == "GET"
9383 assert log["status"] == "error"
9384 assert log["error_type"] == "ObjectMethodExecutionError"
9385 assert "RuntimeError: boom" in log["error"]
9386
9387
9388def test_events_api_requires_admin_token(monkeypatch):
9389 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
9390
9391 status, _, payload = request("/events", headers=auth_headers())
9392
9393 assert status == 403
9394 assert payload == {
9395 "status": "error",
9396 "error": "Events API requires DBBASIC_ADMIN_TOKEN.",
9397 }
9398
9399
9400def test_events_api_publishes_and_lists_daemon_compatible_events(tmp_path, monkeypatch):
9401 data_dir = tmp_path / "data"
9402 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9403 enable_admin_token(monkeypatch)
9404
9405 status, _, payload = request(
9406 "/events",
9407 method="POST",
9408 body=json.dumps(
9409 {
9410 "event_type": "collection.record.created",
9411 "source": "records",
9412 "payload": {"collection": "contacts", "record_id": "c1"},
9413 }
9414 ).encode(),
9415 headers=auth_headers(),
9416 )
9417
9418 assert status == 201
9419 assert payload["status"] == "ok"
9420 event = payload["event"]
9421 assert event["event_type"] == "collection.record.created"
9422 assert event["source"] == "records"
9423 assert event["actor"] == "admin"
9424
9425 state_file = data_dir / "state" / "events" / "state.tsv"
9426 row = state_file.read_text().strip().split("\t")
9427 assert row[0].startswith("event_")
9428 assert json.loads(row[1]) == event
9429
9430 status, _, payload = request(
9431 "/events",
9432 query_string="event_type=collection.record.created",
9433 headers=auth_headers(),
9434 )
9435
9436 assert status == 200
9437 assert payload["status"] == "ok"
9438 assert payload["count"] == 1
9439 assert payload["total"] == 1
9440 assert payload["events"] == [event]
9441
9442
9443def test_events_api_prunes_event_queue(tmp_path, monkeypatch):
9444 data_dir = tmp_path / "data"
9445 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9446 enable_admin_token(monkeypatch)
9447
9448 for record_id in ("c1", "c2"):
9449 status, _, payload = request(
9450 "/events",
9451 method="POST",
9452 body=json.dumps(
9453 {
9454 "event_type": "collection.record.created",
9455 "source": "records",
9456 "payload": {"collection": "contacts", "record_id": record_id},
9457 }
9458 ).encode(),
9459 headers=auth_headers(),
9460 )
9461 assert status == 201
9462 assert payload["status"] == "ok"
9463
9464 status, _, payload = request(
9465 "/events",
9466 method="DELETE",
9467 query_string="keep_count=1&keep_seconds=0",
9468 headers=auth_headers(),
9469 )
9470
9471 assert status == 200
9472 assert payload["status"] == "ok"
9473 assert payload["retention"]["deleted"] == 1
9474 assert payload["retention"]["kept"] == 1
9475
9476 status, _, payload = request("/events", headers=auth_headers())
9477
9478 assert status == 200
9479 assert payload["total"] == 1
9480 assert payload["events"][0]["payload"]["record_id"] in {"c1", "c2"}
9481
9482
9483def test_event_subscription_api_creates_lists_and_deletes(tmp_path, monkeypatch):
9484 data_dir = tmp_path / "data"
9485 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9486 enable_admin_token(monkeypatch)
9487
9488 status, _, payload = request(
9489 "/events/subscriptions",
9490 method="POST",
9491 body=json.dumps(
9492 {
9493 "event_type": "collection.record.updated",
9494 "subscriber_id": "scroll",
9495 "callback_url": "https://example.com/hooks/dbbasic",
9496 }
9497 ).encode(),
9498 headers=auth_headers(),
9499 )
9500
9501 assert status == 201
9502 subscription = payload["subscription"]
9503 assert subscription["id"] == "scroll"
9504 assert subscription["event_type"] == "collection.record.updated"
9505 assert subscription["callback_url"] == "https://example.com/hooks/dbbasic"
9506 assert subscription["last_event_id"] is None
9507
9508 status, _, payload = request(
9509 "/events/subscriptions",
9510 query_string="event_type=collection.record.updated",
9511 headers=auth_headers(),
9512 )
9513
9514 assert status == 200
9515 assert payload["subscriptions"] == [subscription]
9516
9517 status, _, payload = request(
9518 "/events/subscriptions",
9519 method="DELETE",
9520 query_string="event_type=collection.record.updated&subscriber_id=scroll",
9521 headers=auth_headers(),
9522 )
9523
9524 assert status == 200
9525 assert payload["deleted"] is True
9526 assert payload["subscription"] == subscription
9527
9528 status, _, payload = request("/events/subscriptions", headers=auth_headers())
9529
9530 assert status == 200
9531 assert payload["subscriptions"] == []
9532
9533
9534def test_event_delivery_api_lists_pending_failed_subscriptions(tmp_path, monkeypatch):
9535 data_dir = tmp_path / "data"
9536 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9537 enable_admin_token(monkeypatch)
9538
9539 event = object_events.publish_event(
9540 "collection.record.updated",
9541 payload={"secret": "hidden"},
9542 base_dir=data_dir,
9543 )
9544 subscription = object_events.subscribe_event(
9545 "collection.record.updated",
9546 subscriber_id="scroll",
9547 callback_url="https://example.com/hooks/dbbasic",
9548 base_dir=data_dir,
9549 )
9550 subscription = object_events.record_subscription_delivery(
9551 subscription,
9552 event,
9553 success=False,
9554 status_code=502,
9555 error="bad gateway",
9556 now=100,
9557 )
9558 manager = object_state.ObjectStateManager(object_events.EVENTS_OBJECT_ID, base_dir=data_dir)
9559 manager.set("sub_collection.record.updated_scroll", json.dumps(subscription))
9560
9561 status, _, payload = request(
9562 "/events/deliveries",
9563 query_string="event_type=collection.record.updated&delivery_status=failed&pending=true",
9564 headers=auth_headers(),
9565 )
9566
9567 assert status == 200
9568 assert payload["status"] == "ok"
9569 assert payload["count"] == 1
9570 delivery = payload["deliveries"][0]
9571 assert delivery["subscriber_id"] == "scroll"
9572 assert delivery["pending"] is True
9573 assert delivery["pending_count"] == 1
9574 assert delivery["delivery"]["status"] == "failed"
9575 assert delivery["delivery"]["last_error"] == "bad gateway"
9576 assert delivery["callback_url_present"] is True
9577 assert "callback_url" not in delivery
9578 assert "payload" not in delivery["next_pending_event"]
9579
9580
9581def test_event_delivery_api_can_include_callback_and_pending_event_summaries(tmp_path, monkeypatch):
9582 data_dir = tmp_path / "data"
9583 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9584 enable_admin_token(monkeypatch)
9585
9586 event = object_events.publish_event("invoice.created", payload={"id": "i1"}, base_dir=data_dir)
9587 object_events.subscribe_event(
9588 "invoice.created",
9589 subscriber_id="billing",
9590 callback_url="https://example.com/hooks/billing",
9591 base_dir=data_dir,
9592 )
9593
9594 status, _, payload = request(
9595 "/events/deliveries",
9596 query_string="include_callback_url=true&include_events=true&event_limit=1",
9597 headers=auth_headers(),
9598 )
9599
9600 assert status == 200
9601 assert payload["status"] == "ok"
9602 delivery = payload["deliveries"][0]
9603 assert delivery["callback_url"] == "https://example.com/hooks/billing"
9604 assert delivery["pending_events"] == [delivery["next_pending_event"]]
9605 assert delivery["pending_events"][0]["id"] == event["id"]
9606 assert "payload" not in delivery["pending_events"][0]
9607
9608
9609def test_events_api_rejects_bad_payloads(tmp_path, monkeypatch):
9610 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path / "data"))
9611 enable_admin_token(monkeypatch)
9612
9613 status, _, payload = request(
9614 "/events",
9615 method="POST",
9616 body=json.dumps({"event_type": "bad event"}).encode(),
9617 headers=auth_headers(),
9618 )
9619
9620 assert status == 400
9621 assert payload["status"] == "error"
9622 assert "Invalid event type" in payload["error"]
9623
9624 status, _, payload = request(
9625 "/events/subscriptions",
9626 method="POST",
9627 body=json.dumps(
9628 {
9629 "event_type": "invoice.created",
9630 "callback_url": "ftp://example.com/hook",
9631 }
9632 ).encode(),
9633 headers=auth_headers(),
9634 )
9635
9636 assert status == 400
9637 assert "callback_url" in payload["error"]
9638
9639
9640def test_packages_api_requires_admin_token(tmp_path, monkeypatch):
9641 packages_root = tmp_path / "packages"
9642 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
9643 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
9644
9645 status, _, payload = request("/packages", headers=auth_headers())
9646
9647 assert status == 403
9648 assert payload == {
9649 "status": "error",
9650 "error": "Package listing requires DBBASIC_ADMIN_TOKEN.",
9651 }
9652
9653
9654def test_packages_api_lists_package_detail_and_dry_run(tmp_path, monkeypatch):
9655 packages_root = tmp_path / "packages"
9656 data_dir = tmp_path / "data"
9657 object_root = tmp_path / "objects"
9658 write_source(object_root / "hello" / "world.py", "def GET(request): return {}\n")
9659 write_package(
9660 packages_root,
9661 "hello-world",
9662 {
9663 "id": "hello-world",
9664 "name": "Hello World",
9665 "version": "0.1.0",
9666 "description": "Safe package fixture",
9667 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
9668 "schemas": [],
9669 "permissions": [],
9670 "seed": [],
9671 "migrations": [],
9672 },
9673 files=(("objects/hello/world.py", "def GET(request): return {}\n"),),
9674 )
9675 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
9676 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9677 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(object_root))
9678 enable_admin_token(monkeypatch)
9679
9680 status, _, payload = request("/packages", headers=auth_headers())
9681
9682 assert status == 200
9683 assert payload["status"] == "ok"
9684 assert payload["count"] == 1
9685 assert payload["packages"][0]["id"] == "hello-world"
9686 assert payload["packages"][0]["object_count"] == 1
9687
9688 status, _, payload = request("/packages/hello-world", headers=auth_headers())
9689
9690 assert status == 200
9691 assert payload["package"]["id"] == "hello-world"
9692 assert payload["package"]["objects"] == [
9693 {"id": "hello_world", "path": "objects/hello/world.py"}
9694 ]
9695
9696 status, _, payload = request(
9697 "/packages/hello-world",
9698 query_string="dry_run=true",
9699 headers=auth_headers(),
9700 )
9701
9702 assert status == 200
9703 assert payload["dry_run"]["safe_to_install"] is True
9704 assert payload["dry_run"]["install_enabled"] is False
9705 assert payload["dry_run"]["objects"][0]["action"] == "replace"
9706 assert payload["dry_run"]["warnings"] == []
9707 assert payload["change"]["package_id"] == "hello-world"
9708 assert payload["change"]["package_version"] == "0.1.0"
9709 assert payload["change"]["action"] == "dry_run"
9710 assert payload["change"]["actor"] == "admin"
9711 assert payload["change"]["details"]["objects"] == {"replace": 1}
9712 assert payload["change"]["details"]["safe_to_install"] is True
9713
9714 status, _, history = request(
9715 "/packages/hello-world/changes",
9716 headers=auth_headers(),
9717 )
9718
9719 assert status == 200
9720 assert history["package_id"] == "hello-world"
9721 assert history["count"] == 1
9722 assert history["total"] == 1
9723 assert history["changes"][0]["change_id"] == payload["change"]["change_id"]
9724
9725
9726def test_package_install_api_requires_admin_and_enable_flag(tmp_path, monkeypatch):
9727 packages_root = tmp_path / "packages"
9728 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
9729 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
9730 monkeypatch.delenv("DBBASIC_ENABLE_PACKAGE_INSTALLS", raising=False)
9731
9732 status, _, payload = request("/packages/hello-world/install", method="POST", body=b"{}")
9733
9734 assert status == 403
9735 assert payload == {
9736 "status": "error",
9737 "error": "Package installs require DBBASIC_ADMIN_TOKEN.",
9738 }
9739
9740 enable_admin_token(monkeypatch)
9741
9742 status, _, payload = request(
9743 "/packages/hello-world/install",
9744 method="POST",
9745 body=b"{}",
9746 headers=auth_headers(),
9747 )
9748
9749 assert status == 403
9750 assert payload == {
9751 "status": "error",
9752 "error": "Package installs are disabled. Set DBBASIC_ENABLE_PACKAGE_INSTALLS=true.",
9753 }
9754
9755
9756def test_package_install_api_installs_and_records_changes(tmp_path, monkeypatch):
9757 packages_root = tmp_path / "packages"
9758 data_dir = tmp_path / "data"
9759 object_root = tmp_path / "objects"
9760 write_source(object_root / "site" / "home.py", "def GET(request): return {'before': True}\n")
9761 write_package(
9762 packages_root,
9763 "hello-world",
9764 {
9765 "id": "hello-world",
9766 "name": "Hello World",
9767 "version": "0.1.0",
9768 "description": "Safe package fixture",
9769 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
9770 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
9771 "permissions": [],
9772 "seed": [{"collection": "contacts", "path": "seed/contacts.tsv"}],
9773 "migrations": [],
9774 },
9775 files=(
9776 ("objects/hello/world.py", "def GET(request): return {'status': 'ok'}\n"),
9777 ("schemas/contacts.json", '{"name":"contacts","fields":[{"name":"id","type":"text"}]}\n'),
9778 ("seed/contacts.tsv", "id\tname\nc1\tAlice\n"),
9779 ),
9780 )
9781 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
9782 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9783 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(object_root))
9784 monkeypatch.setenv("DBBASIC_ENABLE_PACKAGE_INSTALLS", "true")
9785 enable_admin_token(monkeypatch)
9786
9787 status, _, payload = request(
9788 "/packages/hello-world/install",
9789 method="POST",
9790 body=b"{}",
9791 headers=auth_headers(),
9792 )
9793
9794 assert status == 201
9795 assert payload["status"] == "ok"
9796 assert payload["install"]["mode"] == "install"
9797 assert payload["install"]["objects"][0]["destination"] == "hello/world.py"
9798 assert payload["install"]["restore_point"] == payload["restore_point"]
9799 assert payload["restore_point"]["path"].endswith("-package-hello-world.tar.gz")
9800 assert payload["changes"]["requested"]["action"] == "install_requested"
9801 assert payload["changes"]["installed"]["action"] == "installed"
9802 assert (object_root / "hello" / "world.py").is_file()
9803 assert (data_dir / "schemas" / "contacts.json").is_file()
9804 assert (data_dir / "collections" / "contacts" / "records.tsv").is_file()
9805 with tarfile.open(payload["restore_point"]["path"], "r:*") as archive:
9806 names = archive.getnames()
9807 assert "objects/site/home.py" in names
9808 assert "objects/hello/world.py" not in names
9809
9810 status, _, history = request(
9811 "/packages/hello-world/changes",
9812 headers=auth_headers(),
9813 )
9814
9815 assert status == 200
9816 assert [change["action"] for change in history["changes"]] == [
9817 "installed",
9818 "install_requested",
9819 ]
9820 assert history["changes"][0]["details"]["restore_point"]["path"] == payload["restore_point"]["path"]
9821
9822
9823def test_package_install_api_records_failed_replace(tmp_path, monkeypatch):
9824 packages_root = tmp_path / "packages"
9825 data_dir = tmp_path / "data"
9826 object_root = tmp_path / "objects"
9827 write_source(object_root / "hello" / "world.py", "def GET(request): return {'old': True}\n")
9828 write_package(
9829 packages_root,
9830 "hello-world",
9831 {
9832 "id": "hello-world",
9833 "name": "Hello World",
9834 "version": "0.1.0",
9835 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
9836 },
9837 files=(("objects/hello/world.py", "def GET(request): return {'new': True}\n"),),
9838 )
9839 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
9840 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9841 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(object_root))
9842 monkeypatch.setenv("DBBASIC_ENABLE_PACKAGE_INSTALLS", "true")
9843 enable_admin_token(monkeypatch)
9844
9845 status, _, payload = request(
9846 "/packages/hello-world/install",
9847 method="POST",
9848 body=b"{}",
9849 headers=auth_headers(),
9850 )
9851
9852 assert status == 409
9853 assert "allow_replace=true" in payload["error"]
9854 assert payload["changes"]["requested"]["action"] == "install_requested"
9855 assert payload["changes"]["failed"]["action"] == "failed"
9856 assert (object_root / "hello" / "world.py").read_text() == "def GET(request): return {'old': True}\n"
9857 assert not (data_dir / "backups").exists()
9858
9859 status, _, history = request(
9860 "/packages/hello-world/changes",
9861 headers=auth_headers(),
9862 )
9863
9864 assert status == 200
9865 assert [change["action"] for change in history["changes"]] == [
9866 "failed",
9867 "install_requested",
9868 ]
9869
9870
9871def test_package_install_api_fails_before_writes_when_restore_point_fails(tmp_path, monkeypatch):
9872 packages_root = tmp_path / "packages"
9873 data_dir = tmp_path / "data"
9874 object_root = tmp_path / "objects"
9875 bad_backups_dir = tmp_path / "not-a-directory"
9876 bad_backups_dir.write_text("not a directory")
9877 write_package(
9878 packages_root,
9879 "hello-world",
9880 {
9881 "id": "hello-world",
9882 "name": "Hello World",
9883 "version": "0.1.0",
9884 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
9885 },
9886 files=(("objects/hello/world.py", "def GET(request): return {'new': True}\n"),),
9887 )
9888 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
9889 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9890 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(object_root))
9891 monkeypatch.setenv("DBBASIC_BACKUPS_DIR", str(bad_backups_dir))
9892 monkeypatch.setenv("DBBASIC_ENABLE_PACKAGE_INSTALLS", "true")
9893 enable_admin_token(monkeypatch)
9894
9895 status, _, payload = request(
9896 "/packages/hello-world/install",
9897 method="POST",
9898 body=b"{}",
9899 headers=auth_headers(),
9900 )
9901
9902 assert status == 500
9903 assert payload["status"] == "error"
9904 assert "Package install failed" in payload["error"]
9905 assert payload["changes"]["requested"]["action"] == "install_requested"
9906 assert payload["changes"]["failed"]["action"] == "failed"
9907 assert not (object_root / "hello" / "world.py").exists()
9908
9909 status, _, history = request(
9910 "/packages/hello-world/changes",
9911 headers=auth_headers(),
9912 )
9913
9914 assert status == 200
9915 assert [change["action"] for change in history["changes"]] == [
9916 "failed",
9917 "install_requested",
9918 ]
9919
9920
9921def test_package_restore_api_requires_admin_and_enable_flag(monkeypatch):
9922 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
9923
9924 status, _, payload = request(
9925 "/packages/hello-world/restore",
9926 method="POST",
9927 body=b"{}",
9928 headers=auth_headers(),
9929 )
9930
9931 assert status == 403
9932 assert payload == {
9933 "status": "error",
9934 "error": "Package restore requires DBBASIC_ADMIN_TOKEN.",
9935 }
9936
9937 enable_admin_token(monkeypatch)
9938
9939 status, _, payload = request(
9940 "/packages/hello-world/restore",
9941 method="POST",
9942 body=b"{}",
9943 headers=auth_headers(),
9944 )
9945
9946 assert status == 403
9947 assert payload == {
9948 "status": "error",
9949 "error": "Package restore is disabled. Set DBBASIC_ENABLE_PACKAGE_RESTORE=true.",
9950 }
9951
9952
9953def test_package_restore_api_restores_install_restore_point_and_prunes_new_files(tmp_path, monkeypatch):
9954 packages_root = tmp_path / "packages"
9955 data_dir = tmp_path / "data"
9956 object_root = tmp_path / "objects"
9957 write_source(object_root / "site" / "home.py", "def GET(request): return {'before': True}\n")
9958 write_package(
9959 packages_root,
9960 "hello-world",
9961 {
9962 "id": "hello-world",
9963 "name": "Hello World",
9964 "version": "0.1.0",
9965 "objects": [{"id": "hello_world", "path": "objects/hello/world.py"}],
9966 "schemas": [{"collection": "contacts", "path": "schemas/contacts.json"}],
9967 "seed": [{"collection": "contacts", "path": "seed/contacts.tsv"}],
9968 },
9969 files=(
9970 ("objects/hello/world.py", "def GET(request): return {'new': True}\n"),
9971 ("schemas/contacts.json", '{"name":"contacts","fields":[{"name":"id","type":"text"}]}\n'),
9972 ("seed/contacts.tsv", "id\tname\nc1\tAlice\n"),
9973 ),
9974 )
9975 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
9976 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
9977 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(object_root))
9978 monkeypatch.setenv("DBBASIC_ENABLE_PACKAGE_INSTALLS", "true")
9979 monkeypatch.setenv("DBBASIC_ENABLE_PACKAGE_RESTORE", "true")
9980 enable_admin_token(monkeypatch)
9981
9982 status, _, install_payload = request(
9983 "/packages/hello-world/install",
9984 method="POST",
9985 body=b"{}",
9986 headers=auth_headers(),
9987 )
9988
9989 assert status == 201
9990 installed_change_id = install_payload["changes"]["installed"]["change_id"]
9991 restore_point_path = install_payload["restore_point"]["path"]
9992 assert (object_root / "hello" / "world.py").is_file()
9993 assert (data_dir / "schemas" / "contacts.json").is_file()
9994 assert (data_dir / "collections" / "contacts" / "records.tsv").is_file()
9995
9996 status, _, restore_payload = request(
9997 "/packages/hello-world/restore",
9998 method="POST",
9999 body=json.dumps(
10000 {
10001 "change_id": installed_change_id,
10002 "confirm": "restore-runtime",
10003 }
10004 ).encode(),
10005 headers=auth_headers(),
10006 )
10007
10008 assert status == 200
10009 assert restore_payload["status"] == "ok"
10010 assert restore_payload["restore_point"]["path"] == restore_point_path
10011 assert restore_payload["restore"]["overwritten"] is True
10012 assert restore_payload["restore"]["pruned_files"] >= 3
10013 assert restore_payload["changes"]["requested"]["action"] == "restore_requested"
10014 assert restore_payload["changes"]["rolled_back"]["action"] == "rolled_back"
10015 assert (
10016 restore_payload["changes"]["rolled_back"]["details"]["from_change"]["change_id"]
10017 == installed_change_id
10018 )
10019 assert not (object_root / "hello" / "world.py").exists()
10020 assert not (data_dir / "schemas" / "contacts.json").exists()
10021 assert not (data_dir / "collections" / "contacts" / "records.tsv").exists()
10022 assert (object_root / "site" / "home.py").is_file()
10023 assert Path(restore_point_path).exists()
10024
10025 status, _, history = request(
10026 "/packages/hello-world/changes",
10027 headers=auth_headers(),
10028 )
10029
10030 assert status == 200
10031 assert [change["action"] for change in history["changes"]] == [
10032 "rolled_back",
10033 "restore_requested",
10034 "install_requested",
10035 ]
10036
10037
10038def test_package_restore_api_rejects_changes_without_restore_points(tmp_path, monkeypatch):
10039 data_dir = tmp_path / "data"
10040 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
10041 monkeypatch.setenv("DBBASIC_ENABLE_PACKAGE_RESTORE", "true")
10042 enable_admin_token(monkeypatch)
10043 change = object_package_changes.append_package_change(
10044 package_id="hello-world",
10045 action="dry_run",
10046 package_version="0.1.0",
10047 base_dir=data_dir,
10048 )
10049
10050 status, _, payload = request(
10051 "/packages/hello-world/restore",
10052 method="POST",
10053 body=json.dumps(
10054 {
10055 "change_id": change["change_id"],
10056 "confirm": "restore-runtime",
10057 }
10058 ).encode(),
10059 headers=auth_headers(),
10060 )
10061
10062 assert status == 400
10063 assert payload["status"] == "error"
10064 assert "no restore point" in payload["error"]
10065 assert payload["changes"]["failed"]["action"] == "failed"
10066
10067
10068def test_package_changes_api_requires_admin_token(monkeypatch):
10069 monkeypatch.delenv("DBBASIC_ADMIN_TOKEN", raising=False)
10070
10071 status, _, payload = request("/packages/hello-world/changes", headers=auth_headers())
10072
10073 assert status == 403
10074 assert payload == {
10075 "status": "error",
10076 "error": "Package change history requires DBBASIC_ADMIN_TOKEN.",
10077 }
10078
10079
10080def test_packages_api_rejects_invalid_and_missing_packages(tmp_path, monkeypatch):
10081 packages_root = tmp_path / "packages"
10082 monkeypatch.setenv("DBBASIC_PACKAGES_DIR", str(packages_root))
10083 enable_admin_token(monkeypatch)
10084
10085 status, _, payload = request("/packages/../bad", headers=auth_headers())
10086
10087 assert status == 400
10088 assert "Invalid package id" in payload["error"]
10089
10090 status, _, payload = request("/packages/missing", headers=auth_headers())
10091
10092 assert status == 404
10093 assert "Package not found" in payload["error"]
10094
10095 status, _, payload = request("/packages/bad.name/changes", headers=auth_headers())
10096
10097 assert status == 400
10098 assert "Invalid package id" in payload["error"]
10099
10100 status, _, payload = request(
10101 "/packages/hello-world/changes",
10102 query_string="limit=0",
10103 headers=auth_headers(),
10104 )
10105
10106 assert status == 400
10107 assert "limit" in payload["error"]
10108
10109
10110def test_object_execution_returns_405_when_get_is_missing(tmp_path, monkeypatch):
10111 root = tmp_path / "objects"
10112 write_source(root / "basics" / "poster.py", "def POST(request):\n return {'ok': True}\n")
10113 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
10114
10115 status, _, payload = request("/objects/basics_poster")
10116
10117 assert status == 405
10118 assert payload["status"] == "error"
10119 assert payload["error"].startswith("Execution failed: Method GET not supported")
10120
10121
10122def test_object_collection_unsupported_methods_are_rejected():
10123 status, _, payload = request("/objects", method="PUT", body=b"{}")
10124
10125 assert status == 405
10126 assert payload == {"status": "error", "error": "Method not allowed"}
10127
10128
10129def test_unknown_path_returns_json_404():
10130 status, _, payload = request("/missing")
10131
10132 assert status == 404
10133 assert payload == {"status": "error", "error": "Not found"}
10134
10135
10136def test_websocket_rejects_unknown_path(monkeypatch):
10137 # Realtime lives only at /ws; any other websocket path is closed without accept.
10138 enable_admin_token(monkeypatch)
10139
10140 async def run():
10141 messages = []
10142 sent_connect = False
10143
10144 async def receive():
10145 nonlocal sent_connect
10146 if not sent_connect:
10147 sent_connect = True
10148 return {"type": "websocket.connect"}
10149 return {"type": "websocket.disconnect"}
10150
10151 async def send(message):
10152 messages.append(message)
10153
10154 await object_server.app(
10155 {"type": "websocket", "path": "/ws/basics_counter", "headers": []},
10156 receive,
10157 send,
10158 )
10159 return messages
10160
10161 messages = asyncio.run(run())
10162 assert not any(m["type"] == "websocket.accept" for m in messages)
10163 assert messages[-1]["type"] == "websocket.close"
10164
10165
10166def test_lifespan_startup_and_shutdown_complete():
10167 async def run():
10168 messages = []
10169 incoming = iter(
10170 [
10171 {"type": "lifespan.startup"},
10172 {"type": "lifespan.shutdown"},
10173 ]
10174 )
10175
10176 async def receive():
10177 return next(incoming)
10178
10179 async def send(message):
10180 messages.append(message)
10181
10182 await object_server.app({"type": "lifespan"}, receive, send)
10183 return messages
10184
10185 messages = asyncio.run(run())
10186
10187 assert messages == [
10188 {"type": "lifespan.startup.complete"},
10189 {"type": "lifespan.shutdown.complete"},
10190 ]
10191
10192
10193def test_collection_has_owner_field_detects_owner_id(tmp_path, monkeypatch):
10194 """The create handler stamps owner_id from the session only for
10195 collections that declare an owner_id field; this pins that detection.
10196 A schemaless/unknown collection must return False (nothing to stamp)."""
10197 monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path))
10198 schemas = tmp_path / "schemas"
10199 schemas.mkdir(parents=True, exist_ok=True)
10200 (schemas / "owned.json").write_text(json.dumps(
10201 {"name": "owned", "fields": [{"name": "id"}, {"name": "owner_id", "type": "text"}]}))
10202 (schemas / "ownerless.json").write_text(json.dumps(
10203 {"name": "ownerless", "fields": [{"name": "id"}, {"name": "title", "type": "text"}]}))
10204 assert object_server._collection_has_owner_field("owned") is True
10205 assert object_server._collection_has_owner_field("ownerless") is False
10206 assert object_server._collection_has_owner_field("nonexistent_collection") is False