mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +01:00
* perf(backend): pipeline multi-command Redis writes - upload_chunk records a chunk with SADD, EXPIRE and SCARD in one transaction instead of three round trips, so a failure between them can no longer leave the chunk set without a TTL. - bind_to_login_session does its SADD and EXPIRE in one transaction for the same reason. - close_login_sessions reads and deletes a session's socket set in one transaction, so a socket binding in between is not dropped unseen. - Logout deletes the session and removes it from the user's set in one pipeline. - complete_chunked_upload reads the chunk set once instead of SCARD then SMEMBERS; cancel and invalidate_filter_values_cache delete their keys in one call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv * fix(backend): refuse a socket bind that lands after its session's revocation - bind_to_login_session checks the login session still exists in the same transaction as its SADD. Revocation deletes the session before it reads the socket set, so a bind that finds it gone removes itself and authenticate treats the socket as anonymous. - complete_chunked_upload keeps its SCARD fast path and reads the members only to name the missing chunks. - cancel_chunked_upload removes the temporary files before touching Redis. - Tests check each pipelined write executes as one MULTI/EXEC. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv * fix(backend): close an upload session before removing its files on cancel A chunk PUT that passes the session check after the temporary directory is gone fails with a 500; deleting the session first turns it into a 404. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv * fix(backend): answer a chunk write cut short by a cancel with 404 A PUT that passed the session check before the cancel removed its directory fails writing; it now re-reads the session and returns the same 404 as a PUT that arrives after the cancel, instead of a 500. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv * chore(backend): remove a stray Redis snapshot Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T2WxB8t3Shv4TZmHFdSMHv --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
132 lines
4.4 KiB
Python
132 lines
4.4 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"
|
|
|
|
|
|
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 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 whoami(request: Request) -> JSONResponse:
|
|
return JSONResponse({"sub": request.session.get("sub")})
|
|
|
|
async def logout(request: Request) -> JSONResponse:
|
|
request.session.clear()
|
|
return JSONResponse({"ok": True})
|
|
|
|
return Starlette(
|
|
routes=[
|
|
Route("/login", login, 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_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_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()
|