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_subscriptions.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_account_subscriptions.py · 13.5 KB · 323 lines
1"""Changing an account's subscriptions: the supported operation for billing.
2
3Before: nothing changed what an account is subscribed to except a hand edit
4of the subscriptions column of accounts.tsv (or a billing integration doing
5the same), with no validation and no record of who did it.
6
7Now PUT|POST /identity/accounts/{id}/subscriptions, the
8set-account-subscriptions CLI command and
9object_identity.set_account_subscriptions replace the account's list. Input
10is validated, the write is atomic, and every change leaves an
11account_subscriptions_set ops line with the actor and the list before and
12after. Sessions read the account row on every request, so a change applies
13to signed-in members on their next request and nobody is signed out. API keys
14carry only the user's own subscriptions, never the account's (unchanged).
15
16Everything runs through the ASGI app, with enforcement on and off.
17"""
18
19import pathlib
20
21import pytest
22
23from test_account_disable import ( # noqa: F401 -- data is a fixture
24 PASSWORD,
25 add_account,
26 add_user,
27 admin_session,
28 call,
29 can_read,
30 data,
31 enforced,
32 login,
33 new_key,
34 seen,
35 stored_session,
36)
37
38import object_identity
39import object_identity_cli
40import object_ops_log
41
42
43def set_subscriptions(account_id, subscriptions, **auth):
44 return call("PUT", f"/identity/accounts/{account_id}/subscriptions",
45 {"subscriptions": subscriptions}, **(auth or {"admin": True}))
46
47
48def account_subscriptions(data, account_id="acme"):
49 return object_identity.get_account(account_id, base_dir=data)["subscriptions"]
50
51
52def ops_lines(data):
53 return object_ops_log.read_events(base_dir=data, kind="auth", event="account_subscriptions_set")
54
55
56# ---- the change applies on the next request, nobody signed out ---------------
57
58def test_a_change_applies_to_signed_in_members_on_the_next_request(data):
59 add_account("acme", ["pro"])
60 add_user("bob", "acme")
61 by_login, by_admin = login("bob"), admin_session("bob")
62 key = new_key("bob")
63 for token in (by_login, by_admin):
64 assert seen(token) == ("bob", "acme", ["pro"])
65 if enforced():
66 assert can_read(token, "reports")
67
68 status, result = set_subscriptions("acme", []) # billing lapse
69 assert status == 200, result
70 assert result["before"] == ["pro"] and result["after"] == [] and result["changed"] is True
71 assert result["account"]["subscriptions"] == []
72 for token in (by_login, by_admin):
73 assert seen(token) == ("bob", "acme", []) # still signed in
74 assert not stored_session(data, token).revoked_at
75 if enforced():
76 assert not can_read(token, "reports")
77 assert can_read(token, "notes") and can_read(token, "ledger")
78 assert seen(key) == ("bob", "acme", []) # keys never had them
79
80 status, result = set_subscriptions("acme", ["pro", "team"]) # paid again
81 assert status == 200 and result["before"] == [] and result["after"] == ["pro", "team"]
82 for token in (by_login, by_admin):
83 assert seen(token) == ("bob", "acme", ["pro", "team"])
84 if enforced():
85 assert can_read(token, "reports")
86 assert seen(key) == ("bob", "acme", [])
87
88
89def test_user_and_account_subscriptions_combine_as_a_union_and_the_account_list_never_removes_the_users(data):
90 """_current_subscriptions: the user's own names first, then the
91 account's, without duplicates. The account's list is the only thing this
92 operation changes; a name the user holds on their own row stays."""
93 add_account("acme", ["pro"])
94 status, payload = call("POST", "/identity/users",
95 {"user_id": "bob", "account_id": "acme", "subscriptions": ["beta", "pro"]}, admin=True)
96 assert status == 201, payload
97 call("POST", "/identity/users/bob/password", {"password": PASSWORD}, admin=True)
98 token = login("bob")
99 assert seen(token) == ("bob", "acme", ["beta", "pro"])
100 set_subscriptions("acme", ["team", "pro"])
101 assert seen(token) == ("bob", "acme", ["beta", "pro", "team"])
102 set_subscriptions("acme", [])
103 assert seen(token) == ("bob", "acme", ["beta", "pro"]) # the user's own row
104
105
106def test_a_session_minted_with_explicit_subscriptions_stays_capped_by_them(data):
107 """A narrowed session (POST /identity/sessions with subscriptions) keeps
108 only what it was minted with that the user still holds: removing the
109 account's name drops it, putting it back restores it, and a name the
110 session was never given does not appear."""
111 add_account("acme", ["pro"])
112 add_user("bob", "acme")
113 status, payload = call("POST", "/identity/sessions", {"user_id": "bob", "subscriptions": ["pro"]}, admin=True)
114 assert status == 201, payload
115 token = payload["token"]
116 assert seen(token) == ("bob", "acme", ["pro"])
117 set_subscriptions("acme", [])
118 assert seen(token) == ("bob", "acme", [])
119 set_subscriptions("acme", ["pro", "team"])
120 assert seen(token) == ("bob", "acme", ["pro"])
121
122
123def test_other_accounts_and_users_without_an_account_are_untouched(data):
124 add_account("acme", ["pro"])
125 add_account("globex", ["pro"])
126 add_user("gail", "globex")
127 add_user("nina")
128 gail, nina = login("gail"), login("nina")
129 set_subscriptions("acme", [])
130 assert seen(gail) == ("gail", "globex", ["pro"])
131 assert seen(nina) == ("nina", None, [])
132
133
134# ---- the audit line ----------------------------------------------------------
135
136def test_every_change_is_logged_with_the_actor_and_the_lists_before_and_after(data):
137 add_account("acme", ["pro"])
138 add_account("ops")
139 add_user("carol", "ops", roles=["admin"])
140 carol = login("carol")
141
142 status, _ = set_subscriptions("acme", ["pro", "team"])
143 assert status == 200
144 status, _ = set_subscriptions("acme", ["team"], token=carol)
145 assert status == 200
146 status, result = set_subscriptions("acme", ["team"]) # no change
147 assert status == 200 and result["changed"] is False
148
149 lines = ops_lines(data)
150 assert len(lines) == 3
151 third, second, first = lines # newest first
152 assert first["identifier"] == "acme"
153 assert first["user_id"] == "admin_token" and first["auth_method"] == "admin_token"
154 assert first["before"] == ["pro"] and first["after"] == ["pro", "team"]
155 assert first["label"] == "before=pro after=pro,team"
156 assert second["user_id"] == "carol" and second["auth_method"] == "admin_session"
157 assert second["before"] == ["pro", "team"] and second["after"] == ["team"]
158 assert third["changed"] is False
159
160
161def test_a_direct_call_is_audited_too(data):
162 """A billing integration calling the function, not the route."""
163 add_account("acme")
164 result = object_identity.set_account_subscriptions(
165 "acme", ["pro"], actor="billing-sync", actor_method="billing", base_dir=data)
166 assert result["after"] == ["pro"]
167 [line] = ops_lines(data)
168 assert line["user_id"] == "billing-sync" and line["auth_method"] == "billing"
169 assert line["before"] == [] and line["after"] == ["pro"]
170 with pytest.raises(ValueError):
171 object_identity.set_account_subscriptions("acme", [], actor="", actor_method="billing", base_dir=data)
172
173
174# ---- validation, gate, errors -------------------------------------------------
175
176@pytest.mark.parametrize(
177 "body, expected",
178 [
179 ({}, 400),
180 ({"subscriptions": "pro"}, 400), # not a list
181 ({"subscriptions": "pro,team"}, 400),
182 ({"subscriptions": None}, 400),
183 ({"subscriptions": [1]}, 400),
184 ({"subscriptions": [""]}, 400),
185 ({"subscriptions": ["has space"]}, 400),
186 ({"subscriptions": ["a,b"]}, 400),
187 ({"subscriptions": [" pro"]}, 400),
188 ({"subscriptions": ["-pro"]}, 400),
189 ({"subscriptions": ["pro\n"]}, 400),
190 ({"subscriptions": ["x" * 65]}, 400),
191 ({"subscriptions": [f"s{n}" for n in range(65)]}, 400),
192 ({"subscriptions": ["pro", "pro"]}, 400), # duplicates refused, not merged
193 ({"subscriptions": ["pro"], "status": "active"}, 400),
194 ],
195)
196def test_bad_input_is_refused_and_changes_nothing(data, body, expected):
197 add_account("acme", ["pro"])
198 status, payload = call("PUT", "/identity/accounts/acme/subscriptions", body, admin=True)
199 assert status == expected, payload
200 assert account_subscriptions(data) == ["pro"]
201 assert ops_lines(data) == []
202
203
204def test_the_limits_themselves_are_accepted(data):
205 add_account("acme")
206 names = ["x" * 64] + [f"plan-{n}.v2:eu@b+c_d" for n in range(63)]
207 status, result = set_subscriptions("acme", names)
208 assert status == 200, result
209 assert account_subscriptions(data) == names
210
211
212@pytest.mark.parametrize(
213 "method, path, expected",
214 [
215 ("PUT", "/identity/accounts/nope/subscriptions", 404),
216 ("GET", "/identity/accounts/acme/subscriptions", 405),
217 ("DELETE", "/identity/accounts/acme/subscriptions", 405),
218 ("PUT", "/admin/identity/accounts/acme/subscriptions", 405),
219 ],
220)
221def test_the_route_refuses_other_methods_and_unknown_accounts(data, method, path, expected):
222 add_account("acme", ["pro"])
223 body = {"subscriptions": []} if method == "PUT" else None
224 status, _ = call(method, path, body, admin=True)
225 assert status == expected
226 assert account_subscriptions(data) == ["pro"]
227
228
229def test_the_route_has_the_status_routes_gate(data):
230 """The admin token, or an admin-role session: the same gate as
231 /identity/accounts/{id}/status. A member's own session, any token that
232 is not one of those, and no token are refused."""
233 add_account("acme", ["pro"])
234 add_user("bob", "acme", roles=["staff"])
235 bob, key = login("bob"), new_key("bob")
236 for auth in ({"token": bob}, {"token": key}, {"token": "nonsense"}, {"headers": ()}):
237 status, _ = set_subscriptions("acme", ["pro", "enterprise"], **auth)
238 assert status in (401, 403)
239 status, _ = call("PUT", "/identity/accounts/acme/status", {"status": "disabled"}, **auth)
240 assert status in (401, 403)
241 assert account_subscriptions(data) == ["pro"]
242 assert ops_lines(data) == []
243
244
245def test_a_target_row_that_does_not_parse_is_refused_and_other_broken_rows_are_kept(data):
246 add_account("acme", ["pro"])
247 add_account("globex", ["pro"])
248 path = object_identity.accounts_path(data)
249 lines = path.read_text().splitlines(keepends=True)
250 path.write_text("".join(line.replace("\tactive\t", "\tsuspended\t") if line.startswith("globex\t") else line
251 for line in lines))
252 status, payload = set_subscriptions("globex", [])
253 assert status == 400 and "fix it by hand" in payload["error"], payload
254 status, _ = set_subscriptions("acme", ["team"])
255 assert status == 200
256 text = path.read_text()
257 assert "globex\t\tsuspended\t" in text and '"[""pro""]"' in text
258 assert account_subscriptions(data) == ["team"]
259
260
261def test_a_failed_write_leaves_the_file_as_it_was(data, monkeypatch):
262 add_account("acme", ["pro"])
263 path = object_identity.accounts_path(data)
264 before = path.read_text()
265 real = pathlib.Path.replace
266
267 def broken(self, target):
268 if pathlib.Path(target) == path:
269 raise OSError("disk full")
270 return real(self, target)
271
272 monkeypatch.setattr(pathlib.Path, "replace", broken)
273 status, payload = set_subscriptions("acme", [])
274 assert status == 503 and payload["code"] == "identity_store_unavailable", payload
275 monkeypatch.setattr(pathlib.Path, "replace", real)
276 assert path.read_text() == before
277 assert ops_lines(data) == []
278
279
280def test_duplicate_rows_for_one_account_are_all_rewritten(data):
281 """A duplicated row is read as the intersection of its rows'
282 subscriptions; setting the list rewrites every row, so what is set is
283 what the resolvers read."""
284 add_account("acme", ["pro"])
285 add_user("bob", "acme")
286 path = object_identity.accounts_path(data)
287 header, row = path.read_text().splitlines(keepends=True)
288 path.write_text(header + row + row.replace('"[""pro""]"', '"[""pro"",""team""]"'))
289 token = login("bob")
290 assert seen(token) == ("bob", "acme", ["pro"])
291 status, result = set_subscriptions("acme", ["team"])
292 assert status == 200 and result["before"] == ["pro"], result
293 assert seen(token) == ("bob", "acme", ["team"])
294 assert path.read_text().count('"[""team""]"') == 2
295
296
297# ---- the CLI -----------------------------------------------------------------
298
299def test_the_cli_sets_and_clears_an_account_s_subscriptions(data, capsys):
300 add_account("acme", ["pro"])
301 add_user("bob", "acme")
302 token = login("bob")
303 cli = ["--data-dir", str(data), "set-account-subscriptions", "--account-id", "acme"]
304
305 assert object_identity_cli.main([*cli, "--subscriptions", "pro,team"]) == 0
306 assert "Account acme subscriptions: pro -> pro,team" in capsys.readouterr().out
307 assert seen(token) == ("bob", "acme", ["pro", "team"])
308
309 assert object_identity_cli.main([*cli, "--subscriptions", ""]) == 0
310 assert "Account acme subscriptions: pro,team -> (none)" in capsys.readouterr().out
311 assert seen(token) == ("bob", "acme", [])
312 assert not stored_session(data, token).revoked_at
313
314 assert object_identity_cli.main([*cli, "--subscriptions", ""]) == 0
315 assert "unchanged" in capsys.readouterr().out
316
317 assert object_identity_cli.main([*cli, "--subscriptions", "pro,pro"]) == 1
318 assert "twice" in capsys.readouterr().err
319 assert object_identity_cli.main(["--data-dir", str(data), "set-account-subscriptions",
320 "--account-id", "nope", "--subscriptions", "pro"]) == 1
321 lines = ops_lines(data)
322 assert len(lines) == 3 and all(line["auth_method"] == "cli" for line in lines)
323 assert all(line["user_id"].startswith("cli") for line in lines)