fix: apply the verified-user role gate to WebSocket authentication (#27537)

The Socket.IO handshake and the terminal WebSocket route each reimplement JWT authentication instead of going through the HTTP dependency chain. Both verified that the token decoded, that it had not been revoked, and that the user row existed, but neither applied the role check that `get_verified_user` enforces on every HTTP route, so any role outside `user` and `admin` was accepted.

That splits authorization across two planes. Deactivating an account by setting its role to `pending` takes effect immediately over HTTP, which returns 401, while the same JWT still opens a WebSocket. Changing a role disconnects the account's live sockets but does not revoke its token, so the client simply reconnects and gets a fresh session. Until the token expires, four weeks by default, a deactivated account keeps its channel rooms and can still read and write any note it holds an access grant on through the collaborative document handlers.

Resolve the user once, in `get_verified_user_by_token`, and route both WebSocket entry points through it. The role set moves into `VERIFIED_USER_ROLES` so the HTTP and WebSocket gates cannot drift apart, which is the underlying cause rather than either call site on its own. This also replaces five copies of the decode, revocation check and user lookup sequence.

`user-join` now resolves the user instead of reusing the identity cached in `SESSION_POOL`, which costs one extra query per handshake. Gating on the cached role would make the authorization decision depend on every future role-mutation path remembering to tear down the session pool, and that is precisely the invariant that failed here.
This commit is contained in:
Classic298
2026-07-26 17:27:54 -04:00
committed by GitHub
parent 29499cb4ba
commit f517cc7172
3 changed files with 30 additions and 37 deletions
+17 -1
View File
@@ -488,8 +488,11 @@ async def get_current_user_by_api_key(request, api_key: str):
return user
VERIFIED_USER_ROLES = {'user', 'admin'}
def get_verified_user(user=Depends(get_current_user)):
if user.role not in {'user', 'admin'}:
if user.role not in VERIFIED_USER_ROLES:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
@@ -497,6 +500,19 @@ def get_verified_user(user=Depends(get_current_user)):
return user
async def get_verified_user_by_token(token: str, redis=None):
"""Resolve a verified user from a raw token, for WebSocket handshakes that run outside the HTTP dependency chain."""
decoded = decode_token(token)
if decoded is None or 'id' not in decoded or not await is_valid_token(decoded, redis):
return None
user = await Users.get_user_by_id(decoded['id'])
if user is None or user.role not in VERIFIED_USER_ROLES:
return None
return user
def get_admin_user(user=Depends(get_current_user)):
if user.role != 'admin':
raise HTTPException(