diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index 5a5ea3539895..ad7bd92d967f 100644 --- a/docs/changelogs/v4.7.7.md +++ b/docs/changelogs/v4.7.7.md @@ -35,6 +35,7 @@ Release Date: Unreleased - **Security:** Fixed a bug where `Security::__construct()` threw a `TypeError` when the CSRF cookie was an array, causing an HTTP 500 response for affected requests. - **Security:** Fixed a bug in `strip_image_tags()` where an invalid PCRE character class caused attribute injection and improper quote handling, and ensured tags without `src` are stripped. - **Session:** Fixed a bug where `BaseHandler::destroyCookie()` did not send the `SameSite` attribute in the `Set-Cookie` header, which could prevent browsers from properly clearing the session cookie. +- **Session:** Fixed a bug where `MemcachedHandler` did not reset lock state in `close()` or release an existing lock for a different session ID in `lockSession()`, causing subsequent reads and session ID regeneration on the same handler instance to fail. - **Session:** Fixed a bug where `Session::start()` did not remove an invalid session cookie from `Request`'s cached cookie global if cookies had already been read from `Request`. - **Worker Mode:** Fixed a bug where every request that ended with an uncaught exception, including a `404 Page Not Found` without a 404 override, called `exit()` in the exception handler. This ended the worker script, so FrankenPHP booted a new one, and the worker loop skipped its cleanup after the request. The exception handler now returns to the worker loop. diff --git a/system/Session/Handlers/MemcachedHandler.php b/system/Session/Handlers/MemcachedHandler.php index c64ba65f6454..ecb21f9e3880 100644 --- a/system/Session/Handlers/MemcachedHandler.php +++ b/system/Session/Handlers/MemcachedHandler.php @@ -221,11 +221,7 @@ public function write($id, $data): bool public function close(): bool { if (isset($this->memcached)) { - if (isset($this->lockKey)) { - $this->memcached->delete($this->lockKey); - } - - return true; + return ! isset($this->lockKey) || $this->releaseLock(); } return false; @@ -265,11 +261,19 @@ public function gc($max_lifetime): int */ protected function lockSession(string $sessionID): bool { - if (isset($this->lockKey)) { + $lockKey = $this->keyPrefix . $sessionID . ':lock'; + + // PHP reuses the SessionHandler object on regeneration, + // so we need to check here if the lock key is for the + // correct session ID. + if ($this->lockKey === $lockKey) { return $this->memcached->replace($this->lockKey, Time::now()->getTimestamp(), 300); } - $lockKey = $this->keyPrefix . $sessionID . ':lock'; + if (isset($this->lockKey) && ! $this->releaseLock()) { + return false; + } + $attempt = 0; do { diff --git a/tests/system/Session/Handlers/MemcachedHandlerTest.php b/tests/system/Session/Handlers/MemcachedHandlerTest.php index 8a24a7377722..08d64eaceac5 100644 --- a/tests/system/Session/Handlers/MemcachedHandlerTest.php +++ b/tests/system/Session/Handlers/MemcachedHandlerTest.php @@ -18,6 +18,7 @@ use CodeIgniter\Test\TestLogger; use Config\Logger as LoggerConfig; use Config\Session as SessionConfig; +use Memcached; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\Attributes\RequiresPhpExtension; @@ -33,6 +34,11 @@ final class MemcachedHandlerTest extends CIUnitTestCase private string $sessionSavePath = '127.0.0.1:11211'; private string $userIpAddress = '127.0.0.1'; + /** + * @var list + */ + private array $sessionIds = []; + /** * @param array $options Replace values for `Config\Session`. */ @@ -62,11 +68,34 @@ protected function getInstance($options = []): MemcachedHandler protected function tearDown(): void { + if ($this->sessionIds !== []) { + $memcached = new Memcached(); + $memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true); + $memcached->addServer('127.0.0.1', 11211); + + $prefix = 'ci_session:' . $this->sessionName . ':'; + + foreach ($this->sessionIds as $sessionId) { + $memcached->delete($prefix . $sessionId); + $memcached->delete($prefix . $sessionId . ':lock'); + } + + $this->sessionIds = []; + } + parent::tearDown(); MemcachedHandler::resetPersistentConnections(); } + private function generateSessionId(string $prefix): string + { + $sessionId = $prefix . bin2hex(random_bytes(13)); + $this->sessionIds[] = $sessionId; + + return $sessionId; + } + public function testConstructorThrowsWithEmptySavePath(): void { $this->expectException(SessionException::class); @@ -128,4 +157,120 @@ public function testGC(): void $handler = $this->getInstance(); $this->assertSame(1, $handler->gc(3600)); } + + public function testReopenAndReadWithSameHandlerInstance(): void + { + $handler = $this->getInstance(); + $handler->open($this->sessionSavePath, $this->sessionName); + + $sessionId = $this->generateSessionId('666666'); + + $this->assertSame('', $handler->read($sessionId)); + + $data = '__ci_last_regenerate|i:1664607454;key|s:5:"value";'; + $this->assertTrue($handler->write($sessionId, $data)); + $this->assertTrue($handler->close()); + + // Reopen with the same handler instance (e.g. session_write_close() + session_start()) + $this->assertTrue($handler->open($this->sessionSavePath, $this->sessionName)); + $this->assertSame($data, $handler->read($sessionId)); + $this->assertTrue($handler->close()); + } + + public function testRegenerateSessionIdWithSameHandlerInstance(): void + { + $handler = $this->getInstance(); + $handler->open($this->sessionSavePath, $this->sessionName); + + $oldSessionId = $this->generateSessionId('777777'); + $newSessionId = $this->generateSessionId('888888'); + + $this->assertSame('', $handler->read($oldSessionId)); + + $data = '__ci_last_regenerate|i:1664607454;role|s:5:"admin";'; + $this->assertTrue($handler->write($oldSessionId, $data)); + $this->assertTrue($handler->close()); + + // PHP reuses the same SessionHandler object on regeneration + $this->assertTrue($handler->open($this->sessionSavePath, $this->sessionName)); + $this->assertSame('', $handler->read($newSessionId)); + $this->assertTrue($handler->write($newSessionId, $data)); + $this->assertTrue($handler->close()); + + $this->assertTrue($handler->open($this->sessionSavePath, $this->sessionName)); + $this->assertSame($data, $handler->read($newSessionId)); + $this->assertTrue($handler->close()); + } + + public function testRegenerateSessionIdWriteWithoutClose(): void + { + $handler = $this->getInstance(); + $handler->open($this->sessionSavePath, $this->sessionName); + + $oldSessionId = $this->generateSessionId('999999'); + $newSessionId = $this->generateSessionId('aaaaaa'); + + $this->assertSame('', $handler->read($oldSessionId)); + + $oldData = '__ci_last_regenerate|i:1664607454;role|s:5:"guest";'; + $this->assertTrue($handler->write($oldSessionId, $oldData)); + + $memcached = $this->getPrivateProperty($handler, 'memcached'); + $this->assertInstanceOf(Memcached::class, $memcached); + + $prefix = 'ci_session:' . $this->sessionName . ':'; + $memcached->get($prefix . $oldSessionId . ':lock'); + $this->assertSame(Memcached::RES_SUCCESS, $memcached->getResultCode()); + + // Exercise write() with a different session ID without closing the handler. + $newData = '__ci_last_regenerate|i:1664607500;role|s:5:"admin";'; + $this->assertTrue($handler->write($newSessionId, $newData)); + + $this->assertFalse($memcached->get($prefix . $oldSessionId . ':lock')); + $this->assertSame(Memcached::RES_NOTFOUND, $memcached->getResultCode()); + + $memcached->get($prefix . $newSessionId . ':lock'); + $this->assertSame(Memcached::RES_SUCCESS, $memcached->getResultCode()); + + $this->assertTrue($handler->close()); + $this->assertFalse($memcached->get($prefix . $newSessionId . ':lock')); + $this->assertSame(Memcached::RES_NOTFOUND, $memcached->getResultCode()); + + // Verify that both session IDs retain their respective data. + $handler2 = $this->getInstance(); + $this->assertTrue($handler2->open($this->sessionSavePath, $this->sessionName)); + $this->assertSame($oldData, $handler2->read($oldSessionId)); + $this->assertTrue($handler2->close()); + + $this->assertTrue($handler2->open($this->sessionSavePath, $this->sessionName)); + $this->assertSame($newData, $handler2->read($newSessionId)); + $this->assertTrue($handler2->close()); + } + + public function testReadDifferentSessionIdsWithoutCloseReleasesPreviousLock(): void + { + $handler = $this->getInstance(); + $handler->open($this->sessionSavePath, $this->sessionName); + + $firstSessionId = $this->generateSessionId('bbbbbb'); + $secondSessionId = $this->generateSessionId('cccccc'); + + $firstData = '__ci_last_regenerate|i:1664607454;user|s:5:"alice";'; + $this->assertSame('', $handler->read($firstSessionId)); + $this->assertTrue($handler->write($firstSessionId, $firstData)); + $this->assertTrue($handler->close()); + + // Read two different session IDs on the same handler without closing between them + $this->assertTrue($handler->open($this->sessionSavePath, $this->sessionName)); + $this->assertSame($firstData, $handler->read($firstSessionId)); + $this->assertSame('', $handler->read($secondSessionId)); + + // Another handler should be able to acquire the lock for the first session ID + $handler2 = $this->getInstance(); + $this->assertTrue($handler2->open($this->sessionSavePath, $this->sessionName)); + $this->assertSame($firstData, $handler2->read($firstSessionId)); + $this->assertTrue($handler2->close()); + + $this->assertTrue($handler->close()); + } }