AOSSIE-Org / AOSSIE-Org/DebateAI

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

Open
#402 8 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
TypeScript
Stars
84
Forks
198
Avg merge
2d 19h
Merged PRs (30d)
30

Description

### 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

- [x] I have joined the [Discord server](https://discord.gg/hjUhu33uAn) and will post updates there
- [x] I have searched existing issues to avoid duplicates

Contributor guide

No contributing guide indexed for this repository

Research direction

Start in backend/websocket/websocket.go at WebsocketHandler and trace the room mutex, upgrader.Upgrade(...), getUserDetails, and Client registration sequence. Reproduce the issue with three concurrent requests to /ws?room=X and inspect room.Clients; done means concurrent joins never allow more than two debaters in one room.

Written by the indexing model from the issue text.

Assessment

Tech stack
go, mongodb
Domain
backend, networking
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.