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_password_change_ends_sessions.py · 17.4 KB · 390 lines
| 1 | """Changing or removing a password signs out whoever used the old one. |
| 2 | |
| 3 | Before: a reset by emailed link revoked the user's sessions, but an admin |
| 4 | setting a password (POST /identity/users/{id}/password, its /admin alias, |
| 5 | `set-password` on the CLI) or removing one (DELETE, `remove-password`) |
| 6 | revoked nothing, so whoever was signed in with the old password stayed |
| 7 | signed in. |
| 8 | |
| 9 | Now object_credentials.set_password / remove_password end the user's |
| 10 | sessions themselves, after the credential is written, so every path that |
| 11 | writes a password does it. One exception: a signed-in admin changing their |
| 12 | OWN password over the route keeps the session the request came with. API |
| 13 | keys are never touched (a key is a separate credential). If the password is |
| 14 | written but the sessions cannot be ended, the caller is told so -- a 500 |
| 15 | with code password_sessions_not_ended, a CLI exit of 1 -- never "ok". |
| 16 | |
| 17 | HTTP tests run with enforcement on and off: revocation is a write to |
| 18 | sessions.tsv and must not depend on enforcement. |
| 19 | """ |
| 20 | |
| 21 | import io |
| 22 | import json |
| 23 | |
| 24 | import pytest |
| 25 | |
| 26 | from test_object_server import TEST_ADMIN_TOKEN, request, save_permission_policy, write_records |
| 27 | from test_object_signup import _post, open_signup # noqa: F401 -- open_signup is a fixture |
| 28 | |
| 29 | import object_credentials |
| 30 | import object_identity |
| 31 | import object_identity_cli |
| 32 | import object_identity_sources |
| 33 | import object_server |
| 34 | import object_setup |
| 35 | import object_signup |
| 36 | |
| 37 | OLD = "the-old-password-1" |
| 38 | NEW = "the-new-password-2" |
| 39 | |
| 40 | POLICY = { |
| 41 | "access_mode": "role_based", |
| 42 | "admin_roles": ["admin"], |
| 43 | "rules": [ |
| 44 | {"effect": "allow", "principal": "registered", "actions": ["read"], |
| 45 | "collection": "notes", "reason": "every signed-in user reads notes"}, |
| 46 | ], |
| 47 | } |
| 48 | |
| 49 | |
| 50 | @pytest.fixture(params=[True, False], ids=["enforced", "unenforced"]) |
| 51 | def data(request, tmp_path, monkeypatch): |
| 52 | data = tmp_path / "data" |
| 53 | write_records(data, "notes", "id\ttitle\nn1\thello\n") |
| 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" if request.param else "false") |
| 58 | monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true") |
| 59 | monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true") |
| 60 | monkeypatch.setattr(object_server, "PASSWORD_LOGIN_FAILURE_DELAY_SECONDS", 0) |
| 61 | for name in (object_server.REQUIRE_KNOWN_IDENTITY_USERS_ENV, object_server.PERMISSION_TRUST_HEADERS_ENV, |
| 62 | object_identity_sources.IDENTITY_VERIFY_URL_ENV): |
| 63 | monkeypatch.delenv(name, raising=False) |
| 64 | return data |
| 65 | |
| 66 | |
| 67 | def call(method, path, body=None, token=None, admin=False): |
| 68 | sent = [] |
| 69 | if admin: |
| 70 | sent.append(("authorization", f"Token {TEST_ADMIN_TOKEN}")) |
| 71 | elif token: |
| 72 | sent.append(("authorization", f"Bearer {token}")) |
| 73 | raw = b"" |
| 74 | if body is not None: |
| 75 | raw = json.dumps(body).encode() |
| 76 | sent.append(("content-type", "application/json")) |
| 77 | status, _, payload = request(path, method=method, body=raw, headers=sent) |
| 78 | return status, payload |
| 79 | |
| 80 | |
| 81 | def add_user(user_id, roles=(), password=OLD, email=None): |
| 82 | body = {"user_id": user_id, "roles": list(roles)} |
| 83 | if email: |
| 84 | body["email"] = email |
| 85 | status, payload = call("POST", "/identity/users", body, admin=True) |
| 86 | assert status == 201, payload |
| 87 | if password: |
| 88 | status, payload = call("POST", f"/identity/users/{user_id}/password", {"password": password}, admin=True) |
| 89 | assert status == 200 and payload["sessions_revoked"] == 0, payload |
| 90 | |
| 91 | |
| 92 | def login(user_id, password): |
| 93 | """A password sign-in; the token, or None when refused.""" |
| 94 | status, payload = call("POST", "/identity/session", {"user_id": user_id, "password": password}) |
| 95 | if status == 201: |
| 96 | return payload["token"] |
| 97 | assert status == 401, (status, payload) |
| 98 | return None |
| 99 | |
| 100 | |
| 101 | def admin_session(user_id): |
| 102 | status, payload = call("POST", "/identity/sessions", {"user_id": user_id}, admin=True) |
| 103 | assert status == 201, payload |
| 104 | return payload["token"] |
| 105 | |
| 106 | |
| 107 | def new_key(user_id): |
| 108 | status, payload = call("POST", f"/identity/users/{user_id}/api-keys", {"name": "laptop"}, admin=True) |
| 109 | assert status == 200, payload |
| 110 | return payload["token"] |
| 111 | |
| 112 | |
| 113 | def who(token): |
| 114 | status, payload = call("GET", "/identity", token=token) |
| 115 | assert status == 200, payload |
| 116 | return payload["subject"]["user_id"] |
| 117 | |
| 118 | |
| 119 | def signed_in_as_bob(data): |
| 120 | """Two sessions (a password sign-in and an admin-minted one) and a key.""" |
| 121 | add_user("bob", ["staff"]) |
| 122 | sessions = [login("bob", OLD), admin_session("bob")] |
| 123 | key = new_key("bob") |
| 124 | assert all(who(token) == "bob" for token in [*sessions, key]) |
| 125 | return sessions, key |
| 126 | |
| 127 | |
| 128 | def assert_bob_signed_out_but_new_password_works(sessions, key, *, new=NEW): |
| 129 | for token in sessions: |
| 130 | assert who(token) is None |
| 131 | assert who(key) == "bob" # keys are not the password |
| 132 | assert login("bob", OLD) is None |
| 133 | if new is not None: |
| 134 | fresh = login("bob", new) |
| 135 | assert fresh and who(fresh) == "bob" |
| 136 | |
| 137 | |
| 138 | def live_sessions(data, user_id): |
| 139 | return [s for s in object_identity.list_sessions(base_dir=data) |
| 140 | if s["user_id"] == user_id and not s.get("revoked_at")] |
| 141 | |
| 142 | |
| 143 | # ---- the admin route -------------------------------------------------------- |
| 144 | |
| 145 | @pytest.mark.parametrize("prefix", ["/identity", "/admin/identity"]) |
| 146 | def test_an_admin_setting_a_password_ends_the_users_sessions(data, prefix): |
| 147 | sessions, key = signed_in_as_bob(data) |
| 148 | status, payload = call("POST", f"{prefix}/users/bob/password", {"password": NEW}, admin=True) |
| 149 | assert status == 200, payload |
| 150 | assert payload["operation"] == "replaced" and payload["sessions_revoked"] == 2 |
| 151 | assert_bob_signed_out_but_new_password_works(sessions, key) |
| 152 | |
| 153 | |
| 154 | def test_an_admin_removing_a_password_ends_the_users_sessions(data): |
| 155 | sessions, key = signed_in_as_bob(data) |
| 156 | status, payload = call("DELETE", "/identity/users/bob/password", admin=True) |
| 157 | assert status == 200 and payload["removed"] is True |
| 158 | assert_bob_signed_out_but_new_password_works(sessions, key, new=None) |
| 159 | assert live_sessions(data, "bob") == [] |
| 160 | |
| 161 | |
| 162 | def test_removing_a_password_that_was_not_there_ends_nothing(data): |
| 163 | add_user("bob", password=None) |
| 164 | session = admin_session("bob") |
| 165 | status, payload = call("DELETE", "/identity/users/bob/password", admin=True) |
| 166 | assert status == 200 and payload["removed"] is False |
| 167 | assert who(session) == "bob" |
| 168 | |
| 169 | |
| 170 | def test_an_admin_session_changing_another_users_password_ends_all_of_theirs(data): |
| 171 | add_user("ann", ["admin"]) |
| 172 | ann = login("ann", OLD) |
| 173 | sessions, key = signed_in_as_bob(data) |
| 174 | status, payload = call("POST", "/identity/users/bob/password", {"password": NEW}, token=ann) |
| 175 | assert status == 200, payload |
| 176 | assert payload["sessions_revoked"] == 2 |
| 177 | assert_bob_signed_out_but_new_password_works(sessions, key) |
| 178 | assert who(ann) == "ann" # the admin's own session is not touched |
| 179 | |
| 180 | |
| 181 | def test_changing_your_own_password_keeps_exactly_the_session_you_used(data): |
| 182 | add_user("ann", ["admin"]) |
| 183 | here, elsewhere, minted = login("ann", OLD), login("ann", OLD), admin_session("ann") |
| 184 | key = new_key("ann") |
| 185 | status, payload = call("POST", "/identity/users/ann/password", {"password": NEW}, token=here) |
| 186 | assert status == 200, payload |
| 187 | assert payload["sessions_revoked"] == 2 |
| 188 | assert who(here) == "ann" |
| 189 | assert who(elsewhere) is None and who(minted) is None |
| 190 | assert who(key) == "ann" |
| 191 | assert [s["session_id"] for s in live_sessions(data, "ann")] == [ |
| 192 | object_identity.resolve_session_token(here, base_dir=data).session_id |
| 193 | ] |
| 194 | assert login("ann", OLD) is None and who(login("ann", NEW)) == "ann" |
| 195 | |
| 196 | |
| 197 | def test_removing_your_own_password_keeps_exactly_the_session_you_used(data): |
| 198 | add_user("ann", ["admin"]) |
| 199 | here, elsewhere = login("ann", OLD), login("ann", OLD) |
| 200 | status, payload = call("DELETE", "/identity/users/ann/password", token=here) |
| 201 | assert status == 200 and payload["removed"] is True |
| 202 | assert who(here) == "ann" and who(elsewhere) is None |
| 203 | assert len(live_sessions(data, "ann")) == 1 |
| 204 | |
| 205 | |
| 206 | def test_the_admin_token_changing_an_admins_password_keeps_none_of_their_sessions(data): |
| 207 | """The token is not anyone's session, so there is nothing to keep.""" |
| 208 | add_user("ann", ["admin"]) |
| 209 | sessions = [login("ann", OLD), admin_session("ann")] |
| 210 | status, payload = call("POST", "/identity/users/ann/password", {"password": NEW}, admin=True) |
| 211 | assert status == 200 and payload["sessions_revoked"] == 2 |
| 212 | assert all(who(token) is None for token in sessions) |
| 213 | |
| 214 | |
| 215 | def test_setting_a_first_password_with_no_sessions_is_fine(data): |
| 216 | add_user("bob", password=None) |
| 217 | status, payload = call("POST", "/identity/users/bob/password", {"password": NEW}, admin=True) |
| 218 | assert status == 200 and payload["operation"] == "created" and payload["sessions_revoked"] == 0 |
| 219 | assert who(login("bob", NEW)) == "bob" |
| 220 | |
| 221 | |
| 222 | def test_other_users_sessions_are_not_touched(data): |
| 223 | add_user("carol") |
| 224 | carol = login("carol", OLD) |
| 225 | signed_in_as_bob(data) |
| 226 | assert call("POST", "/identity/users/bob/password", {"password": NEW}, admin=True)[0] == 200 |
| 227 | assert who(carol) == "carol" |
| 228 | |
| 229 | |
| 230 | def test_when_the_sessions_cannot_be_ended_the_route_says_so(data, monkeypatch): |
| 231 | sessions, key = signed_in_as_bob(data) |
| 232 | |
| 233 | def broken(*args, **kwargs): |
| 234 | raise OSError("disk full") |
| 235 | |
| 236 | monkeypatch.setattr(object_identity, "revoke_user_sessions", broken) |
| 237 | for method, body in (("POST", {"password": NEW}), ("DELETE", None)): |
| 238 | status, payload = call(method, "/identity/users/bob/password", body, admin=True) |
| 239 | assert status == 500, payload |
| 240 | assert payload["status"] == "error" |
| 241 | assert payload["code"] == "password_sessions_not_ended" |
| 242 | assert payload["password_changed"] is True |
| 243 | assert "could not be ended" in payload["error"] and "disk full" in payload["error"] |
| 244 | |
| 245 | |
| 246 | def test_a_real_unwritable_sessions_file_is_reported_and_a_retry_finishes_it(data): |
| 247 | sessions, key = signed_in_as_bob(data) |
| 248 | path = object_identity.sessions_path(data) |
| 249 | saved = path.read_bytes() |
| 250 | path.unlink() |
| 251 | path.mkdir() # reading it now fails for real |
| 252 | try: |
| 253 | status, payload = call("POST", "/identity/users/bob/password", {"password": NEW}, admin=True) |
| 254 | assert status == 500 and payload["code"] == "password_sessions_not_ended" |
| 255 | assert object_credentials.verify_password("bob", NEW, base_dir=data) |
| 256 | finally: |
| 257 | path.rmdir() |
| 258 | path.write_bytes(saved) |
| 259 | status, payload = call("POST", "/identity/users/bob/password", {"password": NEW}, admin=True) |
| 260 | assert status == 200 and payload["sessions_revoked"] == 2 |
| 261 | assert_bob_signed_out_but_new_password_works(sessions, key) |
| 262 | |
| 263 | |
| 264 | # ---- the CLI ---------------------------------------------------------------- |
| 265 | |
| 266 | def run_cli(data, *args, stdin=None, monkeypatch=None): |
| 267 | if stdin is not None: |
| 268 | monkeypatch.setattr("sys.stdin", io.StringIO(stdin + "\n")) |
| 269 | return object_identity_cli.main(["--data-dir", str(data), *args]) |
| 270 | |
| 271 | |
| 272 | def test_cli_set_password_ends_the_users_sessions(data, monkeypatch, capsys): |
| 273 | sessions, key = signed_in_as_bob(data) |
| 274 | assert run_cli(data, "set-password", "--user-id", "bob", "--password-stdin", |
| 275 | stdin=NEW, monkeypatch=monkeypatch) == 0 |
| 276 | assert "2 session(s) signed out" in capsys.readouterr().out |
| 277 | assert_bob_signed_out_but_new_password_works(sessions, key) |
| 278 | |
| 279 | |
| 280 | def test_cli_remove_password_ends_the_users_sessions(data, capsys): |
| 281 | sessions, key = signed_in_as_bob(data) |
| 282 | assert run_cli(data, "remove-password", "--user-id", "bob") == 0 |
| 283 | assert "signed out" in capsys.readouterr().out |
| 284 | assert_bob_signed_out_but_new_password_works(sessions, key, new=None) |
| 285 | |
| 286 | |
| 287 | def test_cli_reports_sessions_it_could_not_end(data, monkeypatch, capsys): |
| 288 | signed_in_as_bob(data) |
| 289 | monkeypatch.setattr(object_identity, "revoke_user_sessions", |
| 290 | lambda *a, **k: (_ for _ in ()).throw(OSError("disk full"))) |
| 291 | assert run_cli(data, "set-password", "--user-id", "bob", "--password-stdin", |
| 292 | stdin=NEW, monkeypatch=monkeypatch) == 1 |
| 293 | assert "could not be ended" in capsys.readouterr().err |
| 294 | |
| 295 | |
| 296 | def test_cli_create_superuser_sets_a_first_password(data, monkeypatch): |
| 297 | assert run_cli(data, "create-superuser", "--user-id", "root", "--password-stdin", |
| 298 | stdin=NEW, monkeypatch=monkeypatch) == 0 |
| 299 | assert who(login("root", NEW)) == "root" |
| 300 | |
| 301 | |
| 302 | # ---- reset link, signup, setup --------------------------------------------- |
| 303 | |
| 304 | def test_a_reset_link_still_ends_every_session(data): |
| 305 | add_user("bob", ["staff"], email="bob@example.org") |
| 306 | sessions, key = [login("bob", OLD), admin_session("bob")], new_key("bob") |
| 307 | link = object_signup.issue_token(object_signup.PASSWORD_RESET, "bob", "bob@example.org", base_dir=data) |
| 308 | assert object_signup.reset_password(link, NEW, base_dir=data) is not None |
| 309 | assert_bob_signed_out_but_new_password_works(sessions, key) |
| 310 | |
| 311 | |
| 312 | @pytest.mark.parametrize("enforce", [True, False], ids=["enforced", "unenforced"]) |
| 313 | def test_a_reset_link_whose_sessions_cannot_be_ended_says_so(open_signup, monkeypatch, enforce): # noqa: F811 |
| 314 | data_dir = open_signup |
| 315 | monkeypatch.setattr(object_server, "_permission_enforcement_enabled", lambda: enforce) |
| 316 | user = object_signup.register("ann@example.org", base_dir=data_dir)["user"] |
| 317 | object_credentials.set_password(user["user_id"], OLD, base_dir=data_dir) |
| 318 | object_identity.set_user_status(user["user_id"], "active", base_dir=data_dir) |
| 319 | token = object_signup.issue_token(object_signup.PASSWORD_RESET, user["user_id"], user["email"], base_dir=data_dir) |
| 320 | monkeypatch.setattr(object_identity, "revoke_user_sessions", |
| 321 | lambda *a, **k: (_ for _ in ()).throw(OSError("disk full"))) |
| 322 | status, headers, body = _post("/reset/confirm", {"token": token, "password": NEW}) |
| 323 | assert status == 500 |
| 324 | assert b"couldn't sign you out of your other sessions" in body |
| 325 | assert b"location" not in headers |
| 326 | |
| 327 | |
| 328 | def test_signup_confirmation_sets_a_first_password(tmp_path): |
| 329 | user = object_signup.register("ann@example.org", base_dir=tmp_path)["user"] |
| 330 | token = object_signup.issue_token(object_signup.VERIFY_EMAIL, user["user_id"], user["email"], base_dir=tmp_path) |
| 331 | confirmed = object_signup.confirm_signup(token, NEW, "Ann", base_dir=tmp_path) |
| 332 | assert confirmed["status"] == "active" |
| 333 | assert object_credentials.verify_password(user["user_id"], NEW, base_dir=tmp_path) |
| 334 | |
| 335 | |
| 336 | def test_first_time_setup_sets_a_first_password(tmp_path): |
| 337 | code = object_setup.new_code() |
| 338 | object_setup.code_path(tmp_path).parent.mkdir(parents=True, exist_ok=True) |
| 339 | object_setup.code_path(tmp_path).write_text(object_setup.code_hash(object_setup.normalize_code(code)) + "\n") |
| 340 | assert object_setup.waiting(tmp_path) |
| 341 | user = object_setup.complete(code, "root@example.org", NEW, "Root", base_dir=tmp_path) |
| 342 | assert user is not None |
| 343 | assert object_credentials.verify_password(user["user_id"], NEW, base_dir=tmp_path) |
| 344 | |
| 345 | |
| 346 | # ---- the library function itself ------------------------------------------- |
| 347 | |
| 348 | def test_set_password_keeps_only_the_named_session_of_that_user(tmp_path): |
| 349 | object_credentials.set_password("u1", OLD, base_dir=tmp_path) |
| 350 | keep = object_identity.create_session({"user_id": "u1"}, base_dir=tmp_path) |
| 351 | drop = object_identity.create_session({"user_id": "u1"}, base_dir=tmp_path) |
| 352 | other = object_identity.create_session({"user_id": "u2"}, base_dir=tmp_path) |
| 353 | result = object_credentials.set_password( |
| 354 | "u1", NEW, base_dir=tmp_path, keep_session_id=keep["session"]["session_id"]) |
| 355 | assert result["sessions_revoked"] == 1 |
| 356 | assert object_identity.resolve_session_token(keep["token"], base_dir=tmp_path) is not None |
| 357 | assert object_identity.resolve_session_token(drop["token"], base_dir=tmp_path) is None |
| 358 | assert object_identity.resolve_session_token(other["token"], base_dir=tmp_path) is not None |
| 359 | |
| 360 | # keeping another user's session id does not spare anything of u1's |
| 361 | again = object_identity.create_session({"user_id": "u1"}, base_dir=tmp_path) |
| 362 | object_credentials.set_password("u1", OLD, base_dir=tmp_path, keep_session_id=other["session"]["session_id"]) |
| 363 | assert object_identity.resolve_session_token(again["token"], base_dir=tmp_path) is None |
| 364 | assert object_identity.resolve_session_token(keep["token"], base_dir=tmp_path) is None |
| 365 | |
| 366 | |
| 367 | def test_a_failed_revocation_is_not_an_oserror_or_valueerror(tmp_path, monkeypatch): |
| 368 | """Callers read OSError/ValueError as "nothing changed"; here the password did.""" |
| 369 | monkeypatch.setattr(object_identity, "revoke_user_sessions", |
| 370 | lambda *a, **k: (_ for _ in ()).throw(OSError("disk full"))) |
| 371 | with pytest.raises(object_credentials.SessionRevocationError) as caught: |
| 372 | object_credentials.set_password("u1", NEW, base_dir=tmp_path) |
| 373 | assert not isinstance(caught.value, (OSError, ValueError)) |
| 374 | assert object_credentials.verify_password("u1", NEW, base_dir=tmp_path) |
| 375 | |
| 376 | |
| 377 | def test_changing_your_own_password_from_the_browser_keeps_the_cookie_session(data): |
| 378 | """The same exception when the session comes in the cookie, as from a page.""" |
| 379 | add_user("ann", ["admin"]) |
| 380 | here, elsewhere = login("ann", OLD), login("ann", OLD) |
| 381 | status, _, payload = request( |
| 382 | "/identity/users/ann/password", |
| 383 | method="POST", |
| 384 | body=json.dumps({"password": NEW}).encode(), |
| 385 | headers=[("cookie", f"{object_server.SESSION_COOKIE_NAME}={here}"), |
| 386 | ("content-type", "application/json")], |
| 387 | ) |
| 388 | assert status == 200, payload |
| 389 | assert payload["sessions_revoked"] == 1 |
| 390 | assert who(here) == "ann" and who(elsewhere) is None |