Skip to content

Commit b95b9c7

Browse files
authored
fix(Session): release lock state on close and check session ID in MemcachedHandler (#10760)
1 parent ec86761 commit b95b9c7

3 files changed

Lines changed: 157 additions & 7 deletions

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ Release Date: Unreleased
4040
- **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.
4141
- **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.
4242
- **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.
43+
- **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.
4344
- **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`.
4445
- **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.
4546

‎system/Session/Handlers/MemcachedHandler.php‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -221,11 +221,7 @@ public function write($id, $data): bool
221221
public function close(): bool
222222
{
223223
if (isset($this->memcached)) {
224-
if (isset($this->lockKey)) {
225-
$this->memcached->delete($this->lockKey);
226-
}
227-
228-
return true;
224+
return ! isset($this->lockKey) || $this->releaseLock();
229225
}
230226

231227
return false;
@@ -265,11 +261,19 @@ public function gc($max_lifetime): int
265261
*/
266262
protected function lockSession(string $sessionID): bool
267263
{
268-
if (isset($this->lockKey)) {
264+
$lockKey = $this->keyPrefix . $sessionID . ':lock';
265+
266+
// PHP reuses the SessionHandler object on regeneration,
267+
// so we need to check here if the lock key is for the
268+
// correct session ID.
269+
if ($this->lockKey === $lockKey) {
269270
return $this->memcached->replace($this->lockKey, Time::now()->getTimestamp(), 300);
270271
}
271272

272-
$lockKey = $this->keyPrefix . $sessionID . ':lock';
273+
if (isset($this->lockKey) && ! $this->releaseLock()) {
274+
return false;
275+
}
276+
273277
$attempt = 0;
274278

275279
do {

‎tests/system/Session/Handlers/MemcachedHandlerTest.php‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use CodeIgniter\Test\TestLogger;
1919
use Config\Logger as LoggerConfig;
2020
use Config\Session as SessionConfig;
21+
use Memcached;
2122
use PHPUnit\Framework\Attributes\Group;
2223
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
2324

@@ -33,6 +34,11 @@ final class MemcachedHandlerTest extends CIUnitTestCase
3334
private string $sessionSavePath = '127.0.0.1:11211';
3435
private string $userIpAddress = '127.0.0.1';
3536

37+
/**
38+
* @var list<string>
39+
*/
40+
private array $sessionIds = [];
41+
3642
/**
3743
* @param array<string, bool|int|string|null> $options Replace values for `Config\Session`.
3844
*/
@@ -62,11 +68,34 @@ protected function getInstance($options = []): MemcachedHandler
6268

6369
protected function tearDown(): void
6470
{
71+
if ($this->sessionIds !== []) {
72+
$memcached = new Memcached();
73+
$memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
74+
$memcached->addServer('127.0.0.1', 11211);
75+
76+
$prefix = 'ci_session:' . $this->sessionName . ':';
77+
78+
foreach ($this->sessionIds as $sessionId) {
79+
$memcached->delete($prefix . $sessionId);
80+
$memcached->delete($prefix . $sessionId . ':lock');
81+
}
82+
83+
$this->sessionIds = [];
84+
}
85+
6586
parent::tearDown();
6687

6788
MemcachedHandler::resetPersistentConnections();
6889
}
6990

91+
private function generateSessionId(string $prefix): string
92+
{
93+
$sessionId = $prefix . bin2hex(random_bytes(13));
94+
$this->sessionIds[] = $sessionId;
95+
96+
return $sessionId;
97+
}
98+
7099
public function testConstructorThrowsWithEmptySavePath(): void
71100
{
72101
$this->expectException(SessionException::class);
@@ -128,4 +157,120 @@ public function testGC(): void
128157
$handler = $this->getInstance();
129158
$this->assertSame(1, $handler->gc(3600));
130159
}
160+
161+
public function testReopenAndReadWithSameHandlerInstance(): void
162+
{
163+
$handler = $this->getInstance();
164+
$handler->open($this->sessionSavePath, $this->sessionName);
165+
166+
$sessionId = $this->generateSessionId('666666');
167+
168+
$this->assertSame('', $handler->read($sessionId));
169+
170+
$data = '__ci_last_regenerate|i:1664607454;key|s:5:"value";';
171+
$this->assertTrue($handler->write($sessionId, $data));
172+
$this->assertTrue($handler->close());
173+
174+
// Reopen with the same handler instance (e.g. session_write_close() + session_start())
175+
$this->assertTrue($handler->open($this->sessionSavePath, $this->sessionName));
176+
$this->assertSame($data, $handler->read($sessionId));
177+
$this->assertTrue($handler->close());
178+
}
179+
180+
public function testRegenerateSessionIdWithSameHandlerInstance(): void
181+
{
182+
$handler = $this->getInstance();
183+
$handler->open($this->sessionSavePath, $this->sessionName);
184+
185+
$oldSessionId = $this->generateSessionId('777777');
186+
$newSessionId = $this->generateSessionId('888888');
187+
188+
$this->assertSame('', $handler->read($oldSessionId));
189+
190+
$data = '__ci_last_regenerate|i:1664607454;role|s:5:"admin";';
191+
$this->assertTrue($handler->write($oldSessionId, $data));
192+
$this->assertTrue($handler->close());
193+
194+
// PHP reuses the same SessionHandler object on regeneration
195+
$this->assertTrue($handler->open($this->sessionSavePath, $this->sessionName));
196+
$this->assertSame('', $handler->read($newSessionId));
197+
$this->assertTrue($handler->write($newSessionId, $data));
198+
$this->assertTrue($handler->close());
199+
200+
$this->assertTrue($handler->open($this->sessionSavePath, $this->sessionName));
201+
$this->assertSame($data, $handler->read($newSessionId));
202+
$this->assertTrue($handler->close());
203+
}
204+
205+
public function testRegenerateSessionIdWriteWithoutClose(): void
206+
{
207+
$handler = $this->getInstance();
208+
$handler->open($this->sessionSavePath, $this->sessionName);
209+
210+
$oldSessionId = $this->generateSessionId('999999');
211+
$newSessionId = $this->generateSessionId('aaaaaa');
212+
213+
$this->assertSame('', $handler->read($oldSessionId));
214+
215+
$oldData = '__ci_last_regenerate|i:1664607454;role|s:5:"guest";';
216+
$this->assertTrue($handler->write($oldSessionId, $oldData));
217+
218+
$memcached = $this->getPrivateProperty($handler, 'memcached');
219+
$this->assertInstanceOf(Memcached::class, $memcached);
220+
221+
$prefix = 'ci_session:' . $this->sessionName . ':';
222+
$memcached->get($prefix . $oldSessionId . ':lock');
223+
$this->assertSame(Memcached::RES_SUCCESS, $memcached->getResultCode());
224+
225+
// Exercise write() with a different session ID without closing the handler.
226+
$newData = '__ci_last_regenerate|i:1664607500;role|s:5:"admin";';
227+
$this->assertTrue($handler->write($newSessionId, $newData));
228+
229+
$this->assertFalse($memcached->get($prefix . $oldSessionId . ':lock'));
230+
$this->assertSame(Memcached::RES_NOTFOUND, $memcached->getResultCode());
231+
232+
$memcached->get($prefix . $newSessionId . ':lock');
233+
$this->assertSame(Memcached::RES_SUCCESS, $memcached->getResultCode());
234+
235+
$this->assertTrue($handler->close());
236+
$this->assertFalse($memcached->get($prefix . $newSessionId . ':lock'));
237+
$this->assertSame(Memcached::RES_NOTFOUND, $memcached->getResultCode());
238+
239+
// Verify that both session IDs retain their respective data.
240+
$handler2 = $this->getInstance();
241+
$this->assertTrue($handler2->open($this->sessionSavePath, $this->sessionName));
242+
$this->assertSame($oldData, $handler2->read($oldSessionId));
243+
$this->assertTrue($handler2->close());
244+
245+
$this->assertTrue($handler2->open($this->sessionSavePath, $this->sessionName));
246+
$this->assertSame($newData, $handler2->read($newSessionId));
247+
$this->assertTrue($handler2->close());
248+
}
249+
250+
public function testReadDifferentSessionIdsWithoutCloseReleasesPreviousLock(): void
251+
{
252+
$handler = $this->getInstance();
253+
$handler->open($this->sessionSavePath, $this->sessionName);
254+
255+
$firstSessionId = $this->generateSessionId('bbbbbb');
256+
$secondSessionId = $this->generateSessionId('cccccc');
257+
258+
$firstData = '__ci_last_regenerate|i:1664607454;user|s:5:"alice";';
259+
$this->assertSame('', $handler->read($firstSessionId));
260+
$this->assertTrue($handler->write($firstSessionId, $firstData));
261+
$this->assertTrue($handler->close());
262+
263+
// Read two different session IDs on the same handler without closing between them
264+
$this->assertTrue($handler->open($this->sessionSavePath, $this->sessionName));
265+
$this->assertSame($firstData, $handler->read($firstSessionId));
266+
$this->assertSame('', $handler->read($secondSessionId));
267+
268+
// Another handler should be able to acquire the lock for the first session ID
269+
$handler2 = $this->getInstance();
270+
$this->assertTrue($handler2->open($this->sessionSavePath, $this->sessionName));
271+
$this->assertSame($firstData, $handler2->read($firstSessionId));
272+
$this->assertTrue($handler2->close());
273+
274+
$this->assertTrue($handler->close());
275+
}
131276
}

0 commit comments

Comments
 (0)