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_identity_sources.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, 19 minutes ago History
test_identity_sources.py · 56.5 KB · 1329 lines
1"""External identity sources (object_identity_sources) and per-user objects.
2
3A Django REST Framework client app calls this server with `Authorization: Token <DRF
4token>` and expects POST /objects to make `u_<its user id>_<name>`. These
5tests run a tiny verify stub on 127.0.0.1 (no network) standing in for
6the app's /api/auth/verify/, and check the two claims that matter most:
7an upstream can never make anyone admin here, and one user cannot read,
8run, change, destroy -- or even detect -- another user's object.
9"""
10from __future__ import annotations
11
12import http.server
13import json
14import threading
15import time
16
17import pytest
18
19import object_identity_sources
20import object_server
21from tests.test_object_server import (
22 TEST_ADMIN_TOKEN,
23 auth_headers,
24 request,
25)
26
27AUDIENCE = "box-test.example"
28SECRET = "s3cret-shared-between-boxes"
29
30TOKENS = {
31 "tok-user-1": {"user_id": 1, "username": "alice"},
32 "tok-user-2": {"user_id": "2", "username": "bob"},
33 "tok-staff": {"user_id": 3, "username": "root", "is_staff": True, "is_superuser": True,
34 "roles": ["admin", "superuser", "editor"]},
35 "tok-not-numeric": {"user_id": "alice", "username": "alice"},
36 "tok-bool": {"user_id": True},
37}
38
39
40class _Stub:
41 """A verify endpoint with switchable misbehaviour, counting its calls."""
42
43 def __init__(self):
44 self.mode = "ok"
45 self.calls = 0
46 self.seen_authorization: list[str] = []
47 self.seen_headers: list[dict[str, str]] = []
48 # What the stub writes in "audience" (None: leave it out).
49 self.audience: object = AUDIENCE
50 # The shared secret the stub insists on (None: it checks none). A
51 # request without it is 403 whatever the token, as an upstream
52 # that checks X-DBBASIC-Verify-Secret answers.
53 self.expect_secret: str | None = None
54 stub = self
55
56 class Handler(http.server.BaseHTTPRequestHandler):
57 def log_message(self, *args): # keep test output quiet
58 pass
59
60 def do_GET(self):
61 stub.calls += 1
62 auth = self.headers.get("Authorization", "")
63 stub.seen_authorization.append(auth)
64 stub.seen_headers.append({k.lower(): v for k, v in self.headers.items()})
65
66 def answer(payload):
67 if stub.audience is None:
68 return dict(payload)
69 return {"audience": stub.audience, **payload}
70 if stub.mode == "slow":
71 time.sleep(1.5)
72 if stub.expect_secret is not None and (
73 self.headers.get("X-DBBASIC-Verify-Secret") != stub.expect_secret
74 ):
75 self.send_response(403)
76 self.send_header("Content-Type", "application/json")
77 self.end_headers()
78 self.wfile.write(b'{"detail": "Not allowed."}')
79 return
80 if stub.mode == "down":
81 self.send_response(503)
82 self.end_headers()
83 return
84 if stub.mode == "redirect":
85 self.send_response(302)
86 self.send_header("Location", "http://127.0.0.1:1/elsewhere")
87 self.end_headers()
88 return
89 if stub.mode == "oversized":
90 body = json.dumps(answer({"user_id": 1, "pad": "x" * 200_000})).encode()
91 elif stub.mode == "not_json":
92 body = b"<html>hello</html>"
93 elif stub.mode in {"html_type", "json_charset"}:
94 body = json.dumps(answer({"user_id": 1})).encode()
95 ctype = (
96 "text/html" if stub.mode == "html_type"
97 else "application/json; charset=utf-8"
98 )
99 self.send_response(200)
100 self.send_header("Content-Type", ctype)
101 self.send_header("Content-Length", str(len(body)))
102 self.end_headers()
103 self.wfile.write(body)
104 return
105 else:
106 scheme, _, token = auth.partition(" ")
107 payload = TOKENS.get(token) if scheme == "Token" else None
108 if payload is None:
109 self.send_response(401)
110 self.send_header("Content-Type", "application/json")
111 self.end_headers()
112 self.wfile.write(b'{"detail": "Invalid token."}')
113 return
114 body = json.dumps(answer(payload)).encode()
115 self.send_response(200)
116 self.send_header("Content-Type", "application/json")
117 self.send_header("Content-Length", str(len(body)))
118 self.end_headers()
119 try:
120 self.wfile.write(body)
121 except (BrokenPipeError, ConnectionResetError):
122 pass
123
124 self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
125 self.server.daemon_threads = True
126 self.url = f"http://127.0.0.1:{self.server.server_address[1]}/api/auth/verify/"
127 self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
128 self.thread.start()
129
130 def close(self):
131 self.server.shutdown()
132 self.server.server_close()
133 self.thread.join(timeout=5)
134
135
136@pytest.fixture
137def stub():
138 server = _Stub()
139 try:
140 yield server
141 finally:
142 server.close()
143
144
145@pytest.fixture
146def box(tmp_path, monkeypatch, stub):
147 """A server with an admin token, the verify URL set, user writes on."""
148 root = tmp_path / "objects"
149 data_dir = tmp_path / "data"
150 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(root))
151 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
152 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", TEST_ADMIN_TOKEN)
153 monkeypatch.setenv("DBBASIC_ENABLE_SOURCE_WRITES", "true")
154 monkeypatch.setenv(object_server.USER_SOURCE_WRITES_ENV, "true")
155 monkeypatch.setenv(object_identity_sources.IDENTITY_VERIFY_URL_ENV, stub.url)
156 monkeypatch.setenv(object_identity_sources.IDENTITY_AUDIENCE_ENV, AUDIENCE)
157 monkeypatch.delenv(object_identity_sources.IDENTITY_VERIFY_SECRET_ENV, raising=False)
158 monkeypatch.delenv(object_identity_sources.IDENTITY_ALLOWED_ROLES_ENV, raising=False)
159 # Fresh source (and cache) per test.
160 monkeypatch.setattr(object_identity_sources, "_CONFIGURED", None)
161 (root / "system").mkdir(parents=True)
162 (root / "system" / "ping.py").write_text("def GET(request):\n return {'pong': True}\n")
163 return root
164
165
166def tok(name):
167 return [("authorization", f"Token {name}")]
168
169
170# --- the identity source itself ---------------------------------------------
171
172
173def test_valid_q9_token_resolves_to_that_user(box):
174 status, _, payload = request("/identity", headers=tok("tok-user-1"))
175 assert status == 200
176 assert payload["subject"]["user_id"] == "1"
177 assert payload["auth"]["method"] == "identity_source:http_verify"
178
179
180def test_invalid_token_is_not_authenticated(box):
181 status, _, payload = request("/identity", headers=tok("tok-unknown"))
182 assert payload["subject"]["user_id"] is None
183 status, _, _ = request("/objects", query_string="format=json", headers=tok("tok-unknown"))
184 assert status == 401
185
186
187@pytest.mark.parametrize("mode", ["down", "oversized", "redirect"])
188def test_unreachable_verify_service_is_503_never_anonymous(box, stub, mode):
189 """We could not check the credential: say so, never guess or go anonymous."""
190 stub.mode = mode
191 status, headers, payload = request(
192 "/objects", query_string="format=json", headers=tok("tok-user-1")
193 )
194 assert status == 503
195 assert dict(headers).get(b"retry-after")
196 assert payload["status"] == "error"
197 status, _, _ = request("/identity", headers=tok("tok-user-1"))
198 assert status == 503
199
200
201def test_non_json_verify_answer_authenticates_nobody(box, stub):
202 stub.mode = "not_json"
203 status, _, _ = request("/objects", query_string="format=json", headers=tok("tok-user-1"))
204 assert status == 401
205 _, _, payload = request("/identity", headers=tok("tok-user-1"))
206 assert payload["subject"]["user_id"] is None
207
208
209def test_slow_verify_service_times_out_to_unavailable(stub):
210 stub.mode = "slow"
211 source = object_identity_sources.HttpVerifySource(url=stub.url, audience=AUDIENCE, timeout=0.3)
212 with pytest.raises(object_identity_sources.IdentityUnavailable):
213 source.resolve({"authorization": "Token tok-user-1"})
214
215
216def test_non_numeric_or_boolean_user_id_is_rejected(box):
217 for name in ("tok-not-numeric", "tok-bool"):
218 _, _, payload = request("/identity", headers=tok(name))
219 assert payload["subject"]["user_id"] is None, name
220
221
222def test_upstream_staff_and_admin_roles_never_make_an_admin(box, monkeypatch):
223 # Even an allowlist that names them does not let admin names through.
224 monkeypatch.setenv(object_identity_sources.IDENTITY_ALLOWED_ROLES_ENV, "admin,superuser,editor")
225 _, _, payload = request("/identity", headers=tok("tok-staff"))
226 assert payload["subject"]["user_id"] == "3"
227 assert payload["subject"]["roles"] == ["editor"]
228 # Not the operator: the full listing and system-object writes stay closed.
229 status, _, listing = request("/objects", headers=tok("tok-staff"))
230 assert status == 200
231 assert all(obj["owner"] in {"system", "3"} for obj in listing["objects"])
232 status, _, _ = request(
233 "/objects/system_ping", method="PUT", query_string="source=true",
234 body=json.dumps({"code": "def GET(r):\n return 1\n"}).encode(),
235 headers=tok("tok-staff"),
236 )
237 assert status == 403
238
239
240def test_cache_positive_and_negative_ttls_and_no_raw_token(stub):
241 now = [1000.0]
242 source = object_identity_sources.HttpVerifySource(url=stub.url, audience=AUDIENCE, clock=lambda: now[0])
243 good = {"authorization": "Token tok-user-1"}
244 bad = {"authorization": "Token tok-nope"}
245
246 assert source.resolve(good).user_id == "1"
247 assert source.resolve(good).user_id == "1"
248 assert stub.calls == 1 # cached
249 now[0] += 29
250 source.resolve(good)
251 assert stub.calls == 1
252 now[0] += 2 # past the 30 s default
253 source.resolve(good)
254 assert stub.calls == 2
255
256 assert source.resolve(bad) is None
257 assert source.resolve(bad) is None
258 assert stub.calls == 3 # negative cached
259 now[0] += 11 # past 10 s
260 source.resolve(bad)
261 assert stub.calls == 4
262
263 dumped = repr(source._cache)
264 assert "tok-user-1" not in dumped and "tok-nope" not in dumped
265 assert all(len(key) == 64 for key in source._cache)
266
267
268def test_cache_is_bounded(stub):
269 source = object_identity_sources.HttpVerifySource(url=stub.url, audience=AUDIENCE, max_entries=3)
270 for i in range(10):
271 source.resolve({"authorization": f"Token junk-{i}"})
272 assert len(source._cache) <= 3
273
274
275def test_only_http_urls_are_accepted(monkeypatch):
276 with pytest.raises(ValueError):
277 object_identity_sources.HttpVerifySource(url="file:///etc/passwd")
278 monkeypatch.setenv(object_identity_sources.IDENTITY_VERIFY_URL_ENV, "ftp://x/verify")
279 monkeypatch.setattr(object_identity_sources, "_CONFIGURED", None)
280 assert object_identity_sources.configured_sources() == ()
281 assert object_identity_sources.configuration_error()
282
283
284def test_a_raising_source_is_skipped_not_trusted():
285 class Boom:
286 name = "boom"
287
288 def resolve(self, headers):
289 raise RuntimeError("upstream exploded")
290
291 class Fixed:
292 name = "fixed"
293 allowed_roles = frozenset({"admin", "x"})
294
295 def resolve(self, headers):
296 return object_identity_sources.Principal(user_id="7", source="fixed", roles=("admin", "x"))
297
298 assert object_identity_sources.resolve_principal({}, [Boom()]) is None
299 principal = object_identity_sources.resolve_principal({}, [Boom(), Fixed()])
300 assert principal.user_id == "7" and principal.roles == ("x",)
301
302
303def test_admin_token_is_never_forwarded_and_still_wins(box, stub):
304 status, _, payload = request("/identity", headers=auth_headers())
305 assert payload["auth"]["method"] == "admin_token"
306 status, _, listing = request("/objects", headers=auth_headers())
307 assert status == 200
308 assert stub.calls == 0
309
310
311def test_no_verify_url_means_no_external_identity(box, monkeypatch, stub):
312 monkeypatch.delenv(object_identity_sources.IDENTITY_VERIFY_URL_ENV)
313 _, _, payload = request("/identity", headers=tok("tok-user-1"))
314 assert payload["subject"]["user_id"] is None
315 assert stub.calls == 0
316
317
318# --- hardening round: 503, TTL, forget, strictness, duplicates ---------------
319
320
321def _the_source():
322 return object_identity_sources.configured_sources()[0]
323
324
325def test_saturated_verify_is_503_with_retry_after_not_anonymous(box, stub):
326 source = _the_source()
327 source._inflight = threading.BoundedSemaphore(1)
328 source._inflight.acquire() # every slot busy
329 status, headers, _ = request("/objects", query_string="format=json", headers=tok("tok-user-1"))
330 assert status == 503
331 assert int(dict(headers)[b"retry-after"]) >= 1
332 assert stub.calls == 0
333 # No credential, no problem: anonymous requests are unaffected.
334 assert request("/health")[0] == 200
335 # Admin token never goes near the verify path.
336 assert request("/objects", headers=auth_headers())[0] == 200
337
338
339def test_transport_errors_are_not_cached_users_recover_at_once(box, stub):
340 stub.mode = "down"
341 assert request("/identity", headers=tok("tok-user-1"))[0] == 503
342 assert request("/identity", headers=tok("tok-user-1"))[0] == 503
343 assert stub.calls == 2 # not cached as a "no"
344 stub.mode = "ok"
345 status, _, payload = request("/identity", headers=tok("tok-user-1"))
346 assert status == 200 and payload["subject"]["user_id"] == "1"
347
348
349def test_definite_refusal_is_cached_but_5xx_is_not(stub):
350 source = object_identity_sources.HttpVerifySource(url=stub.url, audience=AUDIENCE)
351 assert source.resolve({"authorization": "Token nope"}) is None
352 assert source.resolve({"authorization": "Token nope"}) is None
353 assert stub.calls == 1
354 stub.mode = "down"
355 with pytest.raises(object_identity_sources.IdentityUnavailable):
356 source.resolve({"authorization": "Token tok-user-1"})
357 assert source._cache.keys() == {source.cache_key("Token nope")}
358
359
360def test_cache_ttl_is_configurable_and_defaults_to_30(monkeypatch, stub):
361 monkeypatch.setenv(object_identity_sources.IDENTITY_VERIFY_URL_ENV, stub.url)
362 monkeypatch.setenv(object_identity_sources.IDENTITY_AUDIENCE_ENV, AUDIENCE)
363 monkeypatch.delenv(object_identity_sources.POSITIVE_CACHE_ENV, raising=False)
364 monkeypatch.setattr(object_identity_sources, "_CONFIGURED", None)
365 assert _the_source().positive_ttl == 30.0
366 monkeypatch.setenv(object_identity_sources.POSITIVE_CACHE_ENV, "5")
367 assert _the_source().positive_ttl == 5.0
368 monkeypatch.setenv(object_identity_sources.POSITIVE_CACHE_ENV, "garbage")
369 assert _the_source().positive_ttl == 30.0
370
371
372def _forget(body, headers):
373 return request(
374 "/admin/identity/sources/forget", method="POST",
375 body=json.dumps(body).encode(), headers=headers,
376 )
377
378
379def test_forget_endpoint_drops_one_entry_or_all_and_is_admin_only(box, stub):
380 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] == "1"
381 assert request("/identity", headers=tok("tok-user-2"))[2]["subject"]["user_id"] == "2"
382 assert stub.calls == 2
383
384 digest = object_identity_sources.HttpVerifySource.cache_key("Token tok-user-1")
385 # Not admin: refused, nothing dropped.
386 assert _forget({"token_hash": digest}, tok("tok-user-1"))[0] in {401, 403}
387 assert _forget({"all": True}, [])[0] in {401, 403}
388 request("/identity", headers=tok("tok-user-1"))
389 assert stub.calls == 2
390
391 status, _, payload = _forget({"token_hash": digest}, auth_headers())
392 assert (status, payload) == (200, {"status": "ok", "forgotten": 1})
393 request("/identity", headers=tok("tok-user-1"))
394 assert stub.calls == 3 # looked up again
395 request("/identity", headers=tok("tok-user-2"))
396 assert stub.calls == 3 # the other entry survived
397
398 status, _, payload = _forget({"all": True}, auth_headers())
399 assert status == 200 and payload["forgotten"] == 2
400 request("/identity", headers=tok("tok-user-2"))
401 assert stub.calls == 4
402
403
404def test_forget_revokes_at_once_when_upstream_has_revoked(box, stub, monkeypatch):
405 monkeypatch.setitem(TOKENS, "tok-temp", {"user_id": 9})
406 assert request("/identity", headers=tok("tok-temp"))[2]["subject"]["user_id"] == "9"
407 monkeypatch.delitem(TOKENS, "tok-temp")
408 assert request("/identity", headers=tok("tok-temp"))[2]["subject"]["user_id"] == "9" # cached
409 digest = object_identity_sources.HttpVerifySource.cache_key("Token tok-temp")
410 assert _forget({"token_hash": digest}, auth_headers())[0] == 200
411 assert request("/identity", headers=tok("tok-temp"))[2]["subject"]["user_id"] is None
412
413
414def test_forget_rejects_raw_tokens_and_bad_bodies(box):
415 for body in (
416 {"token": "Token tok-user-1"},
417 {"token_hash": "Token tok-user-1"},
418 {"token_hash": "A" * 64},
419 {},
420 {"all": False},
421 {"all": True, "token_hash": "a" * 64},
422 ):
423 status, _, payload = _forget(body, auth_headers())
424 assert status == 400, body
425 assert "tok-user-1" not in json.dumps(payload)
426 assert request("/admin/identity/sources/forget", headers=auth_headers())[0] == 405
427
428
429def test_forgotten_while_in_flight_is_not_stored(stub):
430 source = object_identity_sources.HttpVerifySource(url=stub.url, audience=AUDIENCE)
431 key = source.cache_key("Token tok-user-1")
432 generation = source._generation
433 source.forget()
434 source._store(key, object_identity_sources.Principal("1", "x"), generation)
435 assert source._cache == {}
436
437
438def test_two_authorization_headers_are_refused(box, stub):
439 both = [("authorization", "Token tok-user-1"), ("authorization", "Token tok-user-2")]
440 for path in ("/identity", "/objects", "/health"):
441 status, _, payload = request(path, headers=both)
442 assert status == 400, path
443 assert "Authorization" in payload["error"]
444 # Even when both are the same value, and with the admin token.
445 same = [("Authorization", "Token tok-user-1"), ("authorization", "Token tok-user-1")]
446 assert request("/identity", headers=same)[0] == 400
447 assert request("/objects", headers=auth_headers() + auth_headers())[0] == 400
448 assert stub.calls == 0
449 assert request("/identity", headers=tok("tok-user-1"))[0] == 200
450
451
452def test_duplicate_authorization_refused_without_identity_sources(tmp_path, monkeypatch):
453 monkeypatch.delenv(object_identity_sources.IDENTITY_VERIFY_URL_ENV, raising=False)
454 monkeypatch.setattr(object_identity_sources, "_CONFIGURED", None)
455 monkeypatch.setenv("DBBASIC_DATA_DIR", str(tmp_path))
456 monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "o"))
457 assert request("/objects", headers=[("authorization", "Bearer a"), ("authorization", "Bearer b")])[0] == 400
458
459
460@pytest.mark.parametrize(
461 "answer",
462 [
463 {"user_id": "007"},
464 {"user_id": " 7"},
465 {"user_id": "7 "},
466 {"user_id": "+7"},
467 {"user_id": 0},
468 {"user_id": -3},
469 {"user_id": 7.0},
470 {"user_id": 7, "account_id": "../x"},
471 {"user_id": 7, "account_id": "a b"},
472 {"user_id": 7, "account_id": 5},
473 {"user_id": 7, "account_id": ""},
474 ],
475)
476def test_verify_answer_must_be_canonical(box, monkeypatch, answer):
477 monkeypatch.setitem(TOKENS, "tok-odd", answer)
478 _, _, payload = request("/identity", headers=tok("tok-odd"))
479 assert payload["subject"]["user_id"] is None, answer
480
481
482def test_canonical_answers_are_accepted(box, monkeypatch):
483 monkeypatch.setitem(TOKENS, "tok-a", {"user_id": "7", "account_id": "acct_1"})
484 monkeypatch.setitem(TOKENS, "tok-b", {"user_id": 12})
485 assert request("/identity", headers=tok("tok-a"))[2]["subject"]["user_id"] == "7"
486 assert request("/identity", headers=tok("tok-b"))[2]["subject"]["user_id"] == "12"
487
488
489def test_verify_answer_must_be_json_content_type(box, stub):
490 stub.mode = "html_type"
491 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] is None
492 stub.mode = "json_charset"
493 stub.calls = 0
494 assert request("/identity", headers=tok("tok-user-2"))[2]["subject"]["user_id"] == "1"
495
496
497# --- transport and mutual trust ---------------------------------------------
498
499ids = object_identity_sources
500
501
502class _CountingFetch:
503 """A fetch that never touches the network; records what it was handed."""
504
505 def __init__(self, payload=None, status=200, ctype="application/json"):
506 self.calls = []
507 self.payload = payload if payload is not None else {"audience": AUDIENCE, "user_id": 5}
508 self.status = status
509 self.ctype = ctype
510
511 def __call__(self, url, authorization, timeout, max_bytes, extra_headers=None):
512 self.calls.append({"url": url, "authorization": authorization,
513 "headers": dict(extra_headers or {})})
514 return self.status, json.dumps(self.payload).encode(), self.ctype
515
516
517def _env_source(monkeypatch, url, *, secret=None, audience=AUDIENCE):
518 monkeypatch.setenv(ids.IDENTITY_VERIFY_URL_ENV, url)
519 for env, value in ((ids.IDENTITY_VERIFY_SECRET_ENV, secret), (ids.IDENTITY_AUDIENCE_ENV, audience)):
520 if value is None:
521 monkeypatch.delenv(env, raising=False)
522 else:
523 monkeypatch.setenv(env, value)
524 monkeypatch.setattr(ids, "_CONFIGURED", None)
525 return ids.configured_sources(), ids.configuration_error()
526
527
528@pytest.mark.parametrize(
529 "url",
530 [
531 "http://auth.example.com/api/auth/verify/",
532 "http://192.0.2.10/api/auth/verify/",
533 "http://127.0.0.1.example.com/verify/",
534 "http://0x7f.1/verify/",
535 "http://[::ffff:192.0.2.1]/verify/",
536 "https://user:pw@auth.example.com/verify/",
537 "https:///verify/",
538 ],
539)
540def test_plain_http_to_a_remote_host_is_refused_at_config(monkeypatch, url):
541 sources, error = _env_source(monkeypatch, url, secret=SECRET)
542 assert sources == ()
543 assert error and ids.IDENTITY_VERIFY_URL_ENV in error
544 assert SECRET not in error
545 with pytest.raises(ValueError):
546 ids.HttpVerifySource(url=url, audience=AUDIENCE, secret=SECRET)
547
548
549@pytest.mark.parametrize(
550 "url",
551 [
552 "http://127.0.0.1:8000/verify/",
553 "http://127.9.8.7/verify/",
554 "http://[::1]:8000/verify/",
555 "http://localhost:8000/verify/",
556 "http://LOCALHOST/verify/",
557 ],
558)
559def test_loopback_may_use_http_and_needs_no_secret(monkeypatch, url):
560 sources, error = _env_source(monkeypatch, url)
561 assert error is None and len(sources) == 1
562
563
564def test_a_remote_https_source_needs_the_shared_secret(monkeypatch):
565 url = "https://auth.example.com/api/auth/verify/"
566 sources, error = _env_source(monkeypatch, url)
567 assert sources == () and ids.IDENTITY_VERIFY_SECRET_ENV in error
568 sources, error = _env_source(monkeypatch, url, secret="short")
569 assert sources == () and ids.IDENTITY_VERIFY_SECRET_ENV in error and "short" not in error
570 sources, error = _env_source(monkeypatch, url, secret=SECRET)
571 assert error is None and len(sources) == 1
572 assert SECRET not in repr(sources[0])
573
574
575def test_every_source_needs_an_audience(monkeypatch, stub):
576 for audience in (None, "", "two words", "../x"):
577 sources, error = _env_source(monkeypatch, stub.url, audience=audience)
578 assert sources == () and ids.IDENTITY_AUDIENCE_ENV in error, audience
579
580
581def test_secret_and_audience_are_sent_with_each_verify(stub):
582 source = ids.HttpVerifySource(url=stub.url, audience=AUDIENCE, secret=SECRET)
583 assert source.resolve({"authorization": "Token tok-user-1"}).user_id == "1"
584 [sent] = stub.seen_headers
585 assert sent["x-dbbasic-verify-secret"] == SECRET
586 assert sent["x-dbbasic-audience"] == AUDIENCE
587 assert sent["authorization"] == "Token tok-user-1"
588
589
590def test_a_remote_source_hands_the_secret_to_fetch():
591 fetch = _CountingFetch()
592 source = ids.HttpVerifySource(
593 url="https://auth.example.com/verify/", audience=AUDIENCE, secret=SECRET, fetch=fetch
594 )
595 assert source.resolve({"authorization": "Token abc"}).user_id == "5"
596 assert fetch.calls[0]["headers"] == {
597 ids.VERIFY_SECRET_HEADER: SECRET, ids.AUDIENCE_HEADER: AUDIENCE,
598 }
599
600
601def test_transport_is_checked_again_at_call_time():
602 """A source whose url is changed after construction never sends a credential over http."""
603 fetch = _CountingFetch()
604 source = ids.HttpVerifySource(
605 url="https://auth.example.com/verify/", audience=AUDIENCE, secret=SECRET, fetch=fetch
606 )
607 source.url = "http://auth.example.com/verify/"
608 with pytest.raises(ids.IdentityUnavailable):
609 source.resolve({"authorization": "Token abc"})
610 assert fetch.calls == []
611 # The real fetch refuses on its own as well, before opening anything.
612 with pytest.raises(ValueError):
613 ids._default_fetch("http://auth.example.com/verify/", "Token abc", 1.0, 1024, {})
614 # A loopback source whose secret was dropped stays usable; a remote one does not.
615 source.url = "https://auth.example.com/verify/"
616 source.secret = ""
617 with pytest.raises(ids.IdentityUnavailable):
618 source.resolve({"authorization": "Token abc"})
619 assert fetch.calls == []
620
621
622@pytest.mark.parametrize("audience", [None, "", "other-box.example", ["box-test.example"], 7])
623def test_an_answer_not_addressed_to_this_server_authenticates_nobody(box, stub, audience):
624 stub.audience = audience
625 _, _, payload = request("/identity", headers=tok("tok-user-1"))
626 assert payload["subject"]["user_id"] is None
627 status, _, _ = request("/objects", query_string="format=json", headers=tok("tok-user-1"))
628 assert status == 401
629
630
631def test_an_answer_naming_this_server_is_accepted(box, stub):
632 stub.audience = AUDIENCE
633 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] == "1"
634
635
636@pytest.mark.parametrize("status", [301, 302, 307, 308])
637def test_redirects_are_never_followed(status):
638 """The default fetch refuses a redirect (to http or anywhere): not an answer, 503."""
639
640 class Redirecting(http.server.BaseHTTPRequestHandler):
641 def log_message(self, *args):
642 pass
643
644 def do_GET(self):
645 self.send_response(status)
646 self.send_header("Location", "http://auth.example.com/elsewhere")
647 self.end_headers()
648
649 server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Redirecting)
650 thread = threading.Thread(target=server.serve_forever, daemon=True)
651 thread.start()
652 try:
653 source = ids.HttpVerifySource(
654 url=f"http://127.0.0.1:{server.server_address[1]}/v", audience=AUDIENCE
655 )
656 with pytest.raises(ids.IdentityUnavailable):
657 source.resolve({"authorization": "Token abc"})
658 finally:
659 server.shutdown()
660 server.server_close()
661
662
663def test_a_refused_source_is_an_error_at_startup_without_the_secret(monkeypatch, capsys):
664 _env_source(monkeypatch, "http://auth.example.com/verify/", secret=SECRET)
665 object_server._note_identity_sources()
666 err = capsys.readouterr().err
667 assert "ERROR: Identity source refused" in err and "https://" in err
668 assert SECRET not in err
669
670
671def test_a_good_source_says_nothing_at_startup(monkeypatch, capsys, stub):
672 _env_source(monkeypatch, stub.url)
673 object_server._note_identity_sources()
674 assert "Identity source" not in capsys.readouterr().err
675
676
677def _status_pages():
678 status, _, admin = request("/admin/status", headers=auth_headers())
679 assert status == 200, admin
680 status, _, permissions = request("/permissions/status", headers=auth_headers())
681 assert status == 200, permissions
682 return admin, permissions
683
684
685def test_a_refused_source_is_an_admin_status_alert_without_the_secret(box, monkeypatch):
686 """The startup ERROR line used to be the only sign: /admin/status said
687 alerts: [] and identity_source_configured: false."""
688 _env_source(monkeypatch, "http://auth.example.com/verify/", secret=SECRET)
689 admin, permissions = _status_pages()
690 [alert] = [a for a in admin["alerts"] if "Identity source refused" in a]
691 assert "https://" in alert and "anonymous" in alert and "DBBASIC_IDENTITY_VERIFY_URL" in alert
692 assert admin["capabilities"]["identity"]["identity_source_configured"] is False
693 assert "https://" in admin["capabilities"]["identity"]["identity_source_refused"]
694 assert "https://" in permissions["permissions"]["identity_source_refused"]
695 assert any("Identity source refused" in w for w in permissions["warnings"])
696 for page in (admin, permissions):
697 dumped = json.dumps(page)
698 assert SECRET not in dumped and "auth.example.com" not in dumped
699
700
701def test_a_source_missing_its_audience_is_an_alert_too(box, monkeypatch, stub):
702 _env_source(monkeypatch, stub.url, audience=None)
703 admin, _ = _status_pages()
704 assert any("DBBASIC_IDENTITY_AUDIENCE must be set" in a for a in admin["alerts"])
705
706
707def test_an_accepted_source_or_none_raises_no_alert(box, monkeypatch, stub):
708 for url in (stub.url, None):
709 if url is None:
710 monkeypatch.delenv(object_identity_sources.IDENTITY_VERIFY_URL_ENV)
711 monkeypatch.setattr(object_identity_sources, "_CONFIGURED", None)
712 else:
713 _env_source(monkeypatch, url)
714 admin, permissions = _status_pages()
715 assert not any("Identity source" in a for a in admin["alerts"]), admin["alerts"]
716 assert admin["capabilities"]["identity"]["identity_source_refused"] is None
717 assert permissions["permissions"]["identity_source_refused"] is None
718 assert not any("Identity source" in w for w in permissions["warnings"])
719 assert admin["capabilities"]["identity"]["identity_source_configured"] is (url is not None)
720
721
722# --- a remote identity naming a local user -----------------------------------
723
724import object_identity # noqa: E402
725import object_identity_cli # noqa: E402
726import object_ops_log # noqa: E402
727
728
729def _data(box):
730 return box.parent / "data"
731
732
733def _collisions(box):
734 return object_ops_log.read_events(
735 base_dir=_data(box), kind=object_ops_log.AUTH, event="identity_source_collision"
736 )
737
738
739@pytest.fixture
740def fresh_ops_throttle(monkeypatch):
741 monkeypatch.setattr(object_server, "_IDENTITY_SOURCE_OPS_SEEN", {})
742
743
744def test_a_remote_identity_naming_an_unlinked_local_user_is_refused(box, stub, fresh_ops_throttle):
745 object_identity.create_user({"user_id": "1", "roles": ["editor"]}, base_dir=_data(box))
746 _, _, payload = request("/identity", headers=tok("tok-user-1"))
747 assert payload["subject"]["user_id"] is None
748 assert request("/objects", query_string="format=json", headers=tok("tok-user-1"))[0] == 401
749 # Someone else from the same source is unaffected.
750 assert request("/identity", headers=tok("tok-user-2"))[2]["subject"]["user_id"] == "2"
751
752 events = _collisions(box)
753 assert len(events) == 1 # the second refusal inside a minute is not another row
754 [event] = events
755 assert event["user_id"] == "1" and event["auth_method"] == "identity_source:http_verify"
756 dumped = json.dumps(event)
757 assert "tok-user-1" not in dumped
758 assert object_identity_sources.HttpVerifySource.cache_key("Token tok-user-1") not in dumped
759
760
761def test_a_local_user_linked_to_the_source_is_accepted(box, stub):
762 object_identity.create_user(
763 {"user_id": "1", "identity_source": "http_verify"}, base_dir=_data(box)
764 )
765 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] == "1"
766 assert _collisions(box) == []
767
768
769def test_a_link_to_another_source_or_an_unlink_refuses(box, stub, fresh_ops_throttle):
770 object_identity.create_user({"user_id": "1", "identity_source": "other_idp"}, base_dir=_data(box))
771 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] is None
772 object_identity.set_user_identity_source("1", "http_verify", base_dir=_data(box))
773 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] == "1"
774 object_identity.set_user_identity_source("1", None, base_dir=_data(box))
775 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] is None
776
777
778def test_duplicate_rows_that_disagree_are_not_linked(box, stub):
779 data = _data(box)
780 object_identity.create_user({"user_id": "1", "identity_source": "http_verify"}, base_dir=data)
781 path = object_identity.users_path(data)
782 lines = path.read_text().splitlines()
783 lines.append(lines[1].rsplit("\t", 1)[0] + "\t") # same user, no link
784 path.write_text("\n".join(lines) + "\n")
785 assert object_identity.user_record("1", base_dir=data).identity_source is None
786 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] is None
787
788
789def test_a_remote_user_cannot_stamp_records_as_an_unlinked_local_user(box, stub):
790 object_identity.create_user({"user_id": "1"}, base_dir=_data(box))
791 assert object_server._signed_in_user_id({"authorization": "Token tok-user-1"}) is None
792
793
794def test_credentials_left_under_an_id_with_no_user_give_a_remote_identity_nothing(
795 box, stub, monkeypatch, fresh_ops_throttle
796):
797 """A password, a session and an API key left under user id 1, which has no
798 users.tsv row, do not make 1 a local user (no collision), and the remote
799 identity 1 cannot reach any of them: keys and passwords are managed only
800 with a local session of that user or the admin gate, password sign-in needs
801 a user row, and a session or key works only for whoever holds its token."""
802 import object_api_keys
803 import object_credentials
804
805 monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true")
806 data = _data(box)
807 object_credentials.set_password("1", "the old owner's pass", base_dir=data)
808 left_session = object_identity.create_session({"user_id": "1"}, base_dir=data)["token"]
809 _meta, left_key = object_api_keys.create_api_key("1", "left behind", base_dir=data)
810 assert object_identity.user_record("1", base_dir=data) is None
811
812 remote = tok("tok-user-1")
813 assert request("/identity", headers=remote)[2]["subject"]["user_id"] == "1"
814 assert _collisions(box) == []
815 assert object_server._current_identity_session({"authorization": "Token tok-user-1"}) is None
816
817 for method, path, body in (
818 ("GET", "/identity/users/1/api-keys", b""),
819 ("POST", "/identity/users/1/api-keys", b'{"name": "mine now"}'),
820 ("DELETE", "/identity/users/1/api-keys/" + _meta["key_id"], b""),
821 ("POST", "/identity/users/1/password", b'{"password": "a brand new password"}'),
822 ("DELETE", "/identity/users/1/password", b""),
823 ("GET", "/identity/sessions", b""),
824 ):
825 status, _, payload = request(path, method=method, body=body, headers=remote)
826 assert status in (401, 403), (method, path, status, payload)
827 assert "token" not in payload and "keys" not in payload and "sessions" not in payload
828
829 # the leftover password signs in nobody, even when it is right
830 status, _, payload = request("/identity/session", method="POST", headers=remote,
831 body=json.dumps({"user_id": "1", "password": "the old owner's pass"}).encode())
832 assert status == 401, payload
833
834 # all three are as they were
835 assert object_credentials.verify_password("1", "the old owner's pass", base_dir=data)
836 assert [k["key_id"] for k in object_api_keys.list_api_keys("1", base_dir=data)] == [_meta["key_id"]]
837 assert object_api_keys.resolve_api_key(left_key, base_dir=data) == "1"
838 assert object_identity.resolve_session_token(left_session, base_dir=data) is not None
839
840
841def test_users_file_without_the_column_reads_as_unlinked(tmp_path):
842 path = object_identity.users_path(tmp_path)
843 path.parent.mkdir(parents=True)
844 header = [f for f in object_identity.USER_FIELDS if f != "identity_source"]
845 path.write_text(
846 "\t".join(header) + "\n"
847 + "\t".join(["7", "", "", "", "active", "[]", "[]",
848 "2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"]) + "\n"
849 )
850 record = object_identity.user_record("7", base_dir=tmp_path)
851 assert record.active and record.identity_source is None
852 assert object_identity.get_user("7", base_dir=tmp_path)["identity_source"] is None
853
854
855def test_cli_links_and_unlinks(tmp_path, capsys):
856 base = ["--data-dir", str(tmp_path)]
857 assert object_identity_cli.main(base + ["create-user", "--user-id", "7",
858 "--identity-source", "http_verify"]) == 0
859 assert object_identity.user_record("7", base_dir=tmp_path).identity_source == "http_verify"
860 assert object_identity_cli.main(base + ["set-identity-source", "--user-id", "7", "--unlink"]) == 0
861 assert object_identity.user_record("7", base_dir=tmp_path).identity_source is None
862 assert object_identity_cli.main(base + ["set-identity-source", "--user-id", "7",
863 "--source", "http_verify"]) == 0
864 assert "linked to identity source http_verify" in capsys.readouterr().out
865 assert object_identity_cli.main(base + ["set-identity-source", "--user-id", "7",
866 "--source", "../x"]) == 1
867
868
869# --- which roles an upstream may confer ---------------------------------------
870
871
872def _roles_dropped(box):
873 return object_ops_log.read_events(
874 base_dir=_data(box), kind=object_ops_log.AUTH, event="identity_source_roles_dropped"
875 )
876
877
878def test_by_default_an_upstream_confers_no_roles_and_the_drop_is_recorded(
879 box, monkeypatch, fresh_ops_throttle
880):
881 monkeypatch.setitem(TOKENS, "tok-roles", {"user_id": 4, "roles": ["staff", "viewer", "bad role!"]})
882 _, _, payload = request("/identity", headers=tok("tok-roles"))
883 assert payload["subject"]["user_id"] == "4"
884 assert payload["subject"]["roles"] == []
885 request("/identity", headers=tok("tok-roles"))
886 [event] = _roles_dropped(box) # once, not per request
887 assert event["user_id"] == "4" and event["label"] == "roles=staff,viewer"
888 assert "tok-roles" not in json.dumps(event)
889
890
891def test_only_allowlisted_roles_are_conferred(box, monkeypatch, fresh_ops_throttle):
892 monkeypatch.setenv(object_identity_sources.IDENTITY_ALLOWED_ROLES_ENV, " viewer , editor ")
893 monkeypatch.setitem(TOKENS, "tok-roles", {"user_id": 4, "roles": ["staff", "viewer", "admin"]})
894 _, _, payload = request("/identity", headers=tok("tok-roles"))
895 assert payload["subject"]["roles"] == ["viewer"]
896 [event] = _roles_dropped(box)
897 assert event["label"] == "roles=admin,staff"
898
899
900def test_no_drop_no_ops_row(box, monkeypatch):
901 monkeypatch.setenv(object_identity_sources.IDENTITY_ALLOWED_ROLES_ENV, "viewer")
902 monkeypatch.setitem(TOKENS, "tok-roles", {"user_id": 4, "roles": ["viewer"]})
903 assert request("/identity", headers=tok("tok-roles"))[2]["subject"]["roles"] == ["viewer"]
904 assert _roles_dropped(box) == []
905
906
907def test_a_malformed_allowlist_refuses_the_source(monkeypatch, stub):
908 monkeypatch.setenv(object_identity_sources.IDENTITY_ALLOWED_ROLES_ENV, "viewer,not a role")
909 sources, error = _env_source(monkeypatch, stub.url)
910 assert sources == () and object_identity_sources.IDENTITY_ALLOWED_ROLES_ENV in error
911
912
913def test_a_source_without_an_allowlist_confers_nothing():
914 class Bare:
915 name = "bare"
916
917 def resolve(self, headers):
918 return object_identity_sources.Principal(user_id="7", source="bare", roles=("x",))
919
920 principal = object_identity_sources.resolve_principal({}, [Bare()])
921 assert principal.roles == () and principal.dropped_roles == ("x",)
922
923
924# --- the account-active check covers remote users ------------------------------
925
926
927def test_a_remote_user_naming_a_disabled_account_is_refused(box, monkeypatch):
928 data = _data(box)
929 object_identity.create_account({"account_id": "acct_x"}, base_dir=data)
930 monkeypatch.setitem(TOKENS, "tok-acct", {"user_id": 11, "account_id": "acct_x"})
931 assert request("/identity", headers=tok("tok-acct"))[2]["subject"]["user_id"] == "11"
932 object_identity.set_account_status("acct_x", object_identity.DISABLED_STATUS, base_dir=data)
933 assert request("/identity", headers=tok("tok-acct"))[2]["subject"]["user_id"] is None
934 assert request("/objects", query_string="format=json", headers=tok("tok-acct"))[0] == 401
935
936
937def test_a_linked_remote_user_whose_local_account_is_disabled_is_refused(box):
938 data = _data(box)
939 object_identity.create_account({"account_id": "acct_y"}, base_dir=data)
940 object_identity.create_user(
941 {"user_id": "1", "account_id": "acct_y", "identity_source": "http_verify"}, base_dir=data
942 )
943 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] == "1"
944 object_identity.set_account_status("acct_y", object_identity.DISABLED_STATUS, base_dir=data)
945 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] is None
946
947
948def test_a_linked_remote_user_disabled_here_is_refused(box):
949 data = _data(box)
950 object_identity.create_user({"user_id": "1", "identity_source": "http_verify"}, base_dir=data)
951 object_identity.set_user_status("1", object_identity.DISABLED_STATUS, base_dir=data)
952 assert request("/identity", headers=tok("tok-user-1"))[2]["subject"]["user_id"] is None
953
954
955# --- the cache lifetime ceiling ---------------------------------------------------
956
957
958@pytest.mark.parametrize("raw, expected", [("60", 60.0), ("61", 60.0), ("3600", 60.0),
959 ("1e9", 60.0), ("inf", 60.0), ("45", 45.0),
960 ("0", 0.0), ("-5", 30.0), ("nan", 30.0)])
961def test_a_configured_cache_lifetime_is_clamped_to_60(monkeypatch, stub, raw, expected):
962 monkeypatch.setenv(object_identity_sources.POSITIVE_CACHE_ENV, raw)
963 [source], _ = _env_source(monkeypatch, stub.url)
964 assert source.positive_ttl == expected
965
966
967def test_a_clamped_lifetime_warns_at_startup(monkeypatch, stub, capsys):
968 monkeypatch.setenv(object_identity_sources.POSITIVE_CACHE_ENV, "3600")
969 _env_source(monkeypatch, stub.url)
970 object_server._note_identity_sources()
971 err = capsys.readouterr().err
972 assert "WARNING" in err and object_identity_sources.POSITIVE_CACHE_ENV in err and "60 s" in err
973 monkeypatch.setenv(object_identity_sources.POSITIVE_CACHE_ENV, "60")
974 _env_source(monkeypatch, stub.url)
975 object_server._note_identity_sources()
976 assert "WARNING" not in capsys.readouterr().err
977
978
979def test_no_cached_answer_outlives_60_seconds(stub, monkeypatch):
980 """Not a constructor argument, not a later attribute change, not the upstream's say-so."""
981 monkeypatch.setitem(TOKENS, "tok-long", {"user_id": 8, "cache_ttl": 86400, "expires_in": 86400,
982 "max_age": 86400})
983 now = [1000.0]
984 source = object_identity_sources.HttpVerifySource(
985 url=stub.url, audience=AUDIENCE, positive_ttl=3600, negative_ttl=3600,
986 clock=lambda: now[0],
987 )
988 assert source.positive_ttl == 60.0 and source.negative_ttl == 60.0
989 source.positive_ttl = 10_000 # changed after construction
990 headers = {"authorization": "Token tok-long"}
991 assert source.resolve(headers).user_id == "8"
992 now[0] += 59
993 source.resolve(headers)
994 assert stub.calls == 1
995 now[0] += 2
996 source.resolve(headers)
997 assert stub.calls == 2
998
999
1000# --- a slow upstream cannot hold the verify slots -----------------------------------
1001
1002
1003class _Drip:
1004 """A raw TCP upstream that answers one byte at a time, each well inside a
1005 per-read timeout, so only a deadline for the whole exchange stops it."""
1006
1007 def __init__(self, phase):
1008 import socket as _socket
1009
1010 self.phase = phase
1011 self.listener = _socket.create_server(("127.0.0.1", 0))
1012 self.url = f"http://127.0.0.1:{self.listener.getsockname()[1]}/v"
1013 self.stop = threading.Event()
1014 self.thread = threading.Thread(target=self._serve, daemon=True)
1015 self.thread.start()
1016
1017 def _serve(self):
1018 self.listener.settimeout(0.2)
1019 while not self.stop.is_set():
1020 try:
1021 conn, _ = self.listener.accept()
1022 except OSError:
1023 continue
1024 threading.Thread(target=self._drip, args=(conn,), daemon=True).start()
1025
1026 def _drip(self, conn):
1027 body = json.dumps({"audience": AUDIENCE, "user_id": 1, "pad": "x" * 200}).encode()
1028 head = (b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
1029 b"Content-Length: " + str(len(body)).encode() + b"\r\n\r\n")
1030 try:
1031 conn.recv(65536)
1032 if self.phase == "body":
1033 conn.sendall(head)
1034 data = body
1035 else:
1036 data = head + body
1037 for i in range(len(data)):
1038 if self.stop.is_set():
1039 break
1040 conn.sendall(data[i:i + 1])
1041 time.sleep(0.05)
1042 except OSError:
1043 pass
1044 finally:
1045 conn.close()
1046
1047 def close(self):
1048 self.stop.set()
1049 self.listener.close()
1050 self.thread.join(timeout=5)
1051
1052
1053@pytest.mark.parametrize("phase", ["headers", "body"])
1054def test_a_dripping_upstream_is_cut_off_at_the_deadline(phase):
1055 drip = _Drip(phase)
1056 try:
1057 source = object_identity_sources.HttpVerifySource(url=drip.url, audience=AUDIENCE, timeout=0.5)
1058 started = time.monotonic()
1059 with pytest.raises(object_identity_sources.IdentityUnavailable):
1060 source.resolve({"authorization": "Token tok-user-1"})
1061 assert time.monotonic() - started < 3.0
1062 # The slot came back: all 8 are free again.
1063 assert source._inflight._value == object_identity_sources.MAX_CONCURRENT_VERIFICATIONS
1064 assert source._cache == {}
1065 finally:
1066 drip.close()
1067
1068
1069# --- per-user objects ---------------------------------------------------------
1070
1071HELLO = "def GET(request):\n return {'hello': 'v1'}\n"
1072HELLO2 = "def GET(request):\n return {'hello': 'v2'}\n"
1073
1074
1075def _create(name, code, who):
1076 return request(
1077 "/objects", method="POST",
1078 body=json.dumps({"name": name, "code": code}).encode(), headers=tok(who),
1079 )
1080
1081
1082def test_user_round_trip_create_run_state_update_versions_destroy(box):
1083 status, _, payload = _create("hello", HELLO, "tok-user-1")
1084 assert status == 201
1085 assert payload["status"] == "ok"
1086 assert payload["object_id"] == "u_1_hello"
1087 assert payload["message"] == "Object created: u_1_hello"
1088 assert (box / "users" / "1" / "hello.py").read_text() == HELLO
1089
1090 status, _, payload = request("/objects/u_1_hello", headers=tok("tok-user-1"))
1091 assert (status, payload) == (200, {"hello": "v1"})
1092
1093 status, _, payload = request("/objects/u_1_hello", query_string="state=true", headers=tok("tok-user-1"))
1094 assert status == 200 and payload["object_id"] == "u_1_hello"
1095
1096 status, _, payload = request("/objects/u_1_hello", query_string="source=true", headers=tok("tok-user-1"))
1097 assert status == 200 and payload["source"] == HELLO
1098
1099 status, _, payload = request(
1100 "/objects/u_1_hello", method="PUT", query_string="source=true",
1101 body=json.dumps({"code": HELLO2, "author": "somebody-else"}).encode(),
1102 headers=tok("tok-user-1"),
1103 )
1104 assert status == 200, payload
1105 _, _, payload = request("/objects/u_1_hello", headers=tok("tok-user-1"))
1106 assert payload == {"hello": "v2"}
1107
1108 status, _, payload = request("/objects/u_1_hello", query_string="versions=true", headers=tok("tok-user-1"))
1109 assert status == 200
1110 versions = payload["versions"]
1111 assert len(versions) >= 2
1112 # A user cannot sign their change with another name.
1113 assert {v.get("author") for v in versions} == {"1"}
1114
1115 status, _, payload = request(
1116 "/objects/u_1_hello", method="POST",
1117 body=json.dumps({"action": "rollback", "version_id": 1}).encode(),
1118 headers=tok("tok-user-1"),
1119 )
1120 assert status == 200, payload
1121 _, _, payload = request("/objects/u_1_hello", headers=tok("tok-user-1"))
1122 assert payload == {"hello": "v1"}
1123
1124 status, _, listing = request("/objects", query_string="format=json", headers=tok("tok-user-1"))
1125 assert status == 200
1126 rows = {obj["object_id"]: obj for obj in listing["objects"]}
1127 assert rows["u_1_hello"] == {"object_id": "u_1_hello", "path": "users/1/hello.py", "owner": "1"}
1128 assert "system_ping" not in rows # system objects are unlisted unless they say LISTED = True
1129
1130 status, _, payload = request(
1131 "/objects/u_1_hello", method="DELETE", query_string="destroy=true", headers=tok("tok-user-1"),
1132 )
1133 assert status == 200, payload
1134 status, _, _ = request("/objects/u_1_hello", headers=tok("tok-user-1"))
1135 assert status == 404
1136
1137
1138def test_another_user_cannot_touch_or_detect_a_user_object(box):
1139 assert _create("hello", HELLO, "tok-user-1")[0] == 201
1140
1141 attempts = [
1142 ("GET", "", b""),
1143 ("GET", "source=true", b""),
1144 ("GET", "state=true", b""),
1145 ("GET", "logs=true", b""),
1146 ("GET", "versions=true", b""),
1147 ("POST", "", b"{}"),
1148 ("POST", "", json.dumps({"action": "rollback", "version_id": 1}).encode()),
1149 ("PUT", "source=true", json.dumps({"code": "def GET(r):\n return 'pwned'\n"}).encode()),
1150 ("DELETE", "destroy=true", b""),
1151 ]
1152 for method, query, body in attempts:
1153 real = request("/objects/u_1_hello", method=method, query_string=query, body=body,
1154 headers=tok("tok-user-2"))
1155 ghost = request("/objects/u_1_nothere", method=method, query_string=query, body=body,
1156 headers=tok("tok-user-2"))
1157 assert real[0] == ghost[0] == 404, (method, query, real)
1158 real_body = dict(real[2], error=None, correlation_id=None)
1159 ghost_body = dict(ghost[2], error=None, correlation_id=None)
1160 assert real_body == ghost_body
1161 assert real[2]["error"].replace("u_1_hello", "X") == ghost[2]["error"].replace("u_1_nothere", "X")
1162
1163 # Anonymous callers are refused the same way.
1164 assert request("/objects/u_1_hello")[0] == 404
1165
1166 # User 2 cannot create into user 1's namespace either.
1167 status, _, _ = request(
1168 "/objects", method="POST",
1169 body=json.dumps({"object_id": "u_1_evil", "code": HELLO}).encode(), headers=tok("tok-user-2"),
1170 )
1171 assert status == 403
1172 status, _, _ = request(
1173 "/objects", method="POST",
1174 body=json.dumps({"name": "evil", "owner_user_id": 1, "code": HELLO}).encode(),
1175 headers=tok("tok-user-2"),
1176 )
1177 assert status == 403
1178
1179 _, _, listing = request("/objects", query_string="format=json", headers=tok("tok-user-2"))
1180 assert "u_1_hello" not in {obj["object_id"] for obj in listing["objects"]}
1181
1182 # Untouched, and still the owner's.
1183 assert (box / "users" / "1" / "hello.py").read_text() == HELLO
1184 assert request("/objects/u_1_hello", headers=tok("tok-user-1"))[2] == {"hello": "v1"}
1185 # The operator still sees and runs everything.
1186 assert request("/objects/u_1_hello", headers=auth_headers())[2] == {"hello": "v1"}
1187
1188
1189def test_user_writes_flag_off_refuses_create_and_update(box, monkeypatch):
1190 monkeypatch.setenv(object_server.USER_SOURCE_WRITES_ENV, "false")
1191 status, _, payload = _create("hello", HELLO, "tok-user-1")
1192 assert status == 403
1193 assert object_server.USER_SOURCE_WRITES_ENV in payload["error"]
1194 assert "sandboxed" in payload["error"]
1195 assert not (box / "users" / "1").exists()
1196
1197 # An object the operator put there can still be run, but not rewritten.
1198 (box / "users" / "1").mkdir(parents=True)
1199 (box / "users" / "1" / "hello.py").write_text(HELLO)
1200 assert request("/objects/u_1_hello", headers=tok("tok-user-1"))[2] == {"hello": "v1"}
1201 status, _, payload = request(
1202 "/objects/u_1_hello", method="PUT", query_string="source=true",
1203 body=json.dumps({"code": HELLO2}).encode(), headers=tok("tok-user-1"),
1204 )
1205 assert status == 403
1206 assert object_server.USER_SOURCE_WRITES_ENV in payload["error"]
1207
1208
1209def test_user_writes_refused_where_user_objects_cannot_run_sandboxed(box, monkeypatch):
1210 # The flag alone is not enough: the host must be able to sandbox user code.
1211 import object_sandbox
1212
1213 monkeypatch.setenv(object_server.USER_SOURCE_WRITES_ENV, "true")
1214 monkeypatch.setattr(object_sandbox, "isolation_status", lambda: {
1215 "mode": "landlock", "available": False, "landlock_abi": 4,
1216 "reason": "user objects need Landlock ABI >= 6 (Linux >= 6.12); this host has Landlock ABI 4",
1217 })
1218 status, _, payload = _create("hello", HELLO, "tok-user-1")
1219 assert status == 403
1220 assert "sandboxed" in payload["error"]
1221 assert "Landlock ABI >= 6" in payload["error"]
1222 assert not (box / "users" / "1").exists()
1223
1224
1225def test_admin_create_and_source_gate_unchanged(box, monkeypatch):
1226 status, _, payload = request(
1227 "/objects", method="POST",
1228 body=json.dumps({"name": "plain", "code": HELLO}).encode(), headers=auth_headers(),
1229 )
1230 assert status == 201 and payload["object_id"] == "plain"
1231 monkeypatch.setenv("DBBASIC_ENABLE_SOURCE_WRITES", "false")
1232 status, _, payload = request(
1233 "/objects", method="POST",
1234 body=json.dumps({"name": "plain2", "code": HELLO}).encode(), headers=auth_headers(),
1235 )
1236 assert status == 403
1237 assert "DBBASIC_ENABLE_SOURCE_WRITES" in payload["error"]
1238
1239
1240# --- owners see their own schedules -------------------------------------------
1241
1242
1243def test_owner_sees_their_schedules_and_nobody_else_does(box):
1244 import object_schedule
1245
1246 assert _create("hello", HELLO, "tok-user-1")[0] == 201
1247 assert _create("other", HELLO, "tok-user-2")[0] == 201
1248 data_dir = str(box.parent / "data")
1249 object_schedule.schedule("u_1_hello", "refresh", 120, base_dir=data_dir, now=1000)
1250 object_schedule.schedule("u_1_hello", "tick", 300, base_dir=data_dir, now=1000)
1251 object_schedule.schedule("u_2_other", "secret_job", 600, base_dir=data_dir, now=1000)
1252 # a daemon-recorded failure shows up as last_error
1253 manager = object_schedule._manager(data_dir)
1254
1255 def mark(state):
1256 key = object_schedule.task_key("u_1_hello", "tick")
1257 row = json.loads(state[key])
1258 row.update({"last_run": 1300, "run_count": 2, "last_error": "ValueError: boom"})
1259 state[key] = json.dumps(row)
1260
1261 manager.modify(mark)
1262
1263 status, _, payload = request(
1264 "/objects/u_1_hello", query_string="schedules=true", headers=tok("tok-user-1")
1265 )
1266 assert status == 200, payload
1267 rows = {row["method"]: row for row in payload["schedules"]}
1268 assert set(rows) == {"refresh", "tick"}
1269 assert rows["refresh"]["interval_seconds"] == 120
1270 assert rows["refresh"]["next_run"] == 1120
1271 assert rows["refresh"]["last_run"] is None and rows["refresh"]["run_count"] == 0
1272 assert "last_error" not in rows["refresh"]
1273 assert rows["tick"]["last_error"] == "ValueError: boom"
1274 assert rows["tick"]["run_count"] == 2
1275 assert "secret_job" not in json.dumps(payload)
1276
1277 # user 2 cannot see user 1's schedules, nor tell the object exists
1278 real = request("/objects/u_1_hello", query_string="schedules=true", headers=tok("tok-user-2"))
1279 ghost = request("/objects/u_1_nothere", query_string="schedules=true", headers=tok("tok-user-2"))
1280 assert real[0] == ghost[0] == 404
1281 assert request("/objects/u_1_hello", query_string="schedules=true")[0] in {401, 403, 404}
1282
1283 # the operator can
1284 status, _, payload = request(
1285 "/objects/u_1_hello", query_string="schedules=true", headers=auth_headers()
1286 )
1287 assert status == 200 and len(payload["schedules"]) == 2
1288
1289 # an object with none says so
1290 status, _, payload = request(
1291 "/objects/u_2_other", query_string="schedules=true", headers=tok("tok-user-2")
1292 )
1293 assert status == 200
1294 assert [row["method"] for row in payload["schedules"]] == ["secret_job"]
1295
1296
1297def test_unknown_or_revoked_api_key_is_never_forwarded_upstream(box, stub):
1298 """A `dbk_` key is this box's credential, valid or not: it never leaves."""
1299 status, _, payload = request("/identity", headers=[("authorization", "Bearer dbk_notakey")])
1300 assert payload["subject"]["user_id"] is None
1301 status, _, _ = request(
1302 "/objects", query_string="format=json", headers=[("authorization", "Bearer dbk_notakey")]
1303 )
1304 assert status == 401
1305 assert stub.calls == 0
1306 assert not any("dbk_" in seen for seen in stub.seen_authorization)
1307
1308
1309@pytest.mark.parametrize("enforced", [True, False])
1310def test_token_is_not_forwarded_when_the_session_store_cannot_say_it_is_ours(
1311 box, stub, monkeypatch, enforced
1312):
1313 """An unreadable session store cannot rule out that the token is a local
1314 session: it stays on the box (503 under enforcement, no credential otherwise)."""
1315 if enforced:
1316 monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true")
1317
1318 def unreadable(token):
1319 raise OSError("sessions.tsv unreadable")
1320
1321 monkeypatch.setattr(object_server, "_resolve_session_token", unreadable)
1322 status, _, payload = request("/identity", headers=tok("tok-user-1"))
1323 if enforced:
1324 assert status == 503 and payload["code"] == "identity_store_unavailable", payload
1325 else:
1326 assert payload["subject"]["user_id"] is None
1327 # The owner stamp on a record create asks the same question.
1328 assert object_server._signed_in_user_id({"authorization": "Token tok-user-1"}) is None
1329 assert stub.calls == 0