diff --git a/WebFiori/Framework/Session/SessionDB.php b/WebFiori/Framework/Session/SessionDB.php index 26e8380a4..2906329ff 100644 --- a/WebFiori/Framework/Session/SessionDB.php +++ b/WebFiori/Framework/Session/SessionDB.php @@ -291,18 +291,7 @@ public function removeTables() { * @since 1.0 */ public function saveSession(string $sId, string $session) { - if ($this->isSessionExist($sId)) { - $this->table('sessions')->update([ - 'last-used' => date('Y-m-d H:i:s') - ])->where('s-id', $sId) - ->execute(); - } else { - $this->table('sessions')->insert([ - 's-id' => $sId, - 'last-used' => date('Y-m-d H:i:s'), - 'started-at' => date('Y-m-d H:i:s'), - ])->execute(); - } + $this->ensureSessionRow($sId); $this->storeChunks($sId, base64_encode($session)); } /** @@ -318,18 +307,9 @@ public function writeSessionKey( string|int|null $expectedVersion, ConflictStrategy $strategy ): int { - // Ensure the session row exists. - if (!$this->isSessionExist($sId)) { - $this->table('sessions')->insert([ - 's-id' => $sId, - 'last-used' => date('Y-m-d H:i:s'), - 'started-at' => date('Y-m-d H:i:s'), - ])->execute(); - } else { - $this->table('sessions')->update([ - 'last-used' => date('Y-m-d H:i:s'), - ])->where('s-id', $sId)->execute(); - } + // Ensure the session row exists (race-safe: a concurrent first-write + // for the same session id will not raise a duplicate-key error). + $this->ensureSessionRow($sId); $existing = $this->getSessionKey($sId, $key); $currentVersion = $existing !== null ? $existing['version'] : 0; @@ -345,13 +325,27 @@ public function writeSessionKey( $encoded = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); if ($existing === null) { - $this->table('session_kv_data')->insert([ - 's-id' => $sId, - 'skey' => $key, - 'svalue' => $encoded, - 'version' => $newVersion, - 'updated-at' => date('Y-m-d H:i:s'), - ])->execute(); + try { + $this->table('session_kv_data')->insert([ + 's-id' => $sId, + 'skey' => $key, + 'svalue' => $encoded, + 'version' => $newVersion, + 'updated-at' => date('Y-m-d H:i:s'), + ])->execute(); + } catch (DatabaseException $ex) { + // A concurrent request inserted the same (s-id, skey) row + // between our read and insert. Fall through to an update. + if (!$this->isDuplicateKeyError($ex)) { + throw $ex; + } + $this->clear(); + $this->table('session_kv_data')->update([ + 'svalue' => $encoded, + 'version' => $newVersion, + 'updated-at' => date('Y-m-d H:i:s'), + ])->where('s-id', $sId)->andWhere('skey', $key)->execute(); + } } else { $this->table('session_kv_data')->update([ 'svalue' => $encoded, @@ -362,6 +356,73 @@ public function writeSessionKey( return $newVersion; } + /** + * Ensures that the 'sessions' row for the given id exists, race-safely. + * + * The create is idempotent: if a concurrent request inserts the same + * session id between the existence check and the insert, the resulting + * duplicate-key error (SQL Server 2627/2601, MySQL 1062, SQLite 19/23000) + * is caught and treated as "already exists", falling through to an update + * of the 'last-used' timestamp. This resolves the PK_sessions race + * described in issue #428. + * + * @param string $sId The ID of the session. + * + * @throws DatabaseException If a non-duplicate-key database error occurs. + */ + private function ensureSessionRow(string $sId): void { + if ($this->isSessionExist($sId)) { + $this->table('sessions')->update([ + 'last-used' => date('Y-m-d H:i:s'), + ])->where('s-id', $sId)->execute(); + + return; + } + + try { + $this->table('sessions')->insert([ + 's-id' => $sId, + 'last-used' => date('Y-m-d H:i:s'), + 'started-at' => date('Y-m-d H:i:s'), + ])->execute(); + } catch (DatabaseException $ex) { + // A concurrent request created the row between the check and the + // insert. Treat a duplicate-key error as success and update instead. + if (!$this->isDuplicateKeyError($ex)) { + throw $ex; + } + $this->clear(); + $this->table('sessions')->update([ + 'last-used' => date('Y-m-d H:i:s'), + ])->where('s-id', $sId)->execute(); + } + } + /** + * Checks whether a database exception represents a duplicate/primary-key + * constraint violation across the supported database engines. + * + * Error codes: + * - SQL Server: 2627 (PK violation), 2601 (unique index violation) + * - MySQL: 1062 (duplicate entry) + * - SQLite: 19 (SQLITE_CONSTRAINT), 23000 (SQLSTATE) + * + * @param DatabaseException $ex + * + * @return bool True if the exception is a duplicate-key violation. + */ + private function isDuplicateKeyError(DatabaseException $ex): bool { + if (in_array((int) $ex->getCode(), [2627, 2601, 1062, 19], true)) { + return true; + } + + // Fallback for drivers that surface a SQLSTATE string or wrap the + // message without a numeric code (e.g. SQLite via PDO). + $msg = $ex->getMessage(); + + return stripos($msg, 'duplicate') !== false + || stripos($msg, 'PRIMARY KEY') !== false + || stripos($msg, 'UNIQUE constraint') !== false; + } /** * Split session data into smaller chunks. * diff --git a/tests/WebFiori/Framework/Tests/Session/MSSQLSessionStorageTest.php b/tests/WebFiori/Framework/Tests/Session/MSSQLSessionStorageTest.php index 20b44ec87..3bf89fbc8 100644 --- a/tests/WebFiori/Framework/Tests/Session/MSSQLSessionStorageTest.php +++ b/tests/WebFiori/Framework/Tests/Session/MSSQLSessionStorageTest.php @@ -3,9 +3,11 @@ use PHPUnit\Framework\TestCase; use WebFiori\Database\ConnectionInfo; +use WebFiori\Database\DatabaseException; use WebFiori\Framework\App; use WebFiori\Framework\Session\ConflictStrategy; use WebFiori\Framework\Session\DatabaseSessionStorage; +use WebFiori\Framework\Session\SessionDB; class MSSQLSessionStorageTest extends TestCase { protected DatabaseSessionStorage $storage; @@ -18,6 +20,53 @@ public function testConcurrentSessions() { $this->assertEquals('data-b', $this->storage->read('session-b', 'k')['value']); $this->assertEquals('data-c', $this->storage->read('session-c', 'k')['value']); } + /** + * Regression test for bug #428: non-atomic check-then-insert race in + * SessionDB. Two concurrent requests carrying the same new session id both + * pass isSessionExist() and both reach the INSERT, causing a PRIMARY KEY + * (PK_sessions) violation — SQL Server error 2627. + * + * The race is reproduced deterministically with a SessionDB whose existence + * check is stale: it reports "no row" on first look even though another + * concurrent request has already created the row. This drives SessionDB's + * own create branch ("if (!isSessionExist()) INSERT") straight into the + * duplicate INSERT — exactly the losing-request scenario from the issue. + * + * Asserts the EXPECTED (correct) behavior: first-write session creation + * must be idempotent / race-safe, so the collision must be swallowed and + * NOT raise. This FAILS while the bug is present (the create throws 2627) + * and PASSES once SessionDB catches the duplicate-key and falls through to + * an update. + * + * @test + */ + public function testConcurrentCreateIsRaceSafe() { + $sId = 'race-session-'.uniqid(); + + // Request A wins the race and creates the session row first. + $requestA = new SessionDB('test-sessions-conn'); + $requestA->writeSessionKey($sId, 'k', 'value-a', null, ConflictStrategy::LAST_WRITE_WINS); + + // Request B has a STALE existence view: its isSessionExist() returned + // false before A inserted, so B still believes the row is absent and + // proceeds to the create branch. This is the losing request in the race. + $requestB = new StaleSessionDB('test-sessions-conn'); + + try { + $requestB->writeSessionKey($sId, 'k2', 'value-b', null, ConflictStrategy::LAST_WRITE_WINS); + } catch (DatabaseException $e) { + $this->fail( + 'Bug #428: concurrent session creation raised a duplicate-key error '. + '('.$e->getCode().' - '.$e->getMessage().'). '. + 'First-write session creation should be idempotent / race-safe.' + ); + } + + // Both concurrent first-writes must survive under the single session row. + $this->assertTrue($this->storage->getController()->isSessionExist($sId)); + $this->assertEquals('value-a', $this->storage->read($sId, 'k')['value']); + $this->assertEquals('value-b', $this->storage->read($sId, 'k2')['value']); + } /** @test */ public function testGCEmptyTable() { $this->storage->gc('2021-01-01 00:00:00'); @@ -131,3 +180,25 @@ protected function tearDown(): void { } } } + +/** + * Test double that simulates a losing request in the bug #428 race: its very + * first isSessionExist() check returns a STALE "false" (as if read before a + * concurrent request inserted the row), forcing SessionDB's create branch to + * run against an already-existing row. All subsequent checks delegate to the + * real implementation. + */ +class StaleSessionDB extends SessionDB { + private bool $staleReadConsumed = false; + + public function isSessionExist(string $sId): bool { + if (!$this->staleReadConsumed) { + $this->staleReadConsumed = true; + + // Pretend the row does not exist yet (stale read). + return false; + } + + return parent::isSessionExist($sId); + } +} diff --git a/tests/WebFiori/Framework/Tests/Session/MySQLSessionStorageTest.php b/tests/WebFiori/Framework/Tests/Session/MySQLSessionStorageTest.php index cace43f6e..e5e83aedf 100644 --- a/tests/WebFiori/Framework/Tests/Session/MySQLSessionStorageTest.php +++ b/tests/WebFiori/Framework/Tests/Session/MySQLSessionStorageTest.php @@ -4,9 +4,11 @@ use PHPUnit\Framework\TestCase; use WebFiori\Database\ConnectionInfo; use WebFiori\Database\Database; +use WebFiori\Database\DatabaseException; use WebFiori\Framework\App; use WebFiori\Framework\Session\ConflictStrategy; use WebFiori\Framework\Session\DatabaseSessionStorage; +use WebFiori\Framework\Session\SessionDB; class MySQLSessionStorageTest extends TestCase { protected DatabaseSessionStorage $storage; @@ -21,6 +23,51 @@ public function testConcurrentSessions() { $this->assertEquals('data-c', $this->storage->read('session-c', 'k')['value']); } + /** + * Regression test for bug #428 on MySQL: non-atomic check-then-insert race + * in SessionDB. Two concurrent requests carrying the same new session id + * both pass isSessionExist() and both reach the INSERT, causing a duplicate + * PRIMARY KEY error on the 'sessions' table — MySQL error 1062. + * + * The race is reproduced deterministically with a SessionDB whose existence + * check is stale: it reports "no row" on first look even though another + * concurrent request has already created the row, driving SessionDB's own + * create branch straight into the duplicate INSERT. + * + * Asserts the EXPECTED (correct) behavior: first-write session creation + * must be idempotent / race-safe, so the collision must be swallowed and + * NOT raise. FAILS while the bug is present (the create throws 1062) and + * PASSES once SessionDB catches the duplicate-key and falls through to an + * update. Confirms the fix covers MySQL as well as MSSQL. + * + * @test + */ + public function testConcurrentCreateIsRaceSafe() { + $sId = 'race-session-'.uniqid(); + + // Request A wins the race and creates the session row first. + $requestA = new SessionDB('test-sessions-conn'); + $requestA->writeSessionKey($sId, 'k', 'value-a', null, ConflictStrategy::LAST_WRITE_WINS); + + // Request B has a STALE existence view and proceeds to the create + // branch for a row that already exists — the losing request. + $requestB = new StaleMySQLSessionDB('test-sessions-conn'); + + try { + $requestB->writeSessionKey($sId, 'k2', 'value-b', null, ConflictStrategy::LAST_WRITE_WINS); + } catch (DatabaseException $e) { + $this->fail( + 'Bug #428: concurrent session creation raised a duplicate-key error '. + '('.$e->getCode().' - '.$e->getMessage().'). '. + 'First-write session creation should be idempotent / race-safe.' + ); + } + + $this->assertTrue($this->storage->getController()->isSessionExist($sId)); + $this->assertEquals('value-a', $this->storage->read($sId, 'k')['value']); + $this->assertEquals('value-b', $this->storage->read($sId, 'k2')['value']); + } + /** @test */ public function testGCEmptyTable() { $this->storage->gc('2021-01-01 00:00:00'); @@ -126,3 +173,23 @@ protected function tearDown(): void { } } } + +/** + * Test double for the bug #428 race on MySQL: its first isSessionExist() check + * returns a stale "false", forcing SessionDB's create branch to run against a + * row another request already inserted. Subsequent checks delegate to the real + * implementation. + */ +class StaleMySQLSessionDB extends SessionDB { + private bool $staleReadConsumed = false; + + public function isSessionExist(string $sId): bool { + if (!$this->staleReadConsumed) { + $this->staleReadConsumed = true; + + return false; + } + + return parent::isSessionExist($sId); + } +} diff --git a/tests/WebFiori/Framework/Tests/Session/SQLiteSessionStorageTest.php b/tests/WebFiori/Framework/Tests/Session/SQLiteSessionStorageTest.php index c281f296e..8fe1a3753 100644 --- a/tests/WebFiori/Framework/Tests/Session/SQLiteSessionStorageTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SQLiteSessionStorageTest.php @@ -3,11 +3,14 @@ use PHPUnit\Framework\TestCase; use WebFiori\Database\ConnectionInfo; +use WebFiori\Database\DatabaseException; use WebFiori\Framework\Session\ConflictStrategy; use WebFiori\Framework\Session\DatabaseSessionStorage; +use WebFiori\Framework\Session\SessionDB; class SQLiteSessionStorageTest extends TestCase { protected DatabaseSessionStorage $storage; + private ConnectionInfo $connection; /** @test */ public function testConcurrentSessions() { $this->storage->write('session-a', 'k', 'data-a', null, ConflictStrategy::LAST_WRITE_WINS); @@ -17,6 +20,50 @@ public function testConcurrentSessions() { $this->assertEquals('data-b', $this->storage->read('session-b', 'k')['value']); $this->assertEquals('data-c', $this->storage->read('session-c', 'k')['value']); } + /** + * Regression test for bug #428 on SQLite: non-atomic check-then-insert race + * in SessionDB. The 'sessions' table enforces a PRIMARY KEY on s-id for all + * engines, so a duplicate concurrent INSERT raises a UNIQUE constraint + * violation (SQLite error 19). + * + * Note: SQLite serialises writers with a database-level lock, so this + * natural race is far less likely than on a client/server database. The + * test reproduces it deterministically with a stale-read SessionDB double + * (its first isSessionExist() returns a stale "false"), forcing SessionDB's + * create branch to run against an already-existing row. This exercises the + * SQLite branch of the duplicate-key handling. + * + * Asserts the EXPECTED (correct) behavior: first-write session creation + * must be idempotent / race-safe, so the collision must be swallowed and + * NOT raise. FAILS on the pre-fix code (error 19) and PASSES with the fix. + * + * @test + */ + public function testConcurrentCreateIsRaceSafe() { + $sId = 'race-session-'.uniqid(); + + // Request A wins the race and creates the session row first. + $requestA = new SessionDB($this->connection); + $requestA->writeSessionKey($sId, 'k', 'value-a', null, ConflictStrategy::LAST_WRITE_WINS); + + // Request B has a STALE existence view and proceeds to the create + // branch for a row that already exists — the losing request. + $requestB = new StaleSQLiteSessionDB($this->connection); + + try { + $requestB->writeSessionKey($sId, 'k2', 'value-b', null, ConflictStrategy::LAST_WRITE_WINS); + } catch (DatabaseException $e) { + $this->fail( + 'Bug #428: concurrent session creation raised a duplicate-key error '. + '('.$e->getCode().' - '.$e->getMessage().'). '. + 'First-write session creation should be idempotent / race-safe.' + ); + } + + $this->assertTrue($this->storage->getController()->isSessionExist($sId)); + $this->assertEquals('value-a', $this->storage->read($sId, 'k')['value']); + $this->assertEquals('value-b', $this->storage->read($sId, 'k2')['value']); + } /** @test */ public function testGCEmptyTable() { $this->storage->gc('2021-01-01 00:00:00'); @@ -100,6 +147,7 @@ protected function setUp(): void { $dbPath = sys_get_temp_dir().DIRECTORY_SEPARATOR.'wf_session_test_'.getmypid().'.db'; $conn = new ConnectionInfo('sqlite', '', '', $dbPath, ''); $conn->setName('test-sessions-conn'); + $this->connection = $conn; $this->storage = new DatabaseSessionStorage($conn); $this->storage->getController()->removeTables(); @@ -118,3 +166,23 @@ protected function tearDown(): void { } } } + +/** + * Test double for the bug #428 race on SQLite: its first isSessionExist() check + * returns a stale "false", forcing SessionDB's create branch to run against a + * row another request already inserted. Subsequent checks delegate to the real + * implementation. + */ +class StaleSQLiteSessionDB extends SessionDB { + private bool $staleReadConsumed = false; + + public function isSessionExist(string $sId): bool { + if (!$this->staleReadConsumed) { + $this->staleReadConsumed = true; + + return false; + } + + return parent::isSessionExist($sId); + } +}