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_account_row_fail_closed.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_account_row_fail_closed.py · 14.5 KB · 349 lines
1"""A user whose account row is missing or broken is refused, cleanly.
2
3Before: a user whose users.tsv row names an account with no row in
4accounts.tsv (deleted, lost in a restore, or no accounts.tsv at all) was
5treated as if the account were fine: their sessions and API keys kept full
6authority. Signing in for such a user, or for one whose account row does not
7parse, or with an accounts.tsv that cannot be read, was a 500.
8
9Now, for users that reference an account, sign-in and every session and API
10key are refused (object_identity.member_account, AccountUnusableError):
11under enforcement the answer is 403 code account_unusable with a fixed
12message (the detail only for the operator), otherwise the credential carries
13no authority; sign-in is 403 account_unusable in both modes, and only after
14the right password. Each refusal writes an account_unusable ops line (at
15most one a minute per user, account, reason and method). An unreadable
16accounts.tsv is 503 identity_store_unavailable at sign-in too. Nothing is
17ended or deleted, so restoring the row restores everyone.
18
19Users with no account (single-user installs, users made before accounts
20existed: an empty account_id, or a users.tsv with no account_id column) never
21read accounts.tsv and keep working whatever state it is in.
22"""
23
24import urllib.parse
25
26import pytest
27
28from test_account_disable import ( # noqa: F401 -- data is a fixture
29 PASSWORD,
30 add_account,
31 add_user,
32 admin_session,
33 call,
34 can_read,
35 data,
36 enforced,
37 key_ids,
38 login,
39 new_key,
40 seen,
41 stored_session,
42)
43from test_object_server import raw_request
44
45import object_credentials
46import object_identity
47import object_ops_log
48import object_server
49
50
51@pytest.fixture(autouse=True)
52def fresh_log_throttle():
53 object_server._ACCOUNT_UNUSABLE_LOGGED.clear()
54 yield
55 object_server._ACCOUNT_UNUSABLE_LOGGED.clear()
56
57
58def accounts_file(data):
59 return object_identity.accounts_path(data)
60
61
62def drop_account_row(data, account_id="acme"):
63 path = accounts_file(data)
64 path.write_text("".join(line for line in path.read_text().splitlines(keepends=True)
65 if not line.startswith(f"{account_id}\t")))
66
67
68def break_account_row(data, account_id="acme"):
69 """A row whose created_at is not a timestamp: it does not parse."""
70 path = accounts_file(data)
71 lines = path.read_text().splitlines(keepends=True)
72 out = []
73 for line in lines:
74 if line.startswith(f"{account_id}\t"):
75 fields = line.split("\t")
76 fields[4] = "not-a-date"
77 line = "\t".join(fields)
78 out.append(line)
79 path.write_text("".join(out))
80
81
82def password_login(user_id, password=PASSWORD):
83 return call("POST", "/identity/session", {"user_id": user_id, "password": password})
84
85
86def refused(token):
87 """What a request with this credential gets when its account is unusable."""
88 status, payload = call("GET", "/identity", token=token)
89 if enforced():
90 assert status == 403, payload
91 assert payload == {
92 "status": "error",
93 "code": "account_unusable",
94 "error": object_server.ACCOUNT_UNUSABLE_MESSAGE,
95 }
96 else:
97 assert status == 200 and payload["subject"]["user_id"] is None, payload
98 return True
99
100
101def unusable_lines(data):
102 return object_ops_log.read_events(base_dir=data, kind="auth", event="account_unusable")
103
104
105def bob_signed_in():
106 add_account("acme", ["pro"])
107 add_user("bob", "acme")
108 session, minted, key = login("bob"), admin_session("bob"), new_key("bob")
109 assert seen(session) == ("bob", "acme", ["pro"]) and seen(key) == ("bob", "acme", [])
110 return session, minted, key
111
112
113# ---- the three broken shapes -------------------------------------------------
114
115@pytest.mark.parametrize("breakage, reason", [
116 (drop_account_row, "missing"),
117 (lambda data: accounts_file(data).unlink(), "missing"),
118 (break_account_row, "unparsed"),
119])
120def test_sessions_keys_and_sign_in_are_refused_and_restoring_the_row_restores_them(data, breakage, reason):
121 session, minted, key = bob_signed_in()
122 good = accounts_file(data).read_text()
123
124 breakage(data)
125 for token in (session, minted, key):
126 assert refused(token)
127 if enforced():
128 assert not can_read(token, "notes")
129 status, payload = password_login("bob")
130 assert status == 403 and payload["code"] == "account_unusable", payload
131 assert "acme" not in payload["error"] # no detail for the user
132
133 lines = unusable_lines(data)
134 assert lines, "every refusal leaves an ops line"
135 assert {line["identifier"] for line in lines} == {"acme"}
136 assert {line["user_id"] for line in lines} == {"bob"}
137 assert {line["label"] for line in lines} == {f"reason={reason}"}
138 assert {"session", "api_key", "password"} <= {line["auth_method"] for line in lines}
139
140 # Nothing ended or deleted: the row coming back restores everyone.
141 assert not stored_session(data, session).revoked_at and len(key_ids(data)) == 1
142 accounts_file(data).write_text(good)
143 for token in (session, minted):
144 assert seen(token) == ("bob", "acme", ["pro"])
145 assert seen(key) == ("bob", "acme", [])
146 assert login("bob") is not None
147
148
149def test_a_wrong_password_is_still_just_invalid_credentials(data):
150 """The account's state is told only to someone who knows the password."""
151 add_account("acme")
152 add_user("bob", "acme")
153 drop_account_row(data)
154 status, payload = password_login("bob", "not-the-password")
155 assert status == 401 and payload == {"status": "error", "error": "Invalid credentials"}
156 assert unusable_lines(data) == []
157
158
159def test_the_browser_login_form_says_so_instead_of_failing(data):
160 add_account("acme")
161 status, payload = call("POST", "/identity/users",
162 {"user_id": "bob", "account_id": "acme", "email": "bob@example.org"}, admin=True)
163 assert status == 201, payload
164 object_credentials.set_password("bob", PASSWORD, base_dir=data)
165 drop_account_row(data)
166 form = urllib.parse.urlencode({"email": "bob@example.org", "password": PASSWORD}).encode()
167 status, headers, _ = raw_request("/login", method="POST", body=form,
168 headers=[("content-type", "application/x-www-form-urlencoded")])
169 assert status in (302, 303), status
170 location = dict(headers)[b"location"].decode()
171 assert location == "/login?error=account"
172 assert b"set-cookie" not in dict(headers)
173 status, _, page = raw_request("/login", query_string="error=account")
174 assert status == 200
175 assert b"can&#x27;t be used right now" in page or b"can't be used right now" in page
176
177
178def test_the_admin_route_says_which_account_and_why(data):
179 add_account("acme")
180 add_user("bob", "acme")
181 drop_account_row(data)
182 status, payload = call("POST", "/identity/sessions", {"user_id": "bob"}, admin=True)
183 assert status == 403 and payload["code"] == "account_unusable", payload
184 assert "acme" in payload["error_detail"] and "no row" in payload["error_detail"]
185 status, payload = call("POST", "/identity/users/bob/api-keys", {"name": "x"}, admin=True)
186 assert status == 403 and payload["code"] == "account_unusable", payload
187 assert key_ids(data) == []
188
189
190def test_an_unreadable_accounts_file_is_503_at_sign_in_not_500(data):
191 add_account("acme")
192 add_user("bob", "acme")
193 path = accounts_file(data)
194 path.unlink()
195 path.mkdir()
196 status, payload = password_login("bob")
197 assert status == 503 and payload["code"] == "identity_store_unavailable", payload
198
199
200def test_repeated_refusals_log_once_a_minute(data):
201 session, _, _ = bob_signed_in()
202 drop_account_row(data)
203 for _ in range(5):
204 refused(session)
205 assert len([line for line in unusable_lines(data) if line["auth_method"] == "session"]) == 1
206
207
208# ---- who is not affected -----------------------------------------------------
209
210def test_users_with_no_account_never_read_accounts_tsv(data):
211 """A single-user install: no account anywhere, and accounts.tsv in any
212 state at all (absent, unreadable) changes nothing for them."""
213 add_user("nina")
214 assert not accounts_file(data).exists()
215 session, key = login("nina"), new_key("nina")
216 assert seen(session) == ("nina", None, []) and seen(key) == ("nina", None, [])
217 accounts_file(data).mkdir(parents=True) # unreadable as a file
218 assert seen(session) == ("nina", None, []) and seen(key) == ("nina", None, [])
219 assert login("nina") is not None
220 assert unusable_lines(data) == []
221
222
223def test_users_from_before_accounts_existed_keep_working(data):
224 """A users.tsv written before the account_id and subscriptions columns."""
225 path = object_identity.users_path(data)
226 path.parent.mkdir(parents=True, exist_ok=True)
227 stamp = "2025-01-01T00:00:00Z"
228 path.write_text(
229 "user_id\temail\tdisplay_name\tstatus\troles\tcreated_at\tupdated_at\n"
230 f"olga\tolga@example.org\tOlga\tactive\t[]\t{stamp}\t{stamp}\n"
231 )
232 object_credentials.set_password("olga", PASSWORD, base_dir=data)
233 session = login("olga")
234 assert session is not None
235 key = new_key("olga")
236 assert seen(session) == ("olga", None, []) and seen(key) == ("olga", None, [])
237 assert unusable_lines(data) == []
238
239
240def test_other_members_of_healthy_accounts_are_untouched(data):
241 add_account("acme")
242 add_account("globex", ["pro"])
243 add_user("bob", "acme")
244 add_user("gail", "globex")
245 gail = login("gail")
246 drop_account_row(data, "acme")
247 assert seen(gail) == ("gail", "globex", ["pro"])
248 assert login("gail") is not None
249
250
251def test_an_ad_hoc_gateway_session_naming_an_unknown_account_still_works(data):
252 """No user row: the gateway names accounts this box need not know."""
253 status, payload = call("POST", "/identity/sessions",
254 {"user_id": "gateway-user", "account_id": "elsewhere"}, admin=True)
255 assert status == 201, payload
256 assert seen(payload["token"]) == ("gateway-user", "elsewhere", [])
257
258
259def test_trusted_headers_cannot_assert_a_member_of_a_missing_account(data, monkeypatch):
260 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
261 add_account("acme")
262 add_user("bob", "acme")
263 status, payload = call("GET", "/identity", headers=[("x-dbbasic-user-id", "bob")])
264 assert payload["subject"]["user_id"] == "bob"
265 drop_account_row(data)
266 status, payload = call("GET", "/identity", headers=[("x-dbbasic-user-id", "bob")])
267 assert payload["subject"]["user_id"] is None and payload["auth"]["method"] == "anonymous"
268 # An account id asserted for a user with no row here still refuses nothing.
269 status, payload = call("GET", "/identity", headers=[("x-dbbasic-user-id", "visitor"),
270 ("x-dbbasic-account-id", "elsewhere")])
271 assert payload["subject"]["user_id"] == "visitor"
272
273
274# ---- the library ---------------------------------------------------------------
275
276def test_the_library_refuses_by_default_and_explains_on_request(data):
277 session, _, key = bob_signed_in()
278 drop_account_row(data)
279 assert object_identity.resolve_session_token(session, base_dir=data) is None
280 with pytest.raises(object_identity.AccountUnusableError) as caught:
281 object_identity.resolve_session_token(session, base_dir=data, raise_account_unusable=True)
282 assert (caught.value.user_id, caught.value.account_id, caught.value.reason) == ("bob", "acme", "missing")
283 import object_api_keys
284 assert object_api_keys.resolve_api_key(key, base_dir=data) is None
285 with pytest.raises(object_identity.AccountUnusableError):
286 object_api_keys.resolve_api_key(key, base_dir=data, raise_account_unusable=True)
287 with pytest.raises(object_identity.AccountUnusableError):
288 object_identity.create_session({"user_id": "bob"}, base_dir=data)
289
290
291# ---- a user with rows that disagree about the account --------------------------
292
293def duplicate_user_row(data, user_id, account_id):
294 """Append a second users.tsv row for the user, naming another account ("" for none)."""
295 path = object_identity.users_path(data)
296 lines = path.read_text().splitlines()
297 header = lines[0].split("\t")
298 [row] = [line for line in lines[1:] if line.split("\t")[0] == user_id]
299 fields = row.split("\t")
300 fields[header.index("account_id")] = account_id
301 path.write_text("\n".join(lines + ["\t".join(fields)]) + "\n")
302
303
304@pytest.mark.parametrize("other", ["globex", ""])
305def test_rows_naming_different_accounts_are_refused_not_read_as_no_account(data, other):
306 """Two rows for bob, one in acme and one in globex (disabled) or in none: the
307 merged row used to name no account, which skipped every account check."""
308 add_account("globex")
309 call("PUT", "/identity/accounts/globex/status", {"status": "disabled"}, admin=True)
310 session, minted, key = bob_signed_in()
311 duplicate_user_row(data, "bob", other)
312
313 for token in (session, minted, key):
314 assert refused(token)
315 status, payload = password_login("bob")
316 assert status == 403 and payload["code"] == "account_unusable", payload
317 status, payload = call("POST", "/identity/sessions", {"user_id": "bob"}, admin=True)
318 assert status == 403 and "different accounts" in payload["error_detail"], payload
319
320 named = "acme,globex" if other else "(none),acme"
321 lines = unusable_lines(data)
322 assert {line["identifier"] for line in lines} == {named}
323 assert {line["label"] for line in lines} == {"reason=conflicting"}
324 assert {"session", "api_key", "password"} <= {line["auth_method"] for line in lines}
325 with pytest.raises(object_identity.AccountUnusableError) as caught:
326 object_identity.resolve_session_token(session, base_dir=data, raise_account_unusable=True)
327 assert caught.value.reason == "conflicting"
328
329
330def test_trusted_headers_cannot_assert_a_user_whose_rows_disagree(data, monkeypatch):
331 monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true")
332 add_account("acme")
333 add_account("globex")
334 add_user("bob", "acme")
335 duplicate_user_row(data, "bob", "globex")
336 status, payload = call("GET", "/identity", headers=[("x-dbbasic-user-id", "bob")])
337 assert payload["subject"]["user_id"] is None and payload["auth"]["method"] == "anonymous"
338
339
340def test_duplicate_rows_that_agree_are_unaffected(data):
341 session, _, key = bob_signed_in()
342 duplicate_user_row(data, "bob", "acme")
343 assert seen(session) == ("bob", "acme", ["pro"]) and seen(key) == ("bob", "acme", [])
344 add_user("nina")
345 nina = login("nina")
346 duplicate_user_row(data, "nina", "")
347 assert seen(nina) == ("nina", None, [])
348 assert login("nina") is not None
349 assert unusable_lines(data) == []