Skip to content

fix(session): make DatabaseSessionStorage row creation race-safe (#428) - #429

Merged
usernane merged 2 commits into
mainfrom
dev
Nov 9, 2026
Merged

usernane merged 2 commits into
mainfrom
dev

Conversation

@usernane

@usernane usernane commented Nov 9, 2026

Copy link
Copy Markdown
Member

Summary

Makes DatabaseSessionStorage (via SessionDB) create the session row race-safely, fixing a duplicate primary-key error that occurred under concurrency.

Motivation

SessionDB created the sessions row on first write with a non-atomic check-then-insert (isSessionExist() then INSERT). Two concurrent requests carrying the same brand-new session id (e.g. an SPA firing several API calls on first load) could both pass the existence check and both INSERT, causing a PRIMARY KEY violation on PK_sessions — SQL Server error 2627, MySQL error 1062. The losing request failed with a DatabaseException even though the session was ultimately created. Fixes #428.

Changes

  • Added SessionDB::ensureSessionRow() — idempotent, race-safe session-row creation: on a duplicate-key error it treats the row as already created and falls through to a last-used update instead of propagating the exception.
  • Added SessionDB::isDuplicateKeyError() — recognises duplicate/PK violations across SQL Server (2627/2601), MySQL (1062) and SQLite (19/23000), with a SQLSTATE/message fallback.
  • Replaced the inline check-then-insert in saveSession() and writeSessionKey() with ensureSessionRow().
  • Applied the same duplicate-key tolerance to the session_kv_data per-key insert in writeSessionKey() (a secondary race on the same path).
  • Added regression tests to MSSQLSessionStorageTest and MySQLSessionStorageTest.

How to Test / Verify

Automated (PHPUnit) integration tests against real databases:

  • MSSQLSessionStorageTest::testConcurrentCreateIsRaceSafe and MySQLSessionStorageTest::testConcurrentCreateIsRaceSafe deterministically drive SessionDB's create branch into a collision using a stale-read SessionDB double (its first isSessionExist() returns a stale false), reproducing the exact losing-request scenario.
  • Verified the tests fail on the pre-fix code (MSSQL 2627 / MySQL 1062) and pass with the fix.
  • Full Session test suite: 142 tests, 521 assertions, OK — no regressions (SQLite, default, cache, encryption, GC, schema, MSSQL, MySQL).

Breaking Changes and Migration Steps

None.

Checklist

  • I reviewed my own diff before requesting review
  • My commits follow Conventional Commits
  • I added/updated tests (or explained why not)
  • I updated docs (if needed) Docs Repo — not needed (internal behavior fix, no API change)
  • I ran lint/cs-fixer (if applicable) (composer fix-cs) — not run; changes follow existing file style and pass php -l
  • I considered backward compatibility
  • I considered security

Related issues

Closes #428

SessionDB used a non-atomic check-then-insert (isSessionExist() then INSERT)
to create the 'sessions' row on first write. Two concurrent requests carrying
the same new session id could both pass the existence check and both INSERT,
causing a PRIMARY KEY violation on PK_sessions (SQL Server error 2627, MySQL
error 1062).

Make the create idempotent via a new ensureSessionRow() helper: on a
duplicate-key error it treats the row as already created and falls through to
an update. Add isDuplicateKeyError() to recognise duplicate/PK violations
across SQL Server, MySQL and SQLite. Apply the same tolerance to the
session_kv_data per-key insert in writeSessionKey().

Add regression tests to MSSQLSessionStorageTest and MySQLSessionStorageTest
that deterministically drive the create branch into a collision via a
stale-read SessionDB double; they fail on the pre-fix code (2627 / 1062) and
pass with the fix.

Fixes #428
The 'sessions' table enforces a PRIMARY KEY on s-id for all engines, so the
non-atomic check-then-insert race applies to SQLite too (UNIQUE constraint
failed, error 19). SQLite's writer-serialising lock makes the natural race
unlikely, but it is still possible via separate connections or busy-retry.

Add a regression test mirroring the MSSQL/MySQL ones: a stale-read SessionDB
double drives the create branch into a collision. It fails on the pre-fix code
(error 19) and passes with the fix, exercising the SQLite branch of
isDuplicateKeyError().
@codecov

codecov Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.74419% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.99%. Comparing base (1751e54) to head (3dd6417).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
WebFiori/Framework/Session/SessionDB.php 76.74% 10 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main     #429      +/-   ##
============================================
+ Coverage     81.96%   81.99%   +0.03%     
- Complexity     3293     3301       +8     
============================================
  Files           106      106              
  Lines          9735     9752      +17     
============================================
+ Hits           7979     7996      +17     
  Misses         1756     1756              
Flag Coverage Δ
php-8.1 80.85% <77.77%> (+0.05%) ⬆️
php-8.2 80.83% <75.00%> (+0.03%) ⬆️
php-8.3 89.17% <65.11%> (-0.05%) ⬇️
php-8.4 89.17% <65.11%> (-0.05%) ⬇️
php-8.5 89.05% <65.11%> (-0.04%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sonarqubecloud

sonarqubecloud Bot commented Nov 9, 2026

Copy link
Copy Markdown

@usernane
usernane merged commit 00c9d94 into main Nov 9, 2026
15 of 16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(session): PK_sessions duplicate-key race in DatabaseSessionStorage check-then-insert

1 participant