askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_session_role_freshness.py · 22.9 KB · 555 lines
| 1 | """A credential never carries more than its user currently has. |
| 2 | |
| 3 | Sessions used to copy the user's roles when they were minted, and every |
| 4 | permission check read that copy. So a role removed by anything but the roles |
| 5 | route (another process, a hand edit) left a session admin until it expired, |
| 6 | and a user deleted from users.tsv kept a working session with all of their |
| 7 | old roles. In the other direction a granted role needed a new sign-in. API |
| 8 | keys never copied roles, but a deleted user's key went on authenticating as |
| 9 | that user id. |
| 10 | |
| 11 | Now the session's roles are read from the user's row on every request (the |
| 12 | same stat-cached parse that already checked the user was active), a disabled |
| 13 | or deleted user's session and key are ended when presented, and a users file |
| 14 | that is missing altogether is "cannot check" (503 under enforcement), not |
| 15 | "everyone was deleted". Remote identity-source users have no local session: |
| 16 | their roles are the upstream's answer, bounded by its cache TTL. |
| 17 | |
| 18 | Everything runs through the ASGI app, with enforcement on and off. |
| 19 | """ |
| 20 | |
| 21 | import json |
| 22 | import os |
| 23 | import subprocess |
| 24 | import sys |
| 25 | import textwrap |
| 26 | import time |
| 27 | from dataclasses import replace |
| 28 | from pathlib import Path |
| 29 | |
| 30 | import pytest |
| 31 | |
| 32 | from test_object_server import TEST_ADMIN_TOKEN, request, save_permission_policy, write_records |
| 33 | |
| 34 | import object_api_keys |
| 35 | import object_identity |
| 36 | import object_identity_sources |
| 37 | import object_server |
| 38 | import object_signup |
| 39 | |
| 40 | REPO = Path(__file__).resolve().parents[1] |
| 41 | |
| 42 | POLICY = { |
| 43 | "access_mode": "role_based", |
| 44 | "admin_roles": ["admin"], |
| 45 | "rules": [ |
| 46 | {"effect": "allow", "principal": "registered", "actions": ["read"], |
| 47 | "collection": "notes", "reason": "every signed-in user reads notes"}, |
| 48 | {"effect": "allow", "principal": "role:staff", "actions": ["create"], |
| 49 | "collection": "notes", "reason": "staff write notes"}, |
| 50 | ], |
| 51 | } |
| 52 | |
| 53 | |
| 54 | @pytest.fixture(params=[True, False], ids=["enforced", "unenforced"]) |
| 55 | def data(request, tmp_path, monkeypatch): |
| 56 | data = tmp_path / "data" |
| 57 | write_records(data, "notes", "id\ttitle\nn1\thello\n") |
| 58 | schema = data / "schemas" / "notes.json" |
| 59 | schema.parent.mkdir(parents=True, exist_ok=True) |
| 60 | schema.write_text(json.dumps({"fields": [{"name": "id"}, {"name": "title"}]})) |
| 61 | save_permission_policy(data, POLICY) |
| 62 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data)) |
| 63 | monkeypatch.setenv(object_server.ADMIN_TOKEN_ENV, TEST_ADMIN_TOKEN) |
| 64 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true" if request.param else "false") |
| 65 | monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true") |
| 66 | for name in (object_server.REQUIRE_KNOWN_IDENTITY_USERS_ENV, object_server.PERMISSION_TRUST_HEADERS_ENV, |
| 67 | object_identity_sources.IDENTITY_VERIFY_URL_ENV): |
| 68 | monkeypatch.delenv(name, raising=False) |
| 69 | return data |
| 70 | |
| 71 | |
| 72 | def enforced(): |
| 73 | return os.environ.get(object_server.PERMISSION_ENFORCEMENT_ENV) == "true" |
| 74 | |
| 75 | |
| 76 | def call(method, path, body=None, token=None, admin=False): |
| 77 | sent = [] |
| 78 | if admin: |
| 79 | sent.append(("authorization", f"Token {TEST_ADMIN_TOKEN}")) |
| 80 | elif token: |
| 81 | sent.append(("authorization", f"Bearer {token}")) |
| 82 | raw = b"" |
| 83 | if body is not None: |
| 84 | raw = json.dumps(body).encode() |
| 85 | sent.append(("content-type", "application/json")) |
| 86 | status, _, payload = request(path, method=method, body=raw, headers=sent) |
| 87 | return status, payload |
| 88 | |
| 89 | |
| 90 | def add_user(user_id, roles=(), email=None): |
| 91 | body = {"user_id": user_id, "roles": list(roles)} |
| 92 | if email: |
| 93 | body["email"] = email |
| 94 | status, payload = call("POST", "/identity/users", body, admin=True) |
| 95 | assert status == 201, payload |
| 96 | |
| 97 | |
| 98 | def new_session(user_id, **extra): |
| 99 | status, payload = call("POST", "/identity/sessions", {"user_id": user_id, **extra}, admin=True) |
| 100 | assert status == 201, payload |
| 101 | return payload["token"] |
| 102 | |
| 103 | |
| 104 | def new_key(user_id): |
| 105 | status, payload = call("POST", f"/identity/users/{user_id}/api-keys", {"name": "laptop"}, admin=True) |
| 106 | assert status == 200, payload |
| 107 | return payload["token"] |
| 108 | |
| 109 | |
| 110 | def who(token): |
| 111 | """(user_id, roles) the server sees for a credential.""" |
| 112 | status, payload = call("GET", "/identity", token=token) |
| 113 | assert status == 200, payload |
| 114 | return payload["subject"]["user_id"], payload["subject"]["roles"] |
| 115 | |
| 116 | |
| 117 | def is_admin(token): |
| 118 | """The session-admin gate (DBBASIC_ENABLE_SESSION_ADMIN_GATES).""" |
| 119 | status, _ = call("GET", "/identity/users", token=token) |
| 120 | assert status in (200, 401), status |
| 121 | return status == 200 |
| 122 | |
| 123 | |
| 124 | def can_create(data, token): |
| 125 | """Under enforcement only role:staff may create a note.""" |
| 126 | status, _ = call("POST", "/collections/notes/records", {"title": "x"}, token=token) |
| 127 | if enforced(): |
| 128 | assert status in (201, 401, 403), status |
| 129 | return status == 201 |
| 130 | |
| 131 | |
| 132 | def change_user(data, **fields): |
| 133 | """A write to users.tsv that is not the roles or status route: no |
| 134 | revocation, as another process or a hand edit would leave it.""" |
| 135 | object_identity._update_user("bob", lambda user: replace(user, **fields), base_dir=data, now=None) |
| 136 | |
| 137 | |
| 138 | def delete_row(data, user_id="bob"): |
| 139 | path = object_identity.users_path(data) |
| 140 | object_identity._write_users(path, [u for u in object_identity._read_users(path) if u.user_id != user_id]) |
| 141 | |
| 142 | |
| 143 | def stored_session(data, token): |
| 144 | wanted = object_identity.hash_token(token) |
| 145 | [row] = [s for s in object_identity._read_sessions(object_identity.sessions_path(data)) if s.token_hash == wanted] |
| 146 | return row |
| 147 | |
| 148 | |
| 149 | def key_ids(data, user_id="bob"): |
| 150 | return [k["key_id"] for k in object_api_keys.list_api_keys(user_id, base_dir=data)] |
| 151 | |
| 152 | |
| 153 | def age_identity_files(data): |
| 154 | old = time.time() - 600 |
| 155 | for path in (data / "identity").glob("*.tsv"): |
| 156 | os.utime(path, (old, old)) |
| 157 | |
| 158 | |
| 159 | # ---- the dangerous direction: removing access ----------------------------- |
| 160 | |
| 161 | def test_a_role_removed_outside_the_roles_route_leaves_the_session_on_the_next_request(data): |
| 162 | """Before: the session stayed staff and admin until it expired.""" |
| 163 | add_user("bob", ["staff", "admin"]) |
| 164 | session, key = new_session("bob"), new_key("bob") |
| 165 | assert who(session) == ("bob", ["staff", "admin"]) and is_admin(session) |
| 166 | if enforced(): |
| 167 | assert can_create(data, session) |
| 168 | |
| 169 | change_user(data, roles=("member",)) |
| 170 | |
| 171 | for token in (session, key): |
| 172 | assert who(token) == ("bob", ["member"]) |
| 173 | assert not is_admin(token) |
| 174 | assert not can_create(data, token) |
| 175 | # still signed in, just without the roles |
| 176 | assert not stored_session(data, session).revoked_at |
| 177 | |
| 178 | |
| 179 | def test_a_role_removed_by_another_process_is_seen_through_a_warm_cache(data): |
| 180 | add_user("bob", ["staff", "admin"]) |
| 181 | session = new_session("bob") |
| 182 | age_identity_files(data) |
| 183 | assert is_admin(session) # caches now hold the parse |
| 184 | script = textwrap.dedent( |
| 185 | """ |
| 186 | import sys |
| 187 | from pathlib import Path |
| 188 | path = Path(sys.argv[1]) |
| 189 | text = path.read_text() |
| 190 | old = '""admin""' # the roles JSON, csv-quoted |
| 191 | assert old in text |
| 192 | path.write_text(text.replace(old, '""xxxxx""')) # same size, in place |
| 193 | """ |
| 194 | ) |
| 195 | subprocess.run([sys.executable, "-c", script, str(object_identity.users_path(data))], check=True) |
| 196 | assert who(session) == ("bob", ["staff", "xxxxx"]) |
| 197 | assert not is_admin(session) |
| 198 | |
| 199 | |
| 200 | def test_the_roles_route_still_signs_out_sessions_holding_a_removed_role(data): |
| 201 | """Unchanged: PUT .../roles revokes sessions carrying a removed role.""" |
| 202 | add_user("bob", ["staff", "admin"]) |
| 203 | session, key = new_session("bob"), new_key("bob") |
| 204 | status, result = call("PUT", "/identity/users/bob/roles", {"roles": ["member"]}, admin=True) |
| 205 | assert status == 200 and result["sessions_revoked"] == 1 |
| 206 | assert who(session) == (None, []) |
| 207 | assert who(key) == ("bob", ["member"]) |
| 208 | |
| 209 | |
| 210 | def test_a_disabled_user_loses_session_and_key_and_re_enabling_does_not_bring_them_back(data): |
| 211 | """Before: refused while disabled, but a disable written by another |
| 212 | process revoked nothing, so re-enabling restored the old session (with |
| 213 | its old roles) and the old key.""" |
| 214 | add_user("bob", ["staff", "admin"]) |
| 215 | session, key = new_session("bob"), new_key("bob") |
| 216 | |
| 217 | change_user(data, status="disabled") |
| 218 | for token in (session, key): |
| 219 | assert who(token) == (None, []) |
| 220 | assert not is_admin(token) |
| 221 | assert not can_create(data, token) |
| 222 | assert stored_session(data, session).revoked_at |
| 223 | assert key_ids(data) == [] |
| 224 | |
| 225 | change_user(data, status="active") |
| 226 | assert who(session) == (None, []) and who(key) == (None, []) |
| 227 | assert who(new_session("bob")) == ("bob", ["staff", "admin"]) |
| 228 | |
| 229 | |
| 230 | def test_the_status_route_still_revokes_everything(data): |
| 231 | add_user("bob", ["staff"]) |
| 232 | session, key = new_session("bob"), new_key("bob") |
| 233 | status, result = call("PUT", "/identity/users/bob/status", {"status": "disabled"}, admin=True) |
| 234 | assert status == 200 and result["sessions_revoked"] == 1 and result["api_keys_revoked"] == 1 |
| 235 | assert who(session) == (None, []) and who(key) == (None, []) |
| 236 | |
| 237 | |
| 238 | def test_a_deleted_user_loses_session_and_key_and_re_creating_does_not_bring_them_back(data): |
| 239 | """Before: a session kept every old role (admin included) and the key |
| 240 | stayed signed in as the user id with no roles.""" |
| 241 | add_user("bob", ["staff", "admin"]) |
| 242 | session, key = new_session("bob"), new_key("bob") |
| 243 | |
| 244 | delete_row(data) |
| 245 | for token in (session, key): |
| 246 | assert who(token) == (None, []) |
| 247 | assert not is_admin(token) |
| 248 | assert not can_create(data, token) |
| 249 | assert stored_session(data, session).revoked_at |
| 250 | assert key_ids(data) == [] |
| 251 | |
| 252 | add_user("bob", ["staff", "admin"]) |
| 253 | assert who(session) == (None, []) and who(key) == (None, []) |
| 254 | |
| 255 | |
| 256 | def test_a_user_deleted_by_hand_cannot_be_re_created_over_a_session_nobody_presented(data): |
| 257 | """Nothing presents the session between the delete and the re-create, so it |
| 258 | is not ended at first use. It used to come back as the new user (with the |
| 259 | new row's roles); now the re-create is refused while it is signed in, and |
| 260 | clearing the id ends it.""" |
| 261 | add_user("bob", ["staff", "admin"]) |
| 262 | session = new_session("bob") |
| 263 | delete_row(data) |
| 264 | status, payload = call("POST", "/identity/users", {"user_id": "bob", "roles": []}, admin=True) |
| 265 | assert status == 400 and "1 session(s) still signed in" in payload["error"], payload |
| 266 | object_identity.clear_leftover_credentials("bob", base_dir=data) |
| 267 | add_user("bob", []) |
| 268 | assert who(session) == (None, []) |
| 269 | |
| 270 | |
| 271 | def test_a_row_that_does_not_parse_refuses_without_ending_anything(data): |
| 272 | """A hand-edit typo: refused (as before), but the session and key are not |
| 273 | destroyed, so fixing the row restores them.""" |
| 274 | add_user("bob", ["staff"]) |
| 275 | session, key = new_session("bob"), new_key("bob") |
| 276 | users = object_identity.users_path(data) |
| 277 | good = users.read_text() |
| 278 | lines = good.splitlines() |
| 279 | header, row = lines[0].split("\t"), lines[1].split("\t") |
| 280 | row[header.index("created_at")] = "not-a-timestamp" |
| 281 | users.write_text("\n".join([lines[0], "\t".join(row)]) + "\n") |
| 282 | |
| 283 | assert who(session) == (None, []) and who(key) == (None, []) |
| 284 | assert not stored_session(data, session).revoked_at |
| 285 | assert len(key_ids(data)) == 1 |
| 286 | |
| 287 | users.write_text(good) |
| 288 | assert who(session) == ("bob", ["staff"]) and who(key) == ("bob", ["staff"]) |
| 289 | |
| 290 | |
| 291 | def test_a_missing_users_file_is_unavailable_not_every_user_deleted(data): |
| 292 | """Bound credentials with no users.tsv at all: 503 under enforcement (the |
| 293 | identity_store_unavailable answer), no credential when not enforced -- |
| 294 | and nothing is revoked, so restoring the file restores everyone.""" |
| 295 | add_user("bob", ["staff"]) |
| 296 | session, key = new_session("bob"), new_key("bob") |
| 297 | users = object_identity.users_path(data) |
| 298 | users.rename(users.with_name("users.tsv.bak")) |
| 299 | |
| 300 | for token in (session, key): |
| 301 | status, payload = call("GET", "/collections/notes/records", token=token) |
| 302 | if enforced(): |
| 303 | assert status == 503 and payload["code"] == "identity_store_unavailable", payload |
| 304 | else: |
| 305 | assert who(token) == (None, []) |
| 306 | assert not stored_session(data, session).revoked_at |
| 307 | assert len(key_ids(data)) == 1 |
| 308 | |
| 309 | users.with_name("users.tsv.bak").rename(users) |
| 310 | assert who(session) == ("bob", ["staff"]) and who(key) == ("bob", ["staff"]) |
| 311 | |
| 312 | |
| 313 | def test_an_unreadable_users_file_still_answers_503_under_enforcement(data): |
| 314 | add_user("bob", ["staff"]) |
| 315 | session, key = new_session("bob"), new_key("bob") |
| 316 | users = object_identity.users_path(data) |
| 317 | users.unlink() |
| 318 | users.mkdir() |
| 319 | for token in (session, key): |
| 320 | status, payload = call("GET", "/collections/notes/records", token=token) |
| 321 | if enforced(): |
| 322 | assert status == 503 and payload["code"] == "identity_store_unavailable" |
| 323 | else: |
| 324 | assert who(token) == (None, []) |
| 325 | |
| 326 | |
| 327 | def test_a_password_reset_by_link_ends_sessions_but_not_keys(data): |
| 328 | """Unchanged, recorded here: a reset link revokes every session; API keys |
| 329 | are left alone (a key is not the password).""" |
| 330 | add_user("bob", ["staff"], email="bob@example.org") |
| 331 | session, key = new_session("bob"), new_key("bob") |
| 332 | link = object_signup.issue_token(object_signup.PASSWORD_RESET, "bob", "bob@example.org", base_dir=data) |
| 333 | assert object_signup.reset_password(link, "a-long-new-password-1", base_dir=data) is not None |
| 334 | assert who(session) == (None, []) |
| 335 | assert who(key) == ("bob", ["staff"]) |
| 336 | |
| 337 | |
| 338 | def test_an_admin_password_change_ends_sessions_but_not_keys(data): |
| 339 | """Decided since: setting a password through the admin route ends the |
| 340 | user's sessions like a reset link does, and leaves keys alone |
| 341 | (tests/test_password_change_ends_sessions.py covers every path).""" |
| 342 | add_user("bob", ["staff"]) |
| 343 | session, key = new_session("bob"), new_key("bob") |
| 344 | status, _ = call("POST", "/identity/users/bob/password", {"password": "a-long-new-password-2"}, admin=True) |
| 345 | assert status == 200 |
| 346 | assert who(session) == (None, []) |
| 347 | assert who(key) == ("bob", ["staff"]) |
| 348 | |
| 349 | |
| 350 | # ---- the annoying direction: granting access ------------------------------ |
| 351 | |
| 352 | def test_a_granted_role_applies_without_signing_in_again(data): |
| 353 | """Before: the session kept ["member"] until the next sign-in.""" |
| 354 | add_user("bob", ["member"]) |
| 355 | session, key = new_session("bob"), new_key("bob") |
| 356 | assert not is_admin(session) |
| 357 | |
| 358 | status, result = call("PUT", "/identity/users/bob/roles", {"roles": ["member", "staff", "admin"]}, admin=True) |
| 359 | assert status == 200 and result["sessions_revoked"] == 0 |
| 360 | for token in (session, key): |
| 361 | assert who(token) == ("bob", ["member", "staff", "admin"]) |
| 362 | assert is_admin(session) |
| 363 | if enforced(): |
| 364 | assert can_create(data, session) and can_create(data, key) |
| 365 | |
| 366 | change_user(data, roles=("member", "auditor")) # another process |
| 367 | assert who(session) == ("bob", ["member", "auditor"]) |
| 368 | |
| 369 | |
| 370 | def test_the_own_session_route_shows_the_current_roles(data): |
| 371 | add_user("bob", ["member"]) |
| 372 | session = new_session("bob") |
| 373 | change_user(data, roles=("member", "staff")) |
| 374 | status, payload = call("GET", "/identity/session", token=session) |
| 375 | assert status == 200 and payload["session"]["roles"] == ["member", "staff"] |
| 376 | |
| 377 | |
| 378 | # ---- sessions minted with explicit roles, ad hoc users, older rows --------- |
| 379 | |
| 380 | def test_an_explicit_role_session_keeps_its_narrower_roles_capped_by_the_user(data): |
| 381 | add_user("bob", ["staff", "admin"]) |
| 382 | narrow = new_session("bob", roles=["staff"]) |
| 383 | wide = new_session("bob", roles=["staff", "admin", "superuser"]) |
| 384 | assert who(narrow) == ("bob", ["staff"]) # a narrowed session is not widened |
| 385 | assert who(wide) == ("bob", ["staff", "admin"]) # never more than the user has |
| 386 | |
| 387 | change_user(data, roles=("staff",)) |
| 388 | assert who(narrow) == ("bob", ["staff"]) |
| 389 | assert who(wide) == ("bob", ["staff"]) and not is_admin(wide) |
| 390 | |
| 391 | change_user(data, roles=("staff", "admin", "superuser")) |
| 392 | assert who(wide) == ("bob", ["staff", "admin", "superuser"]) |
| 393 | |
| 394 | delete_row(data) |
| 395 | assert who(narrow) == (None, []) and who(wide) == (None, []) |
| 396 | |
| 397 | |
| 398 | def test_an_ad_hoc_session_for_an_unregistered_id_keeps_its_roles(data): |
| 399 | """Unchanged: a gateway session for a user id with no row has nothing to |
| 400 | compare against, so it keeps the roles it was minted with -- and a key |
| 401 | for such an id keeps working. A user row is not created under them: the |
| 402 | create is refused while they are live (see create_user's leftovers).""" |
| 403 | session = new_session("ghost", roles=["staff", "admin"]) |
| 404 | _meta, key = object_api_keys.create_api_key("ghost", "x", base_dir=data) |
| 405 | assert who(session) == ("ghost", ["staff", "admin"]) |
| 406 | assert who(key) == ("ghost", []) |
| 407 | |
| 408 | status, payload = call("POST", "/identity/users", {"user_id": "ghost", "roles": ["staff"]}, admin=True) |
| 409 | assert status == 400, payload |
| 410 | assert who(session) == ("ghost", ["staff", "admin"]) |
| 411 | |
| 412 | |
| 413 | def test_required_known_users_still_refuses_ad_hoc_credentials(data, monkeypatch): |
| 414 | session = new_session("ghost", roles=["staff"]) |
| 415 | _meta, key = object_api_keys.create_api_key("ghost", "x", base_dir=data) |
| 416 | monkeypatch.setenv(object_server.REQUIRE_KNOWN_IDENTITY_USERS_ENV, "true") |
| 417 | assert who(session) == (None, []) and who(key) == (None, []) |
| 418 | |
| 419 | |
| 420 | def _strip_column(path, column): |
| 421 | lines = path.read_text().splitlines() |
| 422 | header = lines[0].split("\t") |
| 423 | at = header.index(column) |
| 424 | rows = [line.split("\t") for line in lines] |
| 425 | path.write_text("\n".join("\t".join(r[:at] + r[at + 1:]) for r in rows) + "\n") |
| 426 | |
| 427 | |
| 428 | def test_a_session_row_from_before_this_change_is_capped_by_the_user(data): |
| 429 | """A sessions.tsv written by an older server has no roles_from column. Its |
| 430 | rows are capped by the user's current roles; a deleted user's old row |
| 431 | keeps its stored roles (it cannot tell "deleted" from "never registered") |
| 432 | until it expires, as before.""" |
| 433 | add_user("bob", ["staff", "admin"]) |
| 434 | session = new_session("bob") |
| 435 | _strip_column(object_identity.sessions_path(data), "roles_from") |
| 436 | assert stored_session(data, session).roles_from == "" |
| 437 | |
| 438 | change_user(data, roles=("staff",)) |
| 439 | assert who(session) == ("bob", ["staff"]) and not is_admin(session) |
| 440 | change_user(data, roles=("staff", "admin")) |
| 441 | assert who(session) == ("bob", ["staff", "admin"]) # capped, not live: back within what it had |
| 442 | |
| 443 | change_user(data, roles=("staff", "admin", "auditor")) |
| 444 | assert who(session) == ("bob", ["staff", "admin"]) # an older row is not widened |
| 445 | |
| 446 | delete_row(data) |
| 447 | assert who(session) == ("bob", ["staff", "admin"]) |
| 448 | |
| 449 | |
| 450 | def test_an_api_key_row_from_before_this_change_keeps_the_old_deleted_user_rule(data): |
| 451 | add_user("bob", ["staff"]) |
| 452 | key = new_key("bob") |
| 453 | _strip_column(object_api_keys.api_keys_path(data), "user_bound") |
| 454 | delete_row(data) |
| 455 | assert who(key) == ("bob", []) # as before this change: no roles, still the user id |
| 456 | |
| 457 | |
| 458 | def test_an_unknown_roles_from_value_is_the_strictest_binding(data): |
| 459 | add_user("bob", ["staff"]) |
| 460 | session = new_session("bob", roles=["staff", "admin"]) |
| 461 | path = object_identity.sessions_path(data) |
| 462 | path.write_text(path.read_text().replace("\tsession\n", "\tsomething-newer\n")) |
| 463 | assert stored_session(data, session).roles_from == object_identity.ROLES_FROM_SESSION |
| 464 | assert who(session) == ("bob", ["staff"]) |
| 465 | delete_row(data) |
| 466 | assert who(session) == (None, []) |
| 467 | |
| 468 | |
| 469 | # ---- remote identity-source users ---------------------------------------- |
| 470 | |
| 471 | class _FakeVerify: |
| 472 | """Stands in for the upstream verify endpoint; never touches the network.""" |
| 473 | |
| 474 | def __init__(self): |
| 475 | self.answers = {} |
| 476 | self.calls = 0 |
| 477 | self.now = 1000.0 |
| 478 | |
| 479 | def fetch(self, url, authorization, timeout, max_bytes, extra_headers=None): |
| 480 | self.calls += 1 |
| 481 | payload = self.answers.get(authorization) |
| 482 | if payload is None: |
| 483 | return 401, b"", "application/json" |
| 484 | audience = (extra_headers or {}).get(object_identity_sources.AUDIENCE_HEADER) |
| 485 | return 200, json.dumps({"audience": audience, **payload}).encode(), "application/json" |
| 486 | |
| 487 | def clock(self): |
| 488 | return self.now |
| 489 | |
| 490 | |
| 491 | @pytest.fixture |
| 492 | def upstream(data, monkeypatch): |
| 493 | monkeypatch.setenv(object_identity_sources.IDENTITY_VERIFY_URL_ENV, "https://verify.invalid/api/auth/verify/") |
| 494 | monkeypatch.setenv(object_identity_sources.IDENTITY_VERIFY_SECRET_ENV, "test-shared-secret-0123") |
| 495 | monkeypatch.setenv(object_identity_sources.IDENTITY_AUDIENCE_ENV, "box-test.example") |
| 496 | monkeypatch.setenv(object_identity_sources.IDENTITY_ALLOWED_ROLES_ENV, "staff") |
| 497 | monkeypatch.delenv(object_identity_sources.POSITIVE_CACHE_ENV, raising=False) |
| 498 | monkeypatch.setattr(object_identity_sources, "_CONFIGURED", None) |
| 499 | [source] = object_identity_sources.configured_sources() |
| 500 | fake = _FakeVerify() |
| 501 | monkeypatch.setattr(source, "fetch", fake.fetch) |
| 502 | monkeypatch.setattr(source, "clock", fake.clock) |
| 503 | fake.source = source |
| 504 | yield fake |
| 505 | monkeypatch.setattr(object_identity_sources, "_CONFIGURED", None) |
| 506 | |
| 507 | |
| 508 | def remote_who(token): |
| 509 | status, _, payload = request("/identity", headers=[("authorization", f"Token {token}")]) |
| 510 | assert status == 200, payload |
| 511 | return payload["subject"]["user_id"], payload["subject"]["roles"] |
| 512 | |
| 513 | |
| 514 | def test_a_remote_user_s_roles_are_the_upstream_answer_bounded_by_the_cache_ttl(data, upstream): |
| 515 | """No local session, no snapshot of ours: the roles are the upstream's |
| 516 | latest answer, trusted for DBBASIC_IDENTITY_CACHE_TTL_SECONDS (30 s by |
| 517 | default). No call per request inside that window.""" |
| 518 | upstream.answers["Token remote-1"] = {"user_id": 7, "roles": ["staff"]} |
| 519 | assert remote_who("remote-1") == ("7", ["staff"]) |
| 520 | calls = upstream.calls |
| 521 | |
| 522 | upstream.answers["Token remote-1"] = {"user_id": 7, "roles": []} |
| 523 | upstream.now += upstream.source.positive_ttl - 1 |
| 524 | assert remote_who("remote-1") == ("7", ["staff"]) # inside the TTL: the cached answer |
| 525 | assert upstream.calls == calls |
| 526 | |
| 527 | upstream.now += 2 |
| 528 | assert remote_who("remote-1") == ("7", []) # past it: asked again |
| 529 | assert upstream.calls == calls + 1 |
| 530 | |
| 531 | |
| 532 | def test_a_remote_user_disabled_or_stripped_here_is_refused_on_the_next_request(data, upstream): |
| 533 | """The local registry still outranks the upstream, inside the cache TTL.""" |
| 534 | upstream.answers["Token remote-7"] = {"user_id": 7, "roles": ["staff"]} |
| 535 | add_user("7", []) |
| 536 | assert remote_who("remote-7") == (None, []) # a local user, not linked: refused |
| 537 | object_identity.set_user_identity_source("7", upstream.source.name, base_dir=data) |
| 538 | assert remote_who("remote-7") == ("7", ["staff"]) # local row roles do not cap upstream roles |
| 539 | object_identity._update_user("7", lambda u: replace(u, status="disabled"), base_dir=data, now=None) |
| 540 | assert remote_who("remote-7") == (None, []) |
| 541 | |
| 542 | |
| 543 | # ---- cost: the roles come from the parse the standing check already made ---- |
| 544 | |
| 545 | def test_resolving_a_session_does_not_re_read_users_tsv_when_unchanged(data, monkeypatch): |
| 546 | add_user("bob", ["staff"]) |
| 547 | session = new_session("bob") |
| 548 | age_identity_files(data) |
| 549 | assert object_identity.resolve_session_token(session, base_dir=data).roles == ("staff",) |
| 550 | parses = [] |
| 551 | real = object_identity._parse_user_standings |
| 552 | monkeypatch.setattr(object_identity, "_parse_user_standings", lambda path: parses.append(path) or real(path)) |
| 553 | for _ in range(5): |
| 554 | assert object_identity.resolve_session_token(session, base_dir=data).roles == ("staff",) |
| 555 | assert parses == [] |