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_user_offboarding.py · 18.0 KB · 408 lines
| 1 | """Taking access away: a non-active user fails authentication on every path, |
| 2 | and offboarding is one admin call. |
| 3 | |
| 4 | Why it matters: a simulated company disabled a departing employee |
| 5 | (`object_identity.set_user_status(..., "disabled")`) and found that their |
| 6 | existing API key still answered 200, that the admin route would mint them a |
| 7 | NEW key that also worked, and that their sessions kept working -- status was |
| 8 | checked only when a session was minted, never when a credential was |
| 9 | presented. There was also no HTTP route to change a user's roles or status, so |
| 10 | the tester edited users.tsv in-process. Everything here goes through the real |
| 11 | ASGI app with permission enforcement on. |
| 12 | """ |
| 13 | |
| 14 | import json |
| 15 | import os |
| 16 | import subprocess |
| 17 | import sys |
| 18 | import textwrap |
| 19 | import time |
| 20 | from pathlib import Path |
| 21 | |
| 22 | import pytest |
| 23 | |
| 24 | from test_object_server import TEST_ADMIN_TOKEN, request, save_permission_policy, write_records |
| 25 | |
| 26 | import object_api_keys |
| 27 | import object_identity |
| 28 | import object_ops_log |
| 29 | import object_server |
| 30 | |
| 31 | REPO = Path(__file__).resolve().parents[1] |
| 32 | |
| 33 | POLICY = { |
| 34 | "access_mode": "role_based", |
| 35 | "admin_roles": ["admin"], |
| 36 | "rules": [ |
| 37 | {"effect": "allow", "principal": "registered", "actions": ["read"], |
| 38 | "collection": "notes", "reason": "every signed-in user reads notes"}, |
| 39 | {"effect": "allow", "principal": "role:staff", "actions": ["create"], |
| 40 | "collection": "notes", "reason": "staff write notes"}, |
| 41 | {"effect": "deny", "principal": "owner_fallback", "actions": ["update", "delete"], |
| 42 | "collection": "notes", "reason": "notes are not edited in these tests"}, |
| 43 | ], |
| 44 | } |
| 45 | |
| 46 | |
| 47 | @pytest.fixture |
| 48 | def data(tmp_path, monkeypatch): |
| 49 | data = tmp_path / "data" |
| 50 | write_records(data, "notes", "id\ttitle\nn1\thello\n") |
| 51 | schema = data / "schemas" / "notes.json" |
| 52 | schema.parent.mkdir(parents=True, exist_ok=True) |
| 53 | schema.write_text(json.dumps({"fields": [{"name": "id"}, {"name": "title"}]})) |
| 54 | save_permission_policy(data, POLICY) |
| 55 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data)) |
| 56 | monkeypatch.setenv(object_server.ADMIN_TOKEN_ENV, TEST_ADMIN_TOKEN) |
| 57 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 58 | monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true") |
| 59 | for name in (object_server.REQUIRE_KNOWN_IDENTITY_USERS_ENV, object_server.SESSION_ADMIN_GATES_ENV, |
| 60 | object_server.PERMISSION_TRUST_HEADERS_ENV): |
| 61 | monkeypatch.delenv(name, raising=False) |
| 62 | return data |
| 63 | |
| 64 | |
| 65 | def call(method, path, body=None, token=None, admin=False, headers=()): |
| 66 | sent = list(headers) |
| 67 | if admin: |
| 68 | sent.append(("authorization", f"Token {TEST_ADMIN_TOKEN}")) |
| 69 | elif token: |
| 70 | sent.append(("authorization", f"Bearer {token}")) |
| 71 | raw = b"" |
| 72 | if body is not None: |
| 73 | raw = json.dumps(body).encode() |
| 74 | sent.append(("content-type", "application/json")) |
| 75 | status, _, payload = request(path, method=method, body=raw, headers=sent) |
| 76 | return status, payload |
| 77 | |
| 78 | |
| 79 | def add_user(user_id, roles=()): |
| 80 | status, payload = call("POST", "/identity/users", {"user_id": user_id, "roles": list(roles)}, admin=True) |
| 81 | assert status == 201, payload |
| 82 | |
| 83 | |
| 84 | def new_key(user_id): |
| 85 | status, payload = call("POST", f"/identity/users/{user_id}/api-keys", {"name": "laptop"}, admin=True) |
| 86 | assert status == 200, payload |
| 87 | return payload["token"] |
| 88 | |
| 89 | |
| 90 | def new_session(user_id): |
| 91 | status, payload = call("POST", "/identity/sessions", {"user_id": user_id}, admin=True) |
| 92 | assert status == 201, payload |
| 93 | return payload["token"] |
| 94 | |
| 95 | |
| 96 | def who(token): |
| 97 | status, payload = call("GET", "/identity", token=token) |
| 98 | assert status == 200 |
| 99 | return payload["subject"]["user_id"], payload["auth"]["method"] |
| 100 | |
| 101 | |
| 102 | def reads_notes(token): |
| 103 | status, _ = call("GET", "/collections/notes/records", token=token) |
| 104 | return status == 200 |
| 105 | |
| 106 | |
| 107 | def age_identity_files(data): |
| 108 | """Push identity files' mtimes into the past so the stat caches keep their |
| 109 | parse (a file younger than the racy window is never cached), making the |
| 110 | invalidation tests below exercise a warm cache, not a cold one.""" |
| 111 | old = time.time() - 600 |
| 112 | for path in (data / "identity").glob("*.tsv"): |
| 113 | os.utime(path, (old, old)) |
| 114 | |
| 115 | |
| 116 | # ---- every credential path refuses a non-active user --------------------- |
| 117 | |
| 118 | def test_disabling_a_user_stops_their_existing_api_key_and_session(data): |
| 119 | add_user("bob", ["staff"]) |
| 120 | key, session = new_key("bob"), new_session("bob") |
| 121 | assert reads_notes(key) and reads_notes(session) |
| 122 | |
| 123 | status, result = call("PUT", "/identity/users/bob/status", {"status": "disabled"}, admin=True) |
| 124 | assert status == 200, result |
| 125 | assert result["user"]["status"] == "disabled" |
| 126 | assert result["sessions_revoked"] == 1 and result["api_keys_revoked"] == 1 |
| 127 | |
| 128 | for token in (key, session): |
| 129 | assert who(token) == (None, "anonymous") |
| 130 | assert not reads_notes(token) |
| 131 | status, _ = call("POST", "/collections/notes/records", {"title": "x"}, token=token) |
| 132 | assert status in (401, 403) |
| 133 | |
| 134 | |
| 135 | def test_a_disable_written_by_another_process_stops_credentials_on_the_next_request(data): |
| 136 | """The disable is checked at resolution, not only revoked: a status edited |
| 137 | into users.tsv by another process (no revocation, no in-process cache |
| 138 | drop) must lock the user out on the very next request, warm caches and all. |
| 139 | "paused" is a status this code does not know -- unknown means not active.""" |
| 140 | add_user("bob", ["staff"]) |
| 141 | key, session = new_key("bob"), new_session("bob") |
| 142 | age_identity_files(data) |
| 143 | assert reads_notes(key) and reads_notes(session) # caches now warm |
| 144 | |
| 145 | script = textwrap.dedent( |
| 146 | """ |
| 147 | import sys |
| 148 | from pathlib import Path |
| 149 | path = Path(sys.argv[1]) |
| 150 | text = path.read_text() |
| 151 | assert "\\tactive\\t" in text |
| 152 | path.write_text(text.replace("\\tactive\\t", "\\tpaused\\t")) # same size, in place |
| 153 | """ |
| 154 | ) |
| 155 | users = data / "identity" / "users.tsv" |
| 156 | subprocess.run([sys.executable, "-c", script, str(users)], check=True) |
| 157 | |
| 158 | assert who(key) == (None, "anonymous") |
| 159 | assert who(session) == (None, "anonymous") |
| 160 | status, user = call("GET", "/identity/users/bob", admin=True) |
| 161 | assert status == 200 and user["user"]["status"] == "paused" # listed, not vanished |
| 162 | |
| 163 | # and the operator can put it right through the API |
| 164 | status, _ = call("PUT", "/identity/users/bob/status", {"status": "active"}, admin=True) |
| 165 | assert status == 200 |
| 166 | |
| 167 | |
| 168 | def test_a_session_revoked_by_another_process_stops_on_the_next_request(data): |
| 169 | add_user("bob") |
| 170 | session = new_session("bob") |
| 171 | age_identity_files(data) |
| 172 | assert who(session) == ("bob", "session_token") |
| 173 | script = textwrap.dedent( |
| 174 | """ |
| 175 | import sys |
| 176 | sys.path.insert(0, sys.argv[2]) |
| 177 | import object_identity |
| 178 | print(object_identity.revoke_user_sessions("bob", base_dir=sys.argv[1])) |
| 179 | """ |
| 180 | ) |
| 181 | out = subprocess.run([sys.executable, "-c", script, str(data), str(REPO)], |
| 182 | check=True, capture_output=True, text=True) |
| 183 | assert out.stdout.strip() == "1" |
| 184 | assert who(session) == (None, "anonymous") |
| 185 | |
| 186 | |
| 187 | def test_a_user_row_that_does_not_parse_fails_closed(data): |
| 188 | """A broken row used to vanish from _read_users, and a vanished user reads |
| 189 | as "unknown", which ad hoc sessions treat as allowed.""" |
| 190 | add_user("bob", ["staff"]) |
| 191 | key, session = new_key("bob"), new_session("bob") |
| 192 | users = data / "identity" / "users.tsv" |
| 193 | lines = users.read_text().splitlines() |
| 194 | header = lines[0].split("\t") |
| 195 | row = lines[1].split("\t") |
| 196 | row[header.index("created_at")] = "not-a-timestamp" |
| 197 | users.write_text("\n".join([lines[0], "\t".join(row)]) + "\n") |
| 198 | |
| 199 | assert who(key) == (None, "anonymous") |
| 200 | assert who(session) == (None, "anonymous") |
| 201 | status, payload = call("POST", "/identity/sessions", {"user_id": "bob"}, admin=True) |
| 202 | assert status == 400 and "not active" in payload["error"] |
| 203 | status, payload = call("POST", "/identity/users/bob/api-keys", {"name": "x"}, admin=True) |
| 204 | assert status == 400 and "not active" in payload["error"] |
| 205 | |
| 206 | |
| 207 | def test_a_non_active_user_is_issued_no_new_key_or_session(data): |
| 208 | add_user("bob") |
| 209 | for status_value in ("disabled", "pending"): |
| 210 | call("PUT", "/identity/users/bob/status", {"status": status_value}, admin=True) |
| 211 | status, payload = call("POST", "/identity/users/bob/api-keys", {"name": "new"}, admin=True) |
| 212 | assert status == 400 and "not active" in payload["error"] |
| 213 | assert "token" not in payload |
| 214 | status, payload = call("POST", "/identity/sessions", {"user_id": "bob"}, admin=True) |
| 215 | assert status == 400 and "not active" in payload["error"] |
| 216 | assert object_api_keys.list_api_keys("bob", base_dir=data) == [] |
| 217 | |
| 218 | |
| 219 | def test_re_enabling_restores_the_person_not_their_old_credentials(data): |
| 220 | add_user("bob", ["staff"]) |
| 221 | key, session = new_key("bob"), new_session("bob") |
| 222 | call("PUT", "/identity/users/bob/status", {"status": "disabled"}, admin=True) |
| 223 | status, result = call("PUT", "/identity/users/bob/status", {"status": "active"}, admin=True) |
| 224 | assert status == 200 and result["sessions_revoked"] == 0 and result["api_keys_revoked"] == 0 |
| 225 | |
| 226 | assert who(key) == (None, "anonymous") |
| 227 | assert who(session) == (None, "anonymous") |
| 228 | assert who(new_key("bob")) == ("bob", "api_key") |
| 229 | |
| 230 | |
| 231 | def test_trusted_headers_cannot_assert_a_disabled_user(data, monkeypatch): |
| 232 | monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true") |
| 233 | add_user("bob", ["staff"]) |
| 234 | asserted = [("x-dbbasic-user-id", "bob")] |
| 235 | status, payload = call("GET", "/identity", headers=asserted) |
| 236 | assert payload["subject"]["user_id"] == "bob" |
| 237 | call("PUT", "/identity/users/bob/status", {"status": "disabled"}, admin=True) |
| 238 | status, payload = call("GET", "/identity", headers=asserted) |
| 239 | assert payload["subject"]["user_id"] is None and payload["auth"]["method"] == "anonymous" |
| 240 | |
| 241 | |
| 242 | def test_required_known_users_refuses_credentials_for_a_user_with_no_row(data, monkeypatch): |
| 243 | """Ad hoc credentials for unregistered ids stay allowed by default (gateway |
| 244 | sessions are documented); DBBASIC_REQUIRE_KNOWN_IDENTITY_USERS now refuses |
| 245 | them at presentation too, so deleting a row cannot leave its keys alive.""" |
| 246 | _meta, key = object_api_keys.create_api_key("ghost", "x", base_dir=data) |
| 247 | session = new_session("ghost") |
| 248 | assert who(key) == ("ghost", "api_key") and who(session) == ("ghost", "session_token") |
| 249 | |
| 250 | monkeypatch.setenv(object_server.REQUIRE_KNOWN_IDENTITY_USERS_ENV, "true") |
| 251 | assert who(key) == (None, "anonymous") |
| 252 | assert who(session) == (None, "anonymous") |
| 253 | status, _ = call("POST", "/identity/users/ghost/api-keys", {"name": "y"}, admin=True) |
| 254 | assert status == 404 |
| 255 | |
| 256 | |
| 257 | # ---- offboarding and the admin user routes -------------------------------- |
| 258 | |
| 259 | def test_offboarding_disables_revokes_everything_and_clears_roles_in_one_call(data): |
| 260 | add_user("bob", ["staff", "manager"]) |
| 261 | keys = [new_key("bob"), new_key("bob")] |
| 262 | sessions = [new_session("bob"), new_session("bob")] |
| 263 | add_user("carol", ["staff"]) |
| 264 | carol = new_key("carol") |
| 265 | |
| 266 | status, result = call("POST", "/identity/users/bob/offboard", |
| 267 | {"clear_roles": True, "reason": "left the company"}, admin=True) |
| 268 | assert status == 200, result |
| 269 | assert result["status"] == "ok" |
| 270 | assert result["user"]["user_id"] == "bob" |
| 271 | assert result["user"]["status"] == "disabled" and result["user"]["roles"] == [] |
| 272 | assert result["sessions_revoked"] == 2 and result["api_keys_revoked"] == 2 |
| 273 | assert result["roles_cleared"] == ["staff", "manager"] |
| 274 | |
| 275 | for token in keys + sessions: |
| 276 | assert who(token) == (None, "anonymous") |
| 277 | assert object_api_keys.list_api_keys("bob", base_dir=data) == [] |
| 278 | assert all(s["revoked_at"] for s in object_identity.list_sessions(base_dir=data) if s["user_id"] == "bob") |
| 279 | assert who(carol) == ("carol", "api_key") # nobody else is touched |
| 280 | |
| 281 | [line] = object_ops_log.read_events(base_dir=data, kind="auth", event="user_offboarded") |
| 282 | assert line["identifier"] == "bob" and line["auth_method"] == "admin_token" |
| 283 | assert "roles_cleared=staff,manager" in line["label"] |
| 284 | assert "sessions_revoked=2 api_keys_revoked=2" in line["label"] |
| 285 | assert "reason=left the company" in line["label"] |
| 286 | |
| 287 | # idempotent: a second offboard succeeds and revokes nothing |
| 288 | status, again = call("POST", "/identity/users/bob/offboard", admin=True) |
| 289 | assert status == 200 and again["sessions_revoked"] == 0 and again["api_keys_revoked"] == 0 |
| 290 | |
| 291 | |
| 292 | def test_offboarding_keeps_roles_unless_asked(data): |
| 293 | add_user("bob", ["staff"]) |
| 294 | status, result = call("POST", "/identity/users/bob/offboard", {}, admin=True) |
| 295 | assert status == 200 and result["user"]["roles"] == ["staff"] and result["roles_cleared"] == [] |
| 296 | |
| 297 | |
| 298 | def test_removing_a_role_revokes_the_sessions_that_carry_it(data): |
| 299 | """Sessions stamp roles at mint; API keys read them live. A session minted |
| 300 | while bob was staff would stay staff after the role was removed.""" |
| 301 | add_user("bob", ["staff"]) |
| 302 | key, session = new_key("bob"), new_session("bob") |
| 303 | status, _ = call("POST", "/collections/notes/records", {"title": "a"}, token=session) |
| 304 | assert status == 201 |
| 305 | |
| 306 | # granting a role signs nobody out |
| 307 | status, result = call("PUT", "/identity/users/bob/roles", {"roles": ["staff", "member"]}, admin=True) |
| 308 | assert status == 200 and result["sessions_revoked"] == 0 |
| 309 | assert who(session) == ("bob", "session_token") |
| 310 | |
| 311 | status, result = call("PUT", "/identity/users/bob/roles", {"roles": ["member"]}, admin=True) |
| 312 | assert status == 200 and result["user"]["roles"] == ["member"] and result["sessions_revoked"] == 1 |
| 313 | assert who(session) == (None, "anonymous") |
| 314 | status, _ = call("POST", "/collections/notes/records", {"title": "b"}, token=key) |
| 315 | assert status == 403 # the key is still bob, without staff |
| 316 | assert who(key) == ("bob", "api_key") |
| 317 | [line] = object_ops_log.read_events(base_dir=data, kind="auth", event="user_roles_set", limit=1) |
| 318 | assert line["identifier"] == "bob" and "roles=member" in line["label"] |
| 319 | |
| 320 | |
| 321 | @pytest.mark.parametrize( |
| 322 | "path,body", |
| 323 | [ |
| 324 | ("/identity/users/bob/status", {"status": "disabled"}), |
| 325 | ("/identity/users/bob/roles", {"roles": ["admin"]}), |
| 326 | ("/identity/users/bob/offboard", {"clear_roles": True}), |
| 327 | ], |
| 328 | ) |
| 329 | def test_the_admin_user_routes_refuse_everyone_but_an_admin(data, monkeypatch, path, body): |
| 330 | add_user("bob", ["staff"]) |
| 331 | add_user("mallory", ["staff"]) |
| 332 | bob_key, bob_session = new_key("bob"), new_session("bob") |
| 333 | mallory_key, mallory_session = new_key("mallory"), new_session("mallory") |
| 334 | before = object_identity.get_user("bob", base_dir=data) |
| 335 | |
| 336 | attempts = [ |
| 337 | (None, False), (bob_key, False), (bob_session, False), |
| 338 | (mallory_key, False), (mallory_session, False), ("wrong-admin-token", False), |
| 339 | ] |
| 340 | for token, _ in attempts: |
| 341 | status, payload = call("PUT", path, body, token=token) |
| 342 | assert status == 401, (token, payload) |
| 343 | # an ordinary session stays refused with session admin gates on, too |
| 344 | monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true") |
| 345 | status, _ = call("PUT", path, body, token=mallory_session) |
| 346 | assert status == 401 |
| 347 | # no admin token configured and no session gates: closed, not open |
| 348 | monkeypatch.delenv(object_server.SESSION_ADMIN_GATES_ENV) |
| 349 | monkeypatch.delenv(object_server.ADMIN_TOKEN_ENV) |
| 350 | status, _ = call("PUT", path, body, token=bob_session) |
| 351 | assert status == 403 |
| 352 | |
| 353 | assert object_identity.get_user("bob", base_dir=data) == before |
| 354 | assert who(bob_key) == ("bob", "api_key") |
| 355 | assert len(object_api_keys.list_api_keys("bob", base_dir=data)) == 1 |
| 356 | assert not object_ops_log.read_events(base_dir=data, kind="auth", event="user_offboarded") |
| 357 | |
| 358 | |
| 359 | def test_an_admin_session_can_offboard_and_is_named_in_the_audit_line(data, monkeypatch): |
| 360 | monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true") |
| 361 | add_user("ada", ["admin"]) |
| 362 | add_user("bob", ["staff"]) |
| 363 | ada = new_session("ada") |
| 364 | status, result = call("POST", "/identity/users/bob/offboard", {}, token=ada) |
| 365 | assert status == 200, result |
| 366 | [line] = object_ops_log.read_events(base_dir=data, kind="auth", event="user_offboarded") |
| 367 | assert line["user_id"] == "ada" and line["auth_method"] == "admin_session" |
| 368 | |
| 369 | # and an admin who is disabled loses the admin gate with everything else |
| 370 | object_identity.set_user_status("ada", "disabled", base_dir=data) |
| 371 | status, _ = call("POST", "/identity/users/bob/offboard", {}, token=ada) |
| 372 | assert status == 401 |
| 373 | |
| 374 | |
| 375 | @pytest.mark.parametrize( |
| 376 | "method,path,body,expected", |
| 377 | [ |
| 378 | ("PUT", "/identity/users/bob/status", {}, 400), |
| 379 | ("PUT", "/identity/users/bob/status", {"status": "suspended"}, 400), |
| 380 | ("PUT", "/identity/users/bob/status", {"status": "disabled", "roles": []}, 400), |
| 381 | ("PUT", "/identity/users/bob/roles", {}, 400), |
| 382 | ("PUT", "/identity/users/bob/roles", {"roles": "admin"}, 400), |
| 383 | ("PUT", "/identity/users/bob/roles", {"role": ["admin"]}, 400), |
| 384 | ("POST", "/identity/users/bob/offboard", {"clear_roles": "yes"}, 400), |
| 385 | ("POST", "/identity/users/bob/offboard", {"revoke": False}, 400), |
| 386 | ("GET", "/identity/users/bob/offboard", None, 405), |
| 387 | ("DELETE", "/identity/users/bob/status", None, 405), |
| 388 | ("PUT", "/identity/users/nobody/status", {"status": "disabled"}, 404), |
| 389 | ("POST", "/identity/users/nobody/offboard", {}, 404), |
| 390 | ], |
| 391 | ) |
| 392 | def test_the_admin_user_routes_refuse_bad_requests_without_changing_anything(data, method, path, body, expected): |
| 393 | add_user("bob", ["staff"]) |
| 394 | key = new_key("bob") |
| 395 | status, payload = call(method, path, body, admin=True) |
| 396 | assert status == expected, payload |
| 397 | assert object_identity.get_user("bob", base_dir=data)["status"] == "active" |
| 398 | assert object_identity.get_user("bob", base_dir=data)["roles"] == ["staff"] |
| 399 | assert who(key) == ("bob", "api_key") |
| 400 | |
| 401 | |
| 402 | def test_set_user_status_in_process_also_revokes(data): |
| 403 | """The in-process call the tester used is the same operation as the route.""" |
| 404 | add_user("bob") |
| 405 | key, session = new_key("bob"), new_session("bob") |
| 406 | object_identity.set_user_status("bob", "disabled", base_dir=data) |
| 407 | object_identity.set_user_status("bob", "active", base_dir=data) |
| 408 | assert who(key) == (None, "anonymous") and who(session) == (None, "anonymous") |