From 1a4a6db90c0a419fd3795a616fc2fd5698326b37 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Thu, 5 Nov 2026 22:35:11 +0100 Subject: [PATCH 1/2] fix(Session): use query binding for session lock in PostgreHandler --- docs/changelogs/v4.7.7.md | 1 + .../Handlers/Database/PostgreHandler.php | 4 +- .../Database/PostgreHandlerMockConnection.php | 40 ++++++ .../Database/PostgreHandlerMockTest.php | 118 ++++++++++++++++++ 4 files changed, 162 insertions(+), 1 deletion(-) create mode 100644 tests/system/Session/Handlers/Database/PostgreHandlerMockConnection.php create mode 100644 tests/system/Session/Handlers/Database/PostgreHandlerMockTest.php diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index 6623106d9e5e..75acdfd1e670 100644 --- a/docs/changelogs/v4.7.7.md +++ b/docs/changelogs/v4.7.7.md @@ -26,6 +26,7 @@ Release Date: Unreleased - **Images:** Fixed a bug in `ImageMagickHandler::save()` where saving without an extension or with an unsupported extension threw an `ImagickException` instead of falling back to the image's format. - **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. - **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:** `PostgreHandler::lockSession()` and `releaseLock()` now defensively escape session IDs and IP addresses using `BaseConnection::escape()`. - **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. See the repo's [CHANGELOG.md](https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md) for a complete list of bugs fixed. diff --git a/system/Session/Handlers/Database/PostgreHandler.php b/system/Session/Handlers/Database/PostgreHandler.php index d8c6d3c8b794..4f6bac599c77 100644 --- a/system/Session/Handlers/Database/PostgreHandler.php +++ b/system/Session/Handlers/Database/PostgreHandler.php @@ -70,7 +70,9 @@ public function gc($max_lifetime): false|int */ protected function lockSession(string $sessionID): bool { - $arg = "hashtext('{$sessionID}')" . ($this->matchIP ? ", hashtext('{$this->ipAddress}')" : ''); + $arg = 'hashtext(' . $this->db->escape($sessionID) . ')' + . ($this->matchIP ? ', hashtext(' . $this->db->escape($this->ipAddress) . ')' : ''); + if ($this->db->simpleQuery("SELECT pg_advisory_lock({$arg})") !== false) { $this->lock = $arg; diff --git a/tests/system/Session/Handlers/Database/PostgreHandlerMockConnection.php b/tests/system/Session/Handlers/Database/PostgreHandlerMockConnection.php new file mode 100644 index 000000000000..fc45a6414b75 --- /dev/null +++ b/tests/system/Session/Handlers/Database/PostgreHandlerMockConnection.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Session\Handlers\Database; + +use CodeIgniter\Test\Mock\MockConnection; +use CodeIgniter\Test\Mock\MockResult; + +/** + * Mock connection that records the raw SQL passed to simpleQuery(). + * + * PostgreHandler uses simpleQuery() when no bindings are needed, so the + * queries are not bound and must be captured as they are sent to the database. + * + * @internal + */ +final class PostgreHandlerMockConnection extends MockConnection +{ + /** + * @var list + */ + public array $executed = []; + + public function simpleQuery(string $sql): MockResult + { + $this->executed[] = $sql; + + return new MockResult($this->connID, $this->resultID); + } +} diff --git a/tests/system/Session/Handlers/Database/PostgreHandlerMockTest.php b/tests/system/Session/Handlers/Database/PostgreHandlerMockTest.php new file mode 100644 index 000000000000..4ba26829ff99 --- /dev/null +++ b/tests/system/Session/Handlers/Database/PostgreHandlerMockTest.php @@ -0,0 +1,118 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Session\Handlers\Database; + +use CodeIgniter\Events\Events; +use CodeIgniter\Test\CIUnitTestCase; +use CodeIgniter\Test\Mock\MockConnection; +use Config\Session as SessionConfig; +use PHPUnit\Framework\Attributes\Group; + +/** + * @internal + */ +#[Group('Others')] +final class PostgreHandlerMockTest extends CIUnitTestCase +{ + private const IP_ADDRESS = "192.168.1.1' OR '1'='1"; + private const SESSION_ID = "sess'id; DROP TABLE users; --"; + + private function createHandler(bool $matchIP, MockConnection $mockDb): PostgreHandler + { + $config = new SessionConfig(); + $config->driver = PostgreHandler::class; + $config->savePath = 'ci_sessions'; + $config->matchIP = $matchIP; + + $handler = new PostgreHandler($config, self::IP_ADDRESS); + $this->setPrivateProperty($handler, 'db', $mockDb); + + return $handler; + } + + private function createMockDb(): PostgreHandlerMockConnection + { + return new PostgreHandlerMockConnection(['DBDriver' => 'Postgre']); + } + + public function testLockAndReleaseSessionWithoutMatchIP(): void + { + $db = $this->createMockDb(); + $handler = $this->createHandler(false, $db); + + $queryCount = 0; + $listener = static function () use (&$queryCount): void { + $queryCount++; + }; + Events::on('DBQuery', $listener); + + $lockSession = self::getPrivateMethodInvoker($handler, 'lockSession'); + $releaseLock = self::getPrivateMethodInvoker($handler, 'releaseLock'); + + $this->assertTrue($lockSession(self::SESSION_ID)); + $this->assertSame( + "hashtext('sess''id; DROP TABLE users; --')", + self::getPrivateProperty($handler, 'lock'), + ); + + $this->assertTrue($releaseLock()); + $this->assertFalse(self::getPrivateProperty($handler, 'lock')); + + Events::removeListener('DBQuery', $listener); + + $this->assertSame(0, $queryCount); + $this->assertSame([ + "SELECT pg_advisory_lock(hashtext('sess''id; DROP TABLE users; --'))", + "SELECT pg_advisory_unlock(hashtext('sess''id; DROP TABLE users; --'))", + ], $db->executed); + + $this->assertStringNotContainsString(self::SESSION_ID, $db->executed[0]); + $this->assertStringNotContainsString(self::SESSION_ID, $db->executed[1]); + } + + public function testLockAndReleaseSessionWithMatchIP(): void + { + $db = $this->createMockDb(); + $handler = $this->createHandler(true, $db); + + $queryCount = 0; + $listener = static function () use (&$queryCount): void { + $queryCount++; + }; + Events::on('DBQuery', $listener); + + $lockSession = self::getPrivateMethodInvoker($handler, 'lockSession'); + $releaseLock = self::getPrivateMethodInvoker($handler, 'releaseLock'); + + $this->assertTrue($lockSession(self::SESSION_ID)); + $this->assertSame( + "hashtext('sess''id; DROP TABLE users; --'), hashtext('192.168.1.1'' OR ''1''=''1')", + self::getPrivateProperty($handler, 'lock'), + ); + + $this->assertTrue($releaseLock()); + $this->assertFalse(self::getPrivateProperty($handler, 'lock')); + + Events::removeListener('DBQuery', $listener); + + $this->assertSame(0, $queryCount); + $this->assertSame([ + "SELECT pg_advisory_lock(hashtext('sess''id; DROP TABLE users; --'), hashtext('192.168.1.1'' OR ''1''=''1'))", + "SELECT pg_advisory_unlock(hashtext('sess''id; DROP TABLE users; --'), hashtext('192.168.1.1'' OR ''1''=''1'))", + ], $db->executed); + + $this->assertStringNotContainsString(self::SESSION_ID, $db->executed[0]); + $this->assertStringNotContainsString(self::IP_ADDRESS, $db->executed[0]); + } +} From 63f68328307e35b5e60576a392d2bb1a0c12df79 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sat, 14 Nov 2026 23:45:12 +0100 Subject: [PATCH 2/2] docs: move PostgreHandler session escaping note to the Changes section The entry describes defensive escaping, not a fixed bug, so it belongs in the Changes section, as requested in review. --- docs/changelogs/v4.7.7.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index 75acdfd1e670..5aa50a84417d 100644 --- a/docs/changelogs/v4.7.7.md +++ b/docs/changelogs/v4.7.7.md @@ -12,6 +12,8 @@ Release Date: Unreleased ## Changes +- **Session:** Added defensive escaping of session lock arguments in `PostgreHandler`, preserving the existing locking behavior. + ## Deprecations ## Bugs Fixed @@ -26,7 +28,6 @@ Release Date: Unreleased - **Images:** Fixed a bug in `ImageMagickHandler::save()` where saving without an extension or with an unsupported extension threw an `ImagickException` instead of falling back to the image's format. - **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. - **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:** `PostgreHandler::lockSession()` and `releaseLock()` now defensively escape session IDs and IP addresses using `BaseConnection::escape()`. - **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. See the repo's [CHANGELOG.md](https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md) for a complete list of bugs fixed.