Files
romm/backend/tests/handler/auth/test_redis_session_middleware.py
Georges-Antoine Assi 494b4b4291 fix(auth): issue a new session id when the session changes identity (#5630)
* fix(auth): issue a new session id when the session changes identity

Logging in (password or OIDC) wrote the user into the session named by
the request cookie, so a session id set in the browser beforehand kept
working for whoever held it after the login. The session middleware now
writes the session under a fresh id whenever its user changes, and
deletes the previous record and closes its sockets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(auth): leave the session cookie alone when a refresh finds it gone

A request still in flight on a session that a concurrent login rotated
away failed its refresh and answered with an expiring session cookie,
which wiped the fresh cookie the login had just set. A failed refresh
now sends no Set-Cookie at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:46:01 -05:00

211 lines
7.5 KiB
Python

"""Test suite for RedisSessionMiddleware's Redis-backed session persistence."""
from unittest.mock import AsyncMock
import pytest
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.testclient import TestClient
from handler.auth.constants import SESSION_COOKIE_NAME
from handler.auth.middleware import redis_session_middleware
from handler.auth.middleware.redis_session_middleware import RedisSessionMiddleware
from handler.redis_handler import sync_cache
USERNAME = "user_1"
OTHER_USERNAME = "user_2"
def create_test_app() -> Starlette:
async def login(request: Request) -> JSONResponse:
request.session["iss"] = "romm:auth"
request.session["sub"] = USERNAME
return JSONResponse({"ok": True})
async def login_other(request: Request) -> JSONResponse:
request.session["iss"] = "romm:auth"
request.session["sub"] = OTHER_USERNAME
return JSONResponse({"ok": True})
async def remember(request: Request) -> JSONResponse:
request.session["state"] = "pending"
return JSONResponse({"ok": True})
async def revoke(request: Request) -> JSONResponse:
"""Revoke the caller's sessions while their own request is in flight."""
await RedisSessionMiddleware.clear_user_sessions(USERNAME)
return JSONResponse({"ok": True})
async def stale(request: Request) -> JSONResponse:
"""Finish after a concurrent login rotated this request's session away."""
sync_cache.delete(f"session:{request.session['session_id']}")
request.session["touched"] = True
return JSONResponse({"ok": True})
async def whoami(request: Request) -> JSONResponse:
return JSONResponse(
{"sub": request.session.get("sub"), "state": request.session.get("state")}
)
async def logout(request: Request) -> JSONResponse:
request.session.clear()
return JSONResponse({"ok": True})
return Starlette(
routes=[
Route("/login", login, methods=["POST"]),
Route("/login_other", login_other, methods=["POST"]),
Route("/remember", remember, methods=["POST"]),
Route("/stale", stale, methods=["POST"]),
Route("/revoke", revoke, methods=["POST"]),
Route("/whoami", whoami, methods=["GET"]),
Route("/logout", logout, methods=["POST"]),
],
middleware=[
Middleware(
RedisSessionMiddleware,
session_cookie=SESSION_COOKIE_NAME,
same_site="strict",
https_only=False,
)
],
)
class TestRedisSessionMiddleware:
def test_session_survives_across_requests(self) -> None:
client = TestClient(create_test_app())
assert client.post("/login").status_code == 200
assert client.get("/whoami").json()["sub"] == USERNAME
def test_revoked_session_is_not_restored_by_an_in_flight_request(self) -> None:
"""A session revoked mid-flight must not be written back."""
client = TestClient(create_test_app())
client.post("/login")
client.post("/revoke")
assert client.get("/whoami").json()["sub"] is None
def test_a_cookie_for_an_unknown_session_gets_a_fresh_id(self) -> None:
client = TestClient(create_test_app())
client.cookies.set(SESSION_COOKIE_NAME, "not-a-real-session")
response = client.post("/login")
assert response.cookies[SESSION_COOKIE_NAME] != "not-a-real-session"
def test_logging_in_over_another_users_session_gets_a_fresh_id(self) -> None:
attacker = TestClient(create_test_app())
planted_id = attacker.post("/login_other").cookies[SESSION_COOKIE_NAME]
victim = TestClient(create_test_app())
victim.cookies.set(SESSION_COOKIE_NAME, planted_id)
victim_id = victim.post("/login").cookies[SESSION_COOKIE_NAME]
assert victim_id != planted_id
assert not sync_cache.exists(f"session:{planted_id}")
assert planted_id.encode() not in sync_cache.smembers(
f"user_sessions:{OTHER_USERNAME}"
)
assert attacker.get("/whoami").json()["sub"] is None
assert victim.get("/whoami").json()["sub"] == USERNAME
def test_logging_in_over_an_anonymous_session_keeps_its_data_under_a_fresh_id(
self,
) -> None:
client = TestClient(create_test_app())
anonymous_id = client.post("/remember").cookies[SESSION_COOKIE_NAME]
login_id = client.post("/login").cookies[SESSION_COOKIE_NAME]
assert login_id != anonymous_id
assert not sync_cache.exists(f"session:{anonymous_id}")
assert client.get("/whoami").json() == {"sub": USERNAME, "state": "pending"}
def test_logging_in_again_as_the_same_user_keeps_the_id(self) -> None:
client = TestClient(create_test_app())
first_id = client.post("/login").cookies[SESSION_COOKIE_NAME]
second_id = client.post("/login").cookies[SESSION_COOKIE_NAME]
assert second_id == first_id
def test_a_request_outliving_its_rotated_session_keeps_the_new_cookie(
self,
) -> None:
client = TestClient(create_test_app())
client.post("/remember")
response = client.post("/stale")
assert "set-cookie" not in response.headers
def test_logging_out_forgets_the_session(self) -> None:
client = TestClient(create_test_app())
session_id = client.post("/login").cookies[SESSION_COOKIE_NAME]
client.post("/logout")
assert not sync_cache.exists(f"session:{session_id}")
assert session_id.encode() not in sync_cache.smembers(
f"user_sessions:{USERNAME}"
)
class TestRevokedSessionsCloseTheirSockets:
@pytest.fixture
def close_login_sessions(self, mocker):
return mocker.patch.object(
redis_session_middleware, "close_login_session_sockets", AsyncMock()
)
def test_logging_out_closes_that_sessions_sockets(
self, close_login_sessions
) -> None:
client = TestClient(create_test_app())
session_id = client.post("/login").cookies[SESSION_COOKIE_NAME]
client.post("/logout")
close_login_sessions.assert_awaited_once_with([session_id])
def test_revoking_a_users_sessions_closes_all_their_sockets(
self, close_login_sessions
) -> None:
phone, laptop = TestClient(create_test_app()), TestClient(create_test_app())
ids = {
phone.post("/login").cookies[SESSION_COOKIE_NAME],
laptop.post("/login").cookies[SESSION_COOKIE_NAME],
}
phone.post("/revoke")
assert ids <= set(close_login_sessions.await_args.args[0])
def test_logging_in_over_another_users_session_closes_its_sockets(
self, close_login_sessions
) -> None:
attacker = TestClient(create_test_app())
planted_id = attacker.post("/login_other").cookies[SESSION_COOKIE_NAME]
victim = TestClient(create_test_app())
victim.cookies.set(SESSION_COOKIE_NAME, planted_id)
victim.post("/login")
close_login_sessions.assert_awaited_once_with([planted_id])
def test_a_cookie_for_a_gone_session_closes_nothing(
self, close_login_sessions
) -> None:
client = TestClient(create_test_app())
client.cookies.set(SESSION_COOKIE_NAME, "not-a-real-session")
client.post("/logout")
close_login_sessions.assert_not_awaited()