Skip to content

fix: prevent MAX_SESSIONS race condition during concurrent session creation#428

Merged
KaranUnique merged 1 commit into
Canopus-Labs:mainfrom
hariom888:fix/372-session-limit-race
Jul 11, 2026
Merged

fix: prevent MAX_SESSIONS race condition during concurrent session creation#428
KaranUnique merged 1 commit into
Canopus-Labs:mainfrom
hariom888:fix/372-session-limit-race

Conversation

@hariom888

Copy link
Copy Markdown
Contributor

Summary

Fixes #372.

This PR resolves a race condition in createSession that allowed concurrent requests to bypass the MAX_SESSIONS limit.

Previously, the controller performed:

  1. countDocuments({ user })
  2. Compare against MAX_SESSIONS
  3. Create a new session

Because these operations were executed separately, multiple concurrent requests could observe the same session count before any insert completed, allowing more than MAX_SESSIONS sessions to be created.

Changes

  • Wrapped the session count and creation logic inside a MongoDB transaction.
  • Performed both the count check and session creation using the same transaction session.
  • Returned the existing session-limit error when the maximum number of sessions has already been reached.

Why this Fix

Executing both operations within a transaction removes the race window between checking the number of sessions and creating a new one.

Under concurrent requests:

  • Only one transaction can successfully create the final allowed session.
  • All remaining concurrent requests correctly receive the session-limit error.
  • Users can no longer exceed MAX_SESSIONS.

Testing

  • Verified normal sequential session creation.
  • Verified concurrent session creation when the user has MAX_SESSIONS - 1 sessions.
  • Confirmed that only one request succeeds and the final session count never exceeds MAX_SESSIONS.

Impact

This change is backward compatible and only strengthens enforcement of the existing session limit under concurrent requests.

@KaranUnique KaranUnique merged commit 534bc05 into Canopus-Labs:main Jul 11, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: TOCTOU race allows bypassing MAX_SESSIONS limit under concurrent session creation

2 participants