diff --git a/backend/endpoints/user.py b/backend/endpoints/user.py index 4af58ff13..25fb86583 100644 --- a/backend/endpoints/user.py +++ b/backend/endpoints/user.py @@ -479,20 +479,23 @@ async def update_user( "hashed_password" ) - # Ahead of the write: an unreachable Redis then aborts the change - # rather than committing it with the account's sessions left live. + # Once before the write, so an unreachable Redis aborts rather than + # commits, and once after, to catch a login the old password was still + # good for while the write was in progress. if creds_updated: await RedisSessionMiddleware.clear_user_sessions(previous_username) db_user_handler.update_user(id, cleaned_data) + if creds_updated: + await RedisSessionMiddleware.clear_user_sessions(previous_username) + if request.user.id == id: + request.session.clear() + # A role change alters the user's effective permissions; tell their UI. if "role" in cleaned_data: await emit_permissions_changed(id) - if creds_updated and request.user.id == id: - request.session.clear() - db_user = db_user_handler.get_user(id) if not db_user: msg = f"Username with id {id} not found" diff --git a/backend/tests/endpoints/test_identity.py b/backend/tests/endpoints/test_identity.py index 7ce724f9a..bb6ec633b 100644 --- a/backend/tests/endpoints/test_identity.py +++ b/backend/tests/endpoints/test_identity.py @@ -307,8 +307,7 @@ async def test_admin_password_reset_invalidates_the_target_user_sessions( async def test_a_failed_revocation_leaves_the_password_unchanged( client, access_token: str, editor_user: User ): - """Revoking before the write keeps the two from disagreeing: a password - that changed while its sessions survived would outlive the reset.""" + """An unreachable Redis aborts the change instead of committing it.""" original_hash = editor_user.hashed_password with mock.patch.object( @@ -328,6 +327,40 @@ async def test_a_failed_revocation_leaves_the_password_unchanged( assert db_user.hashed_password == original_hash +@pytest.mark.asyncio +async def test_sessions_are_revoked_on_both_sides_of_the_write( + client, access_token: str, editor_user: User +): + """The second pass catches a login the old password was still good for.""" + calls: list[str] = [] + real_update = DBUsersHandler.update_user + + def record_update(self, id, data, *args, **kwargs): + # `set_last_active` writes on every authenticated request; only the + # credential write is being ordered here. + if "hashed_password" in data: + calls.append("write") + return real_update(self, id, data, *args, **kwargs) + + async def record_revoke(user_id: str) -> None: + calls.append("revoke") + + with ( + mock.patch.object(DBUsersHandler, "update_user", record_update), + mock.patch.object( + RedisSessionMiddleware, "clear_user_sessions", side_effect=record_revoke + ), + ): + response = client.put( + f"/api/users/{editor_user.id}", + data={"password": "another_reset_password"}, + headers={"Authorization": f"Bearer {access_token}"}, + ) + + assert response.status_code == HTTPStatus.OK + assert calls == ["revoke", "write", "revoke"] + + @pytest.mark.asyncio async def test_password_change_invalidates_sessions(client, admin_user: User): # Get the user's session cookie diff --git a/backend/tests/handler/auth/test_redis_session_middleware.py b/backend/tests/handler/auth/test_redis_session_middleware.py index 49e318013..62e4f274c 100644 --- a/backend/tests/handler/auth/test_redis_session_middleware.py +++ b/backend/tests/handler/auth/test_redis_session_middleware.py @@ -52,8 +52,7 @@ class TestRedisSessionMiddleware: assert client.get("/whoami").json()["sub"] == USERNAME def test_revoked_session_is_not_restored_by_an_in_flight_request(self) -> None: - """A request holding a copy of a session revoked mid-flight must not - write it back, or a credential change could never lock anyone out.""" + """A session revoked mid-flight must not be written back.""" client = TestClient(create_test_app()) client.post("/login")