Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 92 additions & 31 deletions WebFiori/Framework/Session/SessionDB.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
/**
Expand All @@ -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;
Expand All @@ -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,
Expand All @@ -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.
*
Expand Down
71 changes: 71 additions & 0 deletions tests/WebFiori/Framework/Tests/Session/MSSQLSessionStorageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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');
Expand Down Expand Up @@ -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);
}
}
67 changes: 67 additions & 0 deletions tests/WebFiori/Framework/Tests/Session/MySQLSessionStorageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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');
Expand Down Expand Up @@ -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);
}
}
Loading
Loading