fix(auth): a cookie that lands after sign-out no longer signs the browser back in

A renewal answers with the session its request started with. Each session now
carries an id; signing out, or signing in as someone else, revokes it
(revoked_sessions, migration 0120), and a cookie carrying a revoked id is
refused. A cookie from before session ids gets one drawn from the cookie
itself. The race after log-out-everywhere fails closed and stays.
This commit is contained in:
2026-11-14 17:56:36 +01:00
parent d265c84c8b
commit 02714e4986
7 changed files with 164 additions and 8 deletions
+11 -5
View File
@@ -40,6 +40,7 @@ from app.auth import (
log,
operator_contact,
optional_current_user,
revoke_session,
session_user_id,
stamp_session,
)
@@ -531,7 +532,7 @@ async def callback(
db.flush()
_store_token(db, user, token)
_establish_session(request, user)
_establish_session(db, request, user)
db.commit()
log.info(
"signed in",
@@ -641,7 +642,7 @@ def _complete_link(
@router.post("/logout")
async def logout(request: Request):
def logout(request: Request, db: Session = Depends(get_db)):
"""Sign this browser out: the session holds one account, and it ends — unless the tab asking was
built for another account than the one signed in now (a sign-in as someone else in another tab):
its Sign out would end THAT person's session (see `EXPECTED_ACCOUNT_HEADER`)."""
@@ -650,14 +651,19 @@ async def logout(request: Request):
signed_in, request.headers.get(EXPECTED_ACCOUNT_HEADER)
):
raise refused(401, "account_changed")
revoke_session(db, request) # a request still in flight must not sign it back in
db.commit()
request.session.clear()
return JSONResponse({"ok": True})
def _establish_session(request: Request, user: User) -> None:
def _establish_session(db: Session, request: Request, user: User) -> None:
"""Sign `user` in for this browser session — the ONE sign-in path, shared by the Google callback
and password login, so both stamp `last_login_at` (the caller commits). One account per session:
the sign-in replaces whoever was signed in here before."""
the sign-in replaces whoever was signed in here before, and revokes that session's id, so a request
of theirs still in flight cannot land it back."""
revoke_session(db, request)
request.session.pop("sid", None)
request.session["user_id"] = user.id
stamp_session(request, user)
user.last_login_at = datetime.now(timezone.utc)
@@ -1040,7 +1046,7 @@ def password_login(
raise _login_refused(403, "email_unverified", user)
if not user.is_active:
raise _login_refused(403, "pending_approval", user)
_establish_session(request, user)
_establish_session(db, request, user)
db.commit()
log.info(
"signed in",