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_session_subscription_freshness.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_session_subscription_freshness.py · 10.6 KB · 271 lines
1"""A session's subscriptions and account are the user's current ones.
2
3Sessions read their roles from the user's row on every request
4(test_session_role_freshness), but still copied the user's subscriptions
5(merged with their account's) and account id when they were minted. So a
6cancelled subscription, user's or account's, kept matching ``subscription:``
7rules until the session expired, and a user moved to another account, or
8taken out of one, kept the old account (``account:`` rules, ``$account_id``
9row filters) until they signed in again.
10
11Now both come from the same stat-cached users.tsv parse as the roles, plus a
12stat-cached accounts.tsv parse for the account's subscriptions, under the
13same roles_from rules: a session minted from the user's row follows it; one
14minted with explicit roles or subscriptions, or an older row, is capped by
15it; an ad hoc session for an unregistered id keeps what it has. API keys
16already read the user's row on every request; they are checked here so that
17stays true.
18
19Everything runs through the ASGI app, with enforcement on and off.
20"""
21
22import json
23from dataclasses import replace
24
25import pytest
26
27from test_object_server import save_permission_policy, write_records
28from test_session_role_freshness import ( # noqa: F401 -- the shared fixture
29 _strip_column,
30 age_identity_files,
31 call,
32 change_user,
33 data,
34 enforced,
35 new_key,
36 new_session,
37 stored_session,
38)
39
40import object_identity
41
42POLICY = {
43 "access_mode": "role_based",
44 "admin_roles": ["admin"],
45 "rules": [
46 {"effect": "allow", "principal": "subscription:pro", "actions": ["read"],
47 "collection": "reports", "reason": "pro subscribers read reports"},
48 {"effect": "allow", "principal": "account:acme", "actions": ["read"],
49 "collection": "ledger", "reason": "acme members read the ledger"},
50 ],
51}
52
53
54@pytest.fixture
55def box(data):
56 for name in ("reports", "ledger"):
57 write_records(data, name, "id\ttitle\nr1\thello\n")
58 schema = data / "schemas" / f"{name}.json"
59 schema.write_text(json.dumps({"fields": [{"name": "id"}, {"name": "title"}]}))
60 save_permission_policy(data, POLICY)
61 return data
62
63
64def add_account(account_id, subscriptions=(), status="active"):
65 body = {"account_id": account_id, "subscriptions": list(subscriptions), "status": status}
66 status_code, payload = call("POST", "/identity/accounts", body, admin=True)
67 assert status_code == 201, payload
68
69
70def add_member(user_id, account_id=None, subscriptions=(), roles=()):
71 body = {"user_id": user_id, "roles": list(roles), "subscriptions": list(subscriptions)}
72 if account_id:
73 body["account_id"] = account_id
74 status_code, payload = call("POST", "/identity/users", body, admin=True)
75 assert status_code == 201, payload
76
77
78def change_account(data, account_id, **fields):
79 """A hand edit / another process: there is no account update route."""
80 path = object_identity.accounts_path(data)
81 accounts = [
82 replace(account, **fields) if account.account_id == account_id else account
83 for account in object_identity._read_accounts(path)
84 ]
85 object_identity._write_accounts(path, accounts)
86
87
88def seen(token):
89 """(user_id, account_id, subscriptions) the server sees for a credential."""
90 status_code, payload = call("GET", "/identity", token=token)
91 assert status_code == 200, payload
92 subject = payload["subject"]
93 return subject["user_id"], subject["account_id"], subject["subscriptions"]
94
95
96def can_read(token, collection):
97 status_code, _ = call("GET", f"/collections/{collection}/records", token=token)
98 assert status_code in (200, 401, 403), status_code
99 return status_code == 200
100
101
102# ---- subscriptions -----------------------------------------------------------
103
104def test_a_cancelled_user_subscription_stops_matching_on_the_next_request(box):
105 add_member("bob", subscriptions=["pro", "news"])
106 session, key = new_session("bob"), new_key("bob")
107 assert seen(session) == ("bob", None, ["pro", "news"])
108 if enforced():
109 assert can_read(session, "reports") and can_read(key, "reports")
110
111 change_user(box, subscriptions=("news",)) # cancelled elsewhere: no revocation
112 for token in (session, key):
113 assert seen(token) == ("bob", None, ["news"])
114 if enforced():
115 assert not can_read(token, "reports")
116
117 change_user(box, subscriptions=("news", "pro")) # bought again: no new sign-in
118 assert seen(session) == ("bob", None, ["news", "pro"])
119 if enforced():
120 assert can_read(session, "reports")
121
122
123def test_a_cancelled_account_subscription_stops_matching_on_the_next_request(box):
124 add_account("acme", ["pro"])
125 add_member("bob", "acme", subscriptions=["news"])
126 session = new_session("bob")
127 assert seen(session) == ("bob", "acme", ["news", "pro"])
128 if enforced():
129 assert can_read(session, "reports")
130
131 change_account(box, "acme", subscriptions=())
132 assert seen(session) == ("bob", "acme", ["news"])
133 if enforced():
134 assert not can_read(session, "reports")
135
136
137def test_a_disabled_account_contributes_no_subscriptions(box):
138 """A disabled account could not mint the session; it does not keep
139 paying for one it already has either. It used to leave the session
140 signed in with no subscriptions; now (test_account_disable) a disabled
141 account refuses its users' sessions outright, and a disable written by
142 hand ends the session when it is next presented."""
143 add_account("acme", ["pro"])
144 add_member("bob", "acme")
145 session = new_session("bob")
146 change_account(box, "acme", status="disabled")
147 assert seen(session) == (None, None, [])
148 if enforced():
149 assert not can_read(session, "reports")
150 assert stored_session(box, session).revoked_at
151
152
153def test_an_explicit_subscription_session_is_capped_by_the_user(box):
154 """The admin route can mint a session with chosen subscriptions: it keeps
155 them less any the user no longer has, and is never widened."""
156 add_member("bob", subscriptions=["pro", "news"])
157 narrow = new_session("bob", subscriptions=["news"])
158 wide = new_session("bob", subscriptions=["pro", "news", "gold"])
159 assert stored_session(box, narrow).roles_from == object_identity.ROLES_FROM_SESSION
160 assert seen(narrow) == ("bob", None, ["news"])
161 assert seen(wide) == ("bob", None, ["pro", "news"])
162
163 change_user(box, subscriptions=("news",))
164 assert seen(wide) == ("bob", None, ["news"])
165 if enforced():
166 assert not can_read(wide, "reports")
167
168 change_user(box, subscriptions=("pro", "news", "gold"))
169 assert seen(narrow) == ("bob", None, ["news"]) # a narrowed session is not widened
170 assert seen(wide) == ("bob", None, ["pro", "news", "gold"])
171
172
173# ---- account -----------------------------------------------------------------
174
175def test_a_user_moved_to_another_account_is_seen_in_the_new_one(box):
176 add_account("acme", ["pro"])
177 add_account("globex")
178 add_member("bob", "acme")
179 session, key = new_session("bob"), new_key("bob")
180 if enforced():
181 assert can_read(session, "ledger") and can_read(session, "reports")
182
183 change_user(box, account_id="globex")
184 for token in (session, key):
185 assert seen(token)[:2] == ("bob", "globex")
186 if enforced():
187 assert not can_read(token, "ledger")
188 assert seen(session) == ("bob", "globex", []) # acme's subscription went with acme
189 if enforced():
190 assert not can_read(session, "reports")
191
192
193def test_a_user_taken_out_of_an_account_has_none(box):
194 add_account("acme", ["pro"])
195 add_member("bob", "acme")
196 session = new_session("bob")
197 change_user(box, account_id=None)
198 assert seen(session) == ("bob", None, [])
199 if enforced():
200 assert not can_read(session, "ledger")
201
202
203def test_an_explicit_session_loses_an_account_the_user_left_and_gains_none(box):
204 add_account("acme")
205 add_account("globex")
206 add_member("bob", "acme", roles=["staff"])
207 session = new_session("bob", roles=["staff"])
208 assert seen(session)[:2] == ("bob", "acme")
209 change_user(box, account_id="globex")
210 assert seen(session)[:2] == ("bob", None)
211 change_user(box, account_id="acme")
212 assert seen(session)[:2] == ("bob", "acme")
213
214
215# ---- older rows, ad hoc sessions, failures, cost -----------------------------
216
217def test_a_session_row_from_before_roles_from_is_capped_by_the_user(box):
218 add_account("acme", ["pro"])
219 add_account("globex", ["gold"])
220 add_member("bob", "acme", subscriptions=["news"])
221 session = new_session("bob")
222 _strip_column(object_identity.sessions_path(box), "roles_from")
223 assert stored_session(box, session).roles_from == ""
224
225 change_account(box, "acme", subscriptions=())
226 assert seen(session) == ("bob", "acme", ["news"])
227 change_user(box, account_id="globex")
228 assert seen(session) == ("bob", None, ["news"]) # capped: loses acme, does not gain globex or gold
229 if enforced():
230 assert not can_read(session, "ledger")
231
232
233def test_an_ad_hoc_session_for_an_unregistered_id_keeps_what_it_was_given(box):
234 """Unchanged: nothing to compare against."""
235 session = new_session("ghost", account_id="acme", subscriptions=["pro"])
236 assert stored_session(box, session).roles_from == ""
237 assert seen(session) == ("ghost", "acme", ["pro"])
238 if enforced():
239 assert can_read(session, "reports") and can_read(session, "ledger")
240
241
242def test_an_unreadable_accounts_file_answers_503_under_enforcement(box):
243 add_account("acme", ["pro"])
244 add_member("bob", "acme")
245 session = new_session("bob")
246 accounts = object_identity.accounts_path(box)
247 accounts.unlink()
248 accounts.mkdir()
249 status_code, payload = call("GET", "/collections/reports/records", token=session)
250 if enforced():
251 assert status_code == 503 and payload["code"] == "identity_store_unavailable"
252 else:
253 assert seen(session) == (None, None, [])
254 assert not stored_session(box, session).revoked_at
255
256
257def test_resolving_a_session_does_not_re_read_accounts_tsv_when_unchanged(box, monkeypatch):
258 add_account("acme", ["pro"])
259 add_member("bob", "acme")
260 session = new_session("bob")
261 age_identity_files(box)
262 assert object_identity.resolve_session_token(session, base_dir=box).subscriptions == ("pro",)
263 parses = []
264 real = object_identity._parse_account_records
265 monkeypatch.setattr(object_identity, "_parse_account_records", lambda path: parses.append(path) or real(path))
266 for _ in range(5):
267 assert object_identity.resolve_session_token(session, base_dir=box).subscriptions == ("pro",)
268 assert parses == []
269 change_account(box, "acme", subscriptions=())
270 assert object_identity.resolve_session_token(session, base_dir=box).subscriptions == ()
271 assert len(parses) == 1