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

9 downloads

dbbasic-object-server/tests/test_object_server.py
Install on DigitalOcean 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.

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