Files
romm/backend/handler/auth/middleware/redis_session_middleware.py
Sam Dornan d828706ef9 perf(backend): pipeline multi-command Redis writes (#4858)
* 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>
2026-09-27 19:41:49 -05:00

117 lines
4.7 KiB
Python

import json
import uuid
from starlette.datastructures import MutableHeaders
from starlette.requests import HTTPConnection
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from config import SESSION_MAX_AGE_SECONDS
from handler.redis_handler import as_text, async_cache
from handler.socket_handler import close_login_session_sockets
class RedisSessionMiddleware:
def __init__(
self,
app: ASGIApp,
session_cookie: str = "session",
max_age: int = SESSION_MAX_AGE_SECONDS,
same_site: str = "lax",
https_only: bool = False,
) -> None:
self.app = app
self.session_cookie = session_cookie
self.max_age = max_age
self.security_flags = "httponly; samesite=" + same_site
if https_only:
self.security_flags += "; secure"
@staticmethod
async def clear_user_sessions(user_id: str) -> None:
"""
Clears all active sessions for a given user.
"""
session_ids = await async_cache.smembers(f"user_sessions:{user_id}")
if not session_ids:
return
# A member arrives as bytes from a client that does not decode, and its
# repr in a key name would miss the session and leave it live.
ids = [as_text(sid) for sid in session_ids]
await async_cache.delete(
*(f"session:{sid}" for sid in ids), f"user_sessions:{user_id}"
)
await close_login_session_sockets(ids)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in ("http", "websocket"):
await self.app(scope, receive, send)
return
connection = HTTPConnection(scope)
session_id = None
initial_user_id = None
session_cookie_from_request = connection.cookies.get(self.session_cookie)
if session_cookie_from_request:
session_id = session_cookie_from_request
session_data = await async_cache.get(f"session:{session_id}")
if session_data:
scope["session"] = json.loads(session_data)
scope["session"]["session_id"] = session_id
initial_user_id = scope["session"].get("sub")
else:
scope["session"] = {}
else:
scope["session"] = {}
async def send_wrapper(message: Message) -> None:
nonlocal session_id
if message["type"] == "http.response.start":
headers = MutableHeaders(scope=message)
# Check for user_id to track user-specific sessions
user_id = scope["session"].get("sub")
if scope["session"]:
existing_id = scope["session"].pop("session_id", None)
session_id = existing_id or str(uuid.uuid4())
session_data_json = json.dumps(scope["session"])
# Refreshed only while its record is still there, so a
# session revoked mid-request is not written back.
stored = await async_cache.set(
f"session:{session_id}",
session_data_json,
ex=self.max_age,
xx=existing_id is not None,
)
if stored:
# Add session_id to user set of sessions
if user_id:
await async_cache.sadd(
f"user_sessions:{user_id}", session_id
)
header_value = f"{self.session_cookie}={session_id}; path=/; Max-Age={self.max_age}; {self.security_flags}"
else:
header_value = f"{self.session_cookie}=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; {self.security_flags}"
headers.append("Set-Cookie", header_value)
elif session_id:
async with async_cache.pipeline() as pipe:
await pipe.delete(f"session:{session_id}")
if initial_user_id:
await pipe.srem(
f"user_sessions:{initial_user_id}", session_id
)
await pipe.execute()
if initial_user_id:
await close_login_session_sockets([session_id])
header_value = f"{self.session_cookie}=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; {self.security_flags}"
headers.append("Set-Cookie", header_value)
await send(message)
await self.app(scope, receive, send_wrapper)