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_identity.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_identity.py · 15.8 KB · 409 lines
1from datetime import datetime, timedelta, timezone
2from uuid import UUID
3
4import pytest
5
6import object_identity
7
8
9def test_create_account_stores_public_payload(tmp_path):
10 account = object_identity.create_account(
11 {
12 "account_id": "acme",
13 "name": "Acme Corp",
14 "subscriptions": ["pro", "pro", "support"],
15 },
16 base_dir=tmp_path,
17 )
18
19 assert account["account_id"] == "acme"
20 assert account["name"] == "Acme Corp"
21 assert account["status"] == "active"
22 assert account["subscriptions"] == ["pro", "support"]
23
24 assert object_identity.get_account("acme", base_dir=tmp_path) == account
25 assert object_identity.list_accounts(base_dir=tmp_path) == [account]
26
27
28def test_create_account_generates_uuid_id_when_missing(tmp_path):
29 account = object_identity.create_account({"name": "Acme Corp"}, base_dir=tmp_path)
30
31 parsed = UUID(account["account_id"])
32 assert parsed.version == 4
33 assert object_identity.get_account(account["account_id"], base_dir=tmp_path) == account
34
35
36def test_create_user_stores_roles_and_requires_known_account(tmp_path):
37 object_identity.create_account({"account_id": "acme"}, base_dir=tmp_path)
38
39 user = object_identity.create_user(
40 {
41 "user_id": "u_7",
42 "account_id": "acme",
43 "email": "alice@example.com",
44 "display_name": "Alice",
45 "roles": ["sales", "sales", "manager"],
46 "subscriptions": ["team"],
47 },
48 base_dir=tmp_path,
49 )
50
51 assert user["user_id"] == "u_7"
52 assert user["account_id"] == "acme"
53 assert user["email"] == "alice@example.com"
54 assert user["roles"] == ["sales", "manager"]
55
56 assert object_identity.get_user("u_7", base_dir=tmp_path) == user
57 assert object_identity.list_users(base_dir=tmp_path) == [user]
58 assert object_identity.list_users(account_id="acme", base_dir=tmp_path) == [user]
59 assert object_identity.list_users(account_id="other", base_dir=tmp_path) == []
60
61 try:
62 object_identity.create_user(
63 {"user_id": "u_8", "account_id": "missing"},
64 base_dir=tmp_path,
65 )
66 except object_identity.AccountNotFoundError as exc:
67 assert str(exc) == "Account not found: missing"
68 else:
69 raise AssertionError("unknown account should fail")
70
71
72def test_create_user_generates_uuid_id_when_missing(tmp_path):
73 user = object_identity.create_user({"display_name": "Alice"}, base_dir=tmp_path)
74
75 parsed = UUID(user["user_id"])
76 assert parsed.version == 4
77 assert object_identity.get_user(user["user_id"], base_dir=tmp_path) == user
78
79
80def test_create_identity_records_reject_duplicates(tmp_path):
81 object_identity.create_account({"account_id": "acme"}, base_dir=tmp_path)
82 object_identity.create_user({"user_id": "u_7"}, base_dir=tmp_path)
83
84 try:
85 object_identity.create_account({"account_id": "acme"}, base_dir=tmp_path)
86 except object_identity.InvalidIdentityPayloadError as exc:
87 assert str(exc) == "Account already exists: acme"
88 else:
89 raise AssertionError("duplicate account should fail")
90
91 try:
92 object_identity.create_user({"user_id": "u_7"}, base_dir=tmp_path)
93 except object_identity.InvalidIdentityPayloadError as exc:
94 assert str(exc) == "User already exists: u_7"
95 else:
96 raise AssertionError("duplicate user should fail")
97
98
99def test_registered_user_defaults_session_roles_account_and_subscriptions(tmp_path):
100 object_identity.create_account(
101 {"account_id": "acme", "subscriptions": ["pro"]},
102 base_dir=tmp_path,
103 )
104 object_identity.create_user(
105 {
106 "user_id": "u_7",
107 "account_id": "acme",
108 "roles": ["sales"],
109 "subscriptions": ["team"],
110 },
111 base_dir=tmp_path,
112 )
113
114 result = object_identity.create_session({"user_id": "u_7"}, base_dir=tmp_path)
115
116 assert result["session"]["account_id"] == "acme"
117 assert result["session"]["roles"] == ["sales"]
118 assert result["session"]["subscriptions"] == ["team", "pro"]
119
120
121def test_session_rejects_disabled_user_or_account(tmp_path):
122 object_identity.create_account({"account_id": "acme"}, base_dir=tmp_path)
123 object_identity.create_user(
124 {"user_id": "u_7", "account_id": "acme", "status": "disabled"},
125 base_dir=tmp_path,
126 )
127
128 try:
129 object_identity.create_session({"user_id": "u_7"}, base_dir=tmp_path)
130 except object_identity.InvalidSessionPayloadError as exc:
131 assert str(exc) == "User is not active: u_7"
132 else:
133 raise AssertionError("disabled user should not receive a session")
134
135 object_identity.create_account(
136 {"account_id": "closed", "status": "disabled"},
137 base_dir=tmp_path,
138 )
139 object_identity.create_user(
140 {"user_id": "u_8", "account_id": "closed"},
141 base_dir=tmp_path,
142 )
143
144 try:
145 object_identity.create_session({"user_id": "u_8"}, base_dir=tmp_path)
146 except object_identity.InvalidSessionPayloadError as exc:
147 assert str(exc) == "Account is not active: closed"
148 else:
149 raise AssertionError("disabled account should not receive a session")
150
151
152def test_session_can_require_registered_user(tmp_path):
153 try:
154 object_identity.create_session(
155 {"user_id": "u_missing"},
156 base_dir=tmp_path,
157 require_known_user=True,
158 )
159 except object_identity.UserNotFoundError as exc:
160 assert str(exc) == "User not found: u_missing"
161 else:
162 raise AssertionError("strict sessions should require a known user")
163
164
165def test_create_session_stores_hash_and_resolves_subject(tmp_path):
166 now = datetime.now(timezone.utc)
167
168 result = object_identity.create_session(
169 {
170 "user_id": "7",
171 "account_id": "acme",
172 "roles": ["sales", "sales", "manager"],
173 "subscriptions": ["pro"],
174 "label": "scroll",
175 "ttl_seconds": 60,
176 },
177 base_dir=tmp_path,
178 now=now,
179 )
180
181 token = result["token"]
182 session = result["session"]
183 parsed = UUID(session["session_id"])
184 assert parsed.version == 4
185 assert token
186 assert session["user_id"] == "7"
187 assert session["roles"] == ["sales", "manager"]
188 assert session["active"] is True
189
190 session_file = object_identity.sessions_path(tmp_path)
191 stored = session_file.read_text()
192 assert token not in stored
193 assert "sha256:" in stored
194
195 resolved = object_identity.resolve_session_token(
196 token,
197 base_dir=tmp_path,
198 now=now + timedelta(seconds=1),
199 )
200
201 assert resolved is not None
202 assert resolved.subject().user_id == "7"
203 assert resolved.subject().account_id == "acme"
204 assert resolved.subject().roles == ("sales", "manager")
205
206
207def test_expired_session_does_not_resolve(tmp_path):
208 now = datetime.now(timezone.utc)
209 result = object_identity.create_session(
210 {"user_id": "7", "ttl_seconds": 1},
211 base_dir=tmp_path,
212 now=now,
213 )
214
215 resolved = object_identity.resolve_session_token(
216 result["token"],
217 base_dir=tmp_path,
218 now=now + timedelta(seconds=2),
219 )
220
221 assert resolved is None
222
223
224def test_revoke_session_prevents_resolution(tmp_path):
225 now = datetime.now(timezone.utc)
226 result = object_identity.create_session(
227 {"user_id": "7", "ttl_seconds": 60},
228 base_dir=tmp_path,
229 now=now,
230 )
231
232 revoked = object_identity.revoke_session(
233 result["session"]["session_id"],
234 base_dir=tmp_path,
235 now=now + timedelta(seconds=10),
236 )
237
238 assert revoked["active"] is False
239 assert revoked["revoked_at"] is not None
240 assert object_identity.resolve_session_token(result["token"], base_dir=tmp_path, now=now) is None
241
242
243def test_list_sessions_omits_token_material(tmp_path):
244 result = object_identity.create_session({"user_id": "7"}, base_dir=tmp_path)
245
246 sessions = object_identity.list_sessions(base_dir=tmp_path)
247
248 assert sessions == [result["session"]]
249 assert "token" not in sessions[0]
250 assert "token_hash" not in sessions[0]
251
252
253def test_list_sessions_skips_corrupt_rows(tmp_path):
254 result = object_identity.create_session({"user_id": "7"}, base_dir=tmp_path)
255 session_file = object_identity.sessions_path(tmp_path)
256 session_file.write_text(
257 session_file.read_text()
258 + "not-a-session\tbad-hash\t\t\t[]\t[]\t\tbad\tbad\t\n"
259 )
260
261 sessions = object_identity.list_sessions(base_dir=tmp_path)
262
263 assert sessions == [result["session"]]
264
265
266def test_list_sessions_skips_naive_timestamp_rows(tmp_path):
267 result = object_identity.create_session({"user_id": "7"}, base_dir=tmp_path)
268 session_file = object_identity.sessions_path(tmp_path)
269 session_file.write_text(
270 session_file.read_text()
271 + "sess_badbadbadbad\tsha256:"
272 + "0" * 64
273 + "\t8\t\t[]\t[]\t\t2026-06-30T18:00:00\t2026-07-01T18:00:00\t\n"
274 )
275
276 sessions = object_identity.list_sessions(base_dir=tmp_path)
277
278 assert sessions == [result["session"]]
279
280
281def test_create_session_rejects_missing_user_id(tmp_path):
282 try:
283 object_identity.create_session({"roles": ["sales"]}, base_dir=tmp_path)
284 except object_identity.InvalidSessionPayloadError as exc:
285 assert str(exc) == "user_id is required"
286 else:
287 raise AssertionError("missing user_id should fail")
288
289
290def test_create_user_does_not_hand_on_a_leftover_password(tmp_path, caplog):
291 import object_credentials
292
293 object_credentials.set_password("u_7", "the old owner's pass", base_dir=tmp_path)
294 with pytest.raises(object_identity.LeftoverPasswordError):
295 object_identity.create_user({"user_id": "u_7"}, base_dir=tmp_path)
296 assert object_identity.list_users(base_dir=tmp_path) == []
297 assert object_credentials.has_password("u_7", base_dir=tmp_path) # refused, not destroyed
298
299 with caplog.at_level("WARNING", logger="dbbasic.object_identity"):
300 object_identity.create_user({"user_id": "u_7"}, base_dir=tmp_path,
301 leftover_password=object_identity.LEFTOVER_PASSWORD_CLEAR)
302 assert not object_credentials.has_password("u_7", base_dir=tmp_path)
303 assert "u_7" in caplog.text
304
305 object_credentials.set_password("u_8", "written by this caller", base_dir=tmp_path)
306 object_identity.create_user({"user_id": "u_8"}, base_dir=tmp_path,
307 leftover_password=object_identity.LEFTOVER_PASSWORD_KEEP)
308 assert object_credentials.verify_password("u_8", "written by this caller", base_dir=tmp_path)
309
310 with pytest.raises(ValueError):
311 object_identity.create_user({"user_id": "u_9"}, base_dir=tmp_path, leftover_password="maybe")
312
313
314def _user_removed_by_hand(tmp_path, user_id):
315 """A user with a session and an API key, then its users.tsv row deleted by hand (nothing else touched)."""
316 import object_api_keys
317
318 object_identity.create_user({"user_id": user_id, "roles": ["sales"]}, base_dir=tmp_path)
319 session_token = object_identity.create_session({"user_id": user_id}, base_dir=tmp_path)["token"]
320 _meta, key_token = object_api_keys.create_api_key(user_id, "old laptop", base_dir=tmp_path)
321 path = object_identity.users_path(tmp_path)
322 path.write_text(path.read_text().splitlines()[0] + "\n")
323 return session_token, key_token
324
325
326def test_create_user_does_not_hand_on_leftover_sessions_or_api_keys(tmp_path):
327 """The holder of a session or key left under a removed user's id must not become the new user."""
328 import object_api_keys
329
330 session_token, key_token = _user_removed_by_hand(tmp_path, "u_7")
331 with pytest.raises(object_identity.LeftoverCredentialsError) as refused:
332 object_identity.create_user({"user_id": "u_7", "roles": ["admin"]}, base_dir=tmp_path)
333 assert (refused.value.password, refused.value.sessions, refused.value.api_keys) == (False, 1, 1)
334 assert "clear-leftovers --user-id u_7" in str(refused.value)
335 assert object_identity.list_users(base_dir=tmp_path) == []
336 # refused, not destroyed
337 assert object_identity.leftover_credentials("u_7", base_dir=tmp_path) == {
338 "password": False, "sessions": 1, "api_keys": 1}
339
340 removed = object_identity.clear_leftover_credentials("u_7", base_dir=tmp_path)
341 assert removed == {"password": False, "sessions": 1, "api_keys": 1}
342 object_identity.create_user({"user_id": "u_7", "roles": ["admin"]}, base_dir=tmp_path)
343 assert object_identity.resolve_session_token(session_token, base_dir=tmp_path) is None
344 assert object_api_keys.resolve_api_key(key_token, base_dir=tmp_path) is None
345
346
347def test_an_expired_or_ended_session_is_not_a_leftover(tmp_path):
348 session_token, _key = _user_removed_by_hand(tmp_path, "u_7")
349 import object_api_keys
350
351 object_api_keys.revoke_user_api_keys("u_7", base_dir=tmp_path)
352 later = datetime.now(timezone.utc) + timedelta(days=400)
353 assert object_identity.leftover_credentials("u_7", base_dir=tmp_path, now=later)["sessions"] == 0
354 object_identity.create_user({"user_id": "u_7"}, base_dir=tmp_path, now=later)
355
356
357def test_signup_clear_ends_leftover_sessions_and_deletes_keys(tmp_path, caplog):
358 import object_api_keys
359 import object_credentials
360
361 session_token, key_token = _user_removed_by_hand(tmp_path, "u_7")
362 object_credentials.set_password("u_7", "the old owner's pass", base_dir=tmp_path)
363 with caplog.at_level("WARNING", logger="dbbasic.object_identity"):
364 object_identity.create_user({"user_id": "u_7"}, base_dir=tmp_path,
365 leftover_password=object_identity.LEFTOVER_PASSWORD_CLEAR)
366 assert "u_7" in caplog.text and "API keys deleted: 1" in caplog.text
367 assert not object_credentials.has_password("u_7", base_dir=tmp_path)
368 assert object_identity.resolve_session_token(session_token, base_dir=tmp_path) is None
369 assert object_api_keys.resolve_api_key(key_token, base_dir=tmp_path) is None
370
371
372def test_clear_that_fails_creates_nothing(tmp_path, monkeypatch):
373 import object_api_keys
374
375 _user_removed_by_hand(tmp_path, "u_7")
376
377 def unwritable(*args, **kwargs):
378 raise OSError("api_keys.tsv is not writable")
379
380 monkeypatch.setattr(object_api_keys, "_write_entries", unwritable)
381 with pytest.raises(OSError):
382 object_identity.create_user({"user_id": "u_7"}, base_dir=tmp_path,
383 leftover_password=object_identity.LEFTOVER_PASSWORD_CLEAR)
384 assert object_identity.list_users(base_dir=tmp_path) == []
385
386
387def test_keep_keeps_the_callers_password_but_not_leftover_sessions_or_keys(tmp_path):
388 """Setup and create-superuser write the password themselves; they never wrote the sessions or keys."""
389 import object_api_keys
390 import object_credentials
391
392 session_token, key_token = _user_removed_by_hand(tmp_path, "u_7")
393 object_credentials.set_password("u_7", "written by this caller", base_dir=tmp_path)
394 # set_password has ended the session already; mint one more ad hoc, as an operator could have
395 late_token = object_identity.create_session({"user_id": "u_7"}, base_dir=tmp_path)["token"]
396 object_identity.create_user({"user_id": "u_7", "roles": ["admin"]}, base_dir=tmp_path,
397 leftover_password=object_identity.LEFTOVER_PASSWORD_KEEP)
398 assert object_credentials.verify_password("u_7", "written by this caller", base_dir=tmp_path)
399 assert object_identity.resolve_session_token(session_token, base_dir=tmp_path) is None
400 assert object_identity.resolve_session_token(late_token, base_dir=tmp_path) is None
401 assert object_api_keys.resolve_api_key(key_token, base_dir=tmp_path) is None
402
403
404def test_clear_leftover_credentials_refuses_an_id_that_has_a_user(tmp_path):
405 object_identity.create_user({"user_id": "u_7"}, base_dir=tmp_path)
406 session_token = object_identity.create_session({"user_id": "u_7"}, base_dir=tmp_path)["token"]
407 with pytest.raises(object_identity.InvalidIdentityPayloadError):
408 object_identity.clear_leftover_credentials("u_7", base_dir=tmp_path)
409 assert object_identity.resolve_session_token(session_token, base_dir=tmp_path) is not None