Skip to content

[BUG]: Race condition allows more than 2 debaters to join a room (TOCTOU in WebsocketHandler) #402

Description

@Prateekiiitg56

Bug Description

There's a race condition (TOCTOU - time-of-check to time-of-use) in the WebSocket room-joining logic that lets more than 2 debaters join a debate room even though the code is supposed to cap it at 2.

File: backend/websocket/websocket.go, inside WebsocketHandler. The flow is:

Lock the room mutex, count current debaters, unlock.
If under the limit, continue - upgrade the connection (upgrader.Upgrade(...)), fetch user details from MongoDB (getUserDetails), build the Client struct.
Only after all that, lock the mutex again and actually add the client to room.Clients.

The problem: the debater-count check happens in step 1, but the client only gets added to the map in step 3. Between those two locks there's a window (including a DB call and a WebSocket upgrade, which aren't instant) where a second or third debater connecting to the same room at nearly the same time can also pass the same "currentDebaters >= 2" check, since neither of them has been added to the map yet. So instead of exactly 2 debaters, a room can end up with 3+.

Steps to Reproduce

have 3 clients hit the same room's websocket endpoint (/ws?room=X) at nearly the same time, e.g. with a small script firing concurrent requests. Because the DB lookup (getUserDetails) and upgrader.Upgrade() both take non-zero time, more than 2 can slip past the check before any of them is registered in room.Clients.

Logs and Screenshots

ot adding one, this is a backend concurrency bug, not really something you can screenshot - it'd show up as a 3rd/4th person unexpectedly appearing in what should be a 1v1 debate room

Environment Details

No response

Impact

Medium - Feature works but has issues

Code of Conduct

  • I have joined the Discord server and will post updates there
  • I have searched existing issues to avoid duplicates

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions