From 4d1ad42edb2e6b91ca83587a133966823c9b5b56 Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Fri, 20 Nov 2026 18:06:31 +0300 Subject: [PATCH 1/2] feat(session): support Engine 9 and harden payload handling --- .github/workflows/php.yml | 2 +- CHANGELOG.md | 29 +--- README.md | 53 +++++++ README.ru.md | 52 +++++++ composer.json | 6 +- src/Bootstrap.php | 2 +- src/Config/session.php | 2 +- src/Handlers/FileSessionHandler.php | 2 +- src/Handlers/MongoSessionHandler.php | 13 +- src/Handlers/RedisClusterSessionHandler.php | 2 +- src/Handlers/RedisSessionHandler.php | 2 +- src/Install.php | 2 +- src/functions.php | 4 +- tests/session-compatibility.php | 144 ++++++++++++++++++++ 14 files changed, 280 insertions(+), 35 deletions(-) create mode 100644 README.ru.md create mode 100644 tests/session-compatibility.php diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index d521c32..32fc674 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -26,7 +26,7 @@ jobs: uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} - extensions: curl, intl, mbstring, pdo_sqlite + extensions: curl, intl, mbstring, pcntl, pdo_sqlite, posix, sockets tools: composer:v2 github-token: ${{ secrets.GITHUB_TOKEN }} coverage: none diff --git a/CHANGELOG.md b/CHANGELOG.md index c71aa5b..3a17cdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,31 +1,16 @@ # Changelog -All notable changes to this project will be documented in this file. +Notable changes are recorded here. This project follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased -## [1.0.0] - 2025-01-XX - LTS Release +This dependency change requires the next major package release: Engine 9 uses the Server 7 session API, which is not available in the Engine 8.1 / Server 4 dependency graph. ### Added -- Initial LTS release -- Full documentation -- Session management system -- Multiple session drivers (file, redis, database) -- Session encryption -- Session expiration handling -- Flash data support -### Security -- Secure session handling -- Session data encryption +- Compatibility with Triangle Engine 9 and Localzet Server 7. +- A runtime compatibility test for Engine bootstrap, Server session handlers, and file-backed session round trips. ---- - -## [Unreleased] - -### Planned -- Additional session drivers -- Session clustering support -- Performance optimizations +### Changed +- MongoDB session writes disable PHP object instantiation and reject malformed or non-array payloads. diff --git a/README.md b/README.md index 4b71369..73e185e 100644 --- a/README.md +++ b/README.md @@ -19,3 +19,56 @@ Лицензия

+ +# Triangle Session + +Triangle Session connects Engine applications to the HTTP session storage provided by Localzet Server. It includes file, Redis, Redis Cluster and MongoDB handlers and a `session()` helper for the current request. + +## Requirements + +- PHP 8.1 or later +- `triangle/engine` 9.x, which requires Localzet Server 7.1 or later + +## Installation + +```sh +composer require triangle/session +``` + +Engine 9 loads `Triangle\Session\Bootstrap` with its built-in components. This compatibility update is for the next major release because Engine 8.1 resolves to Server 4 and does not provide the Server 7 session API used by this package. To copy the package configuration into an application that does not publish package configuration automatically, run `Triangle\Session\Install::install()` in the application installation context. The default storage driver is `file`; its path comes from `runtime_path('sessions')`. + +## Using a session + +The helper operates on the current request's Server session: + +```php +session(['user_id' => 42]); + +$userId = session('user_id'); +$theme = session('preferences.theme', 'light'); +``` + +The helper returns the current session when called without a key, reads values for string keys, and writes the supplied values when given an array. Session storage is request-scoped by Server; use scalar values and arrays. Objects restored from stored payloads are not instantiated. + +## Storage drivers + +| Driver | Additional requirement | Configuration key | +| --- | --- | --- | +| `file` | Writable runtime directory | `session.config.file` | +| `redis` | PHP Redis extension | `session.config.redis` | +| `redis_cluster` | PHP Redis extension and a configured Redis Cluster | `session.config.redis_cluster` | +| `mongo` | `mongodb/mongodb` and the PHP MongoDB extension | `session.config.mongo` | + +Set `SESSION_TYPE` to the selected driver and provide its connection details through the environment or `config/session.php`. For HTTPS deployments, set `SESSION_COOKIE_SECURE=true`; configure the cookie domain and SameSite policy for the application’s deployment topology. + +## Development checks + +```sh +composer validate --strict --no-check-publish +composer test +composer audit --locked +``` + +The compatibility test exercises Engine bootstrap loading, Server session-handler contracts, file-backed round trips, and safe handling of serialized values. MongoDB and Redis network services are optional and are not started by this test. + +Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved. diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 0000000..c2f711e --- /dev/null +++ b/README.ru.md @@ -0,0 +1,52 @@ +# Triangle Session + +Triangle Session подключает HTTP-сессии Localzet Server к приложениям на Triangle Engine. В пакет входят обработчики для файлов, Redis, Redis Cluster и MongoDB, а также функция `session()` для доступа к сессии текущего запроса. + +## Требования + +- PHP 8.1 или новее +- `triangle/engine` версии 9.x, которая требует Localzet Server 7.1 или новее + +## Установка + +```sh +composer require triangle/session +``` + +Engine 9 запускает `Triangle\Session\Bootstrap` вместе со встроенными компонентами. Это обновление совместимости предназначено для следующей основной версии: Engine 8.1 устанавливает Server 4, в котором нет используемого пакетом API сессий Server 7. Если приложение не публикует конфигурацию пакета автоматически, вызовите `Triangle\Session\Install::install()` в контексте установки приложения. По умолчанию используется файловое хранилище в каталоге `runtime_path('sessions')`. + +## Работа с сессией + +Функция работает с сессией текущего запроса: + +```php +session(['user_id' => 42]); + +$userId = session('user_id'); +$theme = session('preferences.theme', 'light'); +``` + +Вызов без ключа возвращает объект сессии, строковый ключ читает значение, массив записывает несколько значений. Хранилищем и временем жизни запроса управляет Server. Сохраняйте скаляры и массивы: объекты из сохранённого payload не создаются при чтении. + +## Хранилища + +| Драйвер | Дополнительное требование | Ключ конфигурации | +| --- | --- | --- | +| `file` | Доступный для записи каталог runtime | `session.config.file` | +| `redis` | PHP-расширение Redis | `session.config.redis` | +| `redis_cluster` | PHP-расширение Redis и настроенный Redis Cluster | `session.config.redis_cluster` | +| `mongo` | `mongodb/mongodb` и PHP-расширение MongoDB | `session.config.mongo` | + +Укажите драйвер через `SESSION_TYPE`, а параметры подключения задайте в окружении или `config/session.php`. Для HTTPS включите `SESSION_COOKIE_SECURE=true`. Домен cookie и SameSite выберите с учётом схемы размещения приложения. + +## Проверки разработки + +```sh +composer validate --strict --no-check-publish +composer test +composer audit --locked +``` + +Тест совместимости проверяет загрузку Engine bootstrap, контракты обработчиков Server, файловый цикл чтения и записи и безопасную обработку сериализованных значений. MongoDB и Redis не запускаются: сетевые сервисы для теста не требуются. + +Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved. diff --git a/composer.json b/composer.json index b1a7655..5433a3d 100644 --- a/composer.json +++ b/composer.json @@ -31,14 +31,18 @@ }, "require": { "php": "^8.1", - "triangle/engine": "^8.1" + "triangle/engine": "^9.0" }, "suggest": { + "ext-redis": "For RedisSessionHandler and RedisClusterSessionHandler", "mongodb/mongodb": "For MongoSessionHandler" }, "config": { "platform": { "php": "8.1.0" } + }, + "scripts": { + "test": "php tests/session-compatibility.php" } } diff --git a/src/Bootstrap.php b/src/Bootstrap.php index d2b40fc..9156611 100644 --- a/src/Bootstrap.php +++ b/src/Bootstrap.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Session * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Config/session.php b/src/Config/session.php index 6e85825..ee6e376 100644 --- a/src/Config/session.php +++ b/src/Config/session.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Session * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Handlers/FileSessionHandler.php b/src/Handlers/FileSessionHandler.php index baaa121..f574722 100644 --- a/src/Handlers/FileSessionHandler.php +++ b/src/Handlers/FileSessionHandler.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Session * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Handlers/MongoSessionHandler.php b/src/Handlers/MongoSessionHandler.php index 5a06ff0..21a3fa7 100644 --- a/src/Handlers/MongoSessionHandler.php +++ b/src/Handlers/MongoSessionHandler.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Session * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify @@ -111,7 +111,9 @@ public function read(string $sessionId): string { $session = $this->collection->findOne(['_id' => $sessionId]); if ($session !== null) { - return serialize((array)$session); + $data = (array)$session; + unset($data['_id'], $data['updated_at']); + return serialize($data); } return ''; } @@ -121,7 +123,12 @@ public function read(string $sessionId): string */ public function write(string $sessionId, string $sessionData): bool { - $session = ['_id' => $sessionId] + unserialize($sessionData); + $data = @unserialize($sessionData, ['allowed_classes' => false]); + if (!is_array($data)) { + return false; + } + + $session = ['_id' => $sessionId] + $data; $options = ['upsert' => true]; $this->collection->replaceOne(['_id' => $sessionId], $session, $options); $this->updateTimestamp($sessionId); diff --git a/src/Handlers/RedisClusterSessionHandler.php b/src/Handlers/RedisClusterSessionHandler.php index 43ef270..f19dcd8 100644 --- a/src/Handlers/RedisClusterSessionHandler.php +++ b/src/Handlers/RedisClusterSessionHandler.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Session * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Handlers/RedisSessionHandler.php b/src/Handlers/RedisSessionHandler.php index bab780f..7705db5 100644 --- a/src/Handlers/RedisSessionHandler.php +++ b/src/Handlers/RedisSessionHandler.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Session * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/Install.php b/src/Install.php index 4d77dc4..eca94d9 100644 --- a/src/Install.php +++ b/src/Install.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Session * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify diff --git a/src/functions.php b/src/functions.php index 9994d97..136a874 100644 --- a/src/functions.php +++ b/src/functions.php @@ -5,7 +5,7 @@ * @link https://github.com/Triangle-org/Session * * @author Ivan Zorin - * @copyright Copyright (c) 2023-2024 Triangle Framework Team + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 * * This program is free software: you can redistribute it and/or modify @@ -56,4 +56,4 @@ function session(mixed $key = null, mixed $default = null): mixed } return $session->get($key, $default); } -} \ No newline at end of file +} diff --git a/tests/session-compatibility.php b/tests/session-compatibility.php new file mode 100644 index 0000000..3301cf9 --- /dev/null +++ b/tests/session-compatibility.php @@ -0,0 +1,144 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * SPDX-License-Identifier: AGPL-3.0-or-later + * @license AGPL-3.0-or-later + */ + +namespace { + require_once dirname(__DIR__) . '/vendor/autoload.php'; +} + +namespace MongoDB { + if (!class_exists(Client::class)) { + class Client + { + } + + define(__NAMESPACE__ . '\\SESSION_TEST_STUBS', true); + } + + if (!class_exists(Collection::class)) { + class Collection + { + public static ?array $lastReplacement = null; + public static mixed $lastDocument = null; + + public function findOne(array $filter): mixed + { + return self::$lastDocument; + } + + public function replaceOne(array $filter, array $replacement, array $options = []): void + { + self::$lastReplacement = $replacement; + } + + public function updateOne(array $filter, array $update): void + { + } + } + } +} + +namespace MongoDB\BSON { + if (!class_exists(UTCDateTime::class)) { + class UTCDateTime + { + } + } +} + +namespace { + use localzet\Server; + use localzet\Server\Protocols\Http\Session as ServerSession; + use localzet\Server\Protocols\Http\Session\SessionHandlerInterface; + use Triangle\Engine\BootstrapInterface; + use Triangle\Session\Bootstrap; + use Triangle\Session\Handlers\FileSessionHandler; + use Triangle\Session\Handlers\MongoSessionHandler; + use Triangle\Session\Handlers\RedisClusterSessionHandler; + use Triangle\Session\Handlers\RedisSessionHandler; + + final class SessionCompatibilityProbe + { + public static bool $woken = false; + + public function __wakeup(): void + { + self::$woken = true; + } + } + + function expect(bool $condition, string $message): void + { + if (!$condition) { + throw new RuntimeException($message); + } + } + + expect(is_subclass_of(Bootstrap::class, BootstrapInterface::class), 'Session bootstrap must implement the Engine bootstrap contract.'); + Bootstrap::start(new Server()); + + foreach ([FileSessionHandler::class, MongoSessionHandler::class, RedisSessionHandler::class, RedisClusterSessionHandler::class] as $handlerClass) { + expect(is_subclass_of($handlerClass, SessionHandlerInterface::class), "$handlerClass must implement the Server session handler contract."); + } + + $sessionId = 'sessioncompat1234567890'; + $savePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'triangle-session-' . bin2hex(random_bytes(6)); + + try { + ServerSession::handlerClass(FileSessionHandler::class, ['save_path' => $savePath]); + + $session = new ServerSession($sessionId); + $session->put(['user_id' => 41, 'preferences' => ['theme' => 'dark']]); + $session->save(); + + $restored = new ServerSession($sessionId); + expect($restored->get('user_id') === 41, 'Scalar session values must survive a storage round trip.'); + expect($restored->get('preferences') === ['theme' => 'dark'], 'Nested session arrays must survive a storage round trip.'); + + SessionCompatibilityProbe::$woken = false; + ServerSession::handler()->write($sessionId, serialize(['payload' => new SessionCompatibilityProbe()])); + + $untrusted = new ServerSession($sessionId); + expect(!SessionCompatibilityProbe::$woken, 'Session payload objects must not execute wakeup hooks when restored.'); + expect($untrusted->get('payload') instanceof __PHP_Incomplete_Class, 'Objects in restored session data must remain incomplete values.'); + } finally { + ServerSession::handler()->destroy($sessionId); + @rmdir($savePath); + } + + if (defined('MongoDB\\SESSION_TEST_STUBS')) { + $reflection = new ReflectionClass(MongoSessionHandler::class); + $mongoHandler = $reflection->newInstanceWithoutConstructor(); + $collection = new \MongoDB\Collection(); + + $property = $reflection->getProperty('collection'); + $property->setAccessible(true); + $property->setValue($mongoHandler, $collection); + + \MongoDB\Collection::$lastDocument = (object)[ + '_id' => $sessionId, + 'updated_at' => new \MongoDB\BSON\UTCDateTime(), + 'user_id' => 41, + ]; + $storedData = unserialize($mongoHandler->read($sessionId), ['allowed_classes' => false]); + expect($storedData === ['user_id' => 41], 'Mongo storage metadata must not appear in session data.'); + + SessionCompatibilityProbe::$woken = false; + $validPayload = serialize(['name' => 'safe', 'payload' => new SessionCompatibilityProbe()]); + expect($mongoHandler->write($sessionId, $validPayload), 'Mongo session writes should accept serialized arrays.'); + expect(!SessionCompatibilityProbe::$woken, 'Mongo session writes must not instantiate objects from serialized session data.'); + expect(\MongoDB\Collection::$lastReplacement['payload'] instanceof __PHP_Incomplete_Class, 'Mongo session writes must preserve object payloads as incomplete values.'); + + $previousReplacement = \MongoDB\Collection::$lastReplacement; + expect(!$mongoHandler->write($sessionId, 'not a serialized array'), 'Malformed Mongo session payloads must be rejected.'); + expect(\MongoDB\Collection::$lastReplacement === $previousReplacement, 'Rejected Mongo payloads must not mutate storage.'); + } + + echo "SESSION_ENGINE_COMPATIBILITY=ok\n"; +} From bb6e7781ec7bf49277eea59d71ac7af53acd64de Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Sat, 21 Nov 2026 03:16:12 +0300 Subject: [PATCH 2/2] fix!: restore nested MongoDB session arrays --- .github/workflows/php.yml | 36 +++++++++++- CHANGELOG.md | 6 +- README.md | 2 +- README.ru.md | 2 +- composer.json | 7 ++- src/Handlers/MongoSessionHandler.php | 7 ++- tests/mongo-integration.php | 88 ++++++++++++++++++++++++++++ tests/session-compatibility.php | 10 +++- 8 files changed, 147 insertions(+), 11 deletions(-) create mode 100644 tests/mongo-integration.php diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index 32fc674..718f8fe 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -26,7 +26,7 @@ jobs: uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} - extensions: curl, intl, mbstring, pcntl, pdo_sqlite, posix, sockets + extensions: curl, intl, mbstring, mongodb, pcntl, pdo_sqlite, posix, sockets tools: composer:v2 github-token: ${{ secrets.GITHUB_TOKEN }} coverage: none @@ -48,3 +48,37 @@ jobs: else echo 'No test script is declared for this package.' fi + + mongo-integration: + name: MongoDB integration + runs-on: ubuntu-24.04 + services: + mongodb: + image: mongo:7.0 + ports: + - 27017:27017 + options: >- + --health-cmd "mongosh --quiet --eval 'db.adminCommand({ ping: 1 }).ok'" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.5' + extensions: mongodb + tools: composer:v2 + github-token: ${{ secrets.GITHUB_TOKEN }} + coverage: none + + - name: Install dependencies + run: composer install --prefer-dist --no-interaction --no-progress --no-scripts + + - name: Run MongoDB integration test + run: composer test:mongo --no-interaction + env: + MONGODB_URI: mongodb://127.0.0.1:27017 diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a17cdc..3dd506a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,15 +2,17 @@ Notable changes are recorded here. This project follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## Unreleased +## [2.0.0] - Unreleased This dependency change requires the next major package release: Engine 9 uses the Server 7 session API, which is not available in the Engine 8.1 / Server 4 dependency graph. ### Added - Compatibility with Triangle Engine 9 and Localzet Server 7. -- A runtime compatibility test for Engine bootstrap, Server session handlers, and file-backed session round trips. +- Runtime compatibility tests for Engine bootstrap, Server session handlers, and file-backed session round trips. +- A MongoDB integration test for session round trips and persistence behavior. ### Changed - MongoDB session writes disable PHP object instantiation and reject malformed or non-array payloads. +- MongoDB session reads restore BSON documents and arrays as PHP arrays. diff --git a/README.md b/README.md index 73e185e..70e3484 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Triangle Session connects Engine applications to the HTTP session storage provid ## Installation ```sh -composer require triangle/session +composer require triangle/session:^2.0 ``` Engine 9 loads `Triangle\Session\Bootstrap` with its built-in components. This compatibility update is for the next major release because Engine 8.1 resolves to Server 4 and does not provide the Server 7 session API used by this package. To copy the package configuration into an application that does not publish package configuration automatically, run `Triangle\Session\Install::install()` in the application installation context. The default storage driver is `file`; its path comes from `runtime_path('sessions')`. diff --git a/README.ru.md b/README.ru.md index c2f711e..4c101d7 100644 --- a/README.ru.md +++ b/README.ru.md @@ -10,7 +10,7 @@ Triangle Session подключает HTTP-сессии Localzet Server к пр ## Установка ```sh -composer require triangle/session +composer require triangle/session:^2.0 ``` Engine 9 запускает `Triangle\Session\Bootstrap` вместе со встроенными компонентами. Это обновление совместимости предназначено для следующей основной версии: Engine 8.1 устанавливает Server 4, в котором нет используемого пакетом API сессий Server 7. Если приложение не публикует конфигурацию пакета автоматически, вызовите `Triangle\Session\Install::install()` в контексте установки приложения. По умолчанию используется файловое хранилище в каталоге `runtime_path('sessions')`. diff --git a/composer.json b/composer.json index 5433a3d..7dce7a6 100644 --- a/composer.json +++ b/composer.json @@ -33,6 +33,10 @@ "php": "^8.1", "triangle/engine": "^9.0" }, + "require-dev": { + "ext-mongodb": "*", + "mongodb/mongodb": "^2.0" + }, "suggest": { "ext-redis": "For RedisSessionHandler and RedisClusterSessionHandler", "mongodb/mongodb": "For MongoSessionHandler" @@ -43,6 +47,7 @@ } }, "scripts": { - "test": "php tests/session-compatibility.php" + "test": "php tests/session-compatibility.php", + "test:mongo": "php tests/mongo-integration.php" } } diff --git a/src/Handlers/MongoSessionHandler.php b/src/Handlers/MongoSessionHandler.php index 21a3fa7..8fac977 100644 --- a/src/Handlers/MongoSessionHandler.php +++ b/src/Handlers/MongoSessionHandler.php @@ -109,9 +109,12 @@ public function close(): bool */ public function read(string $sessionId): string { - $session = $this->collection->findOne(['_id' => $sessionId]); + $session = $this->collection->findOne( + ['_id' => $sessionId], + ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']], + ); if ($session !== null) { - $data = (array)$session; + $data = $session; unset($data['_id'], $data['updated_at']); return serialize($data); } diff --git a/tests/mongo-integration.php b/tests/mongo-integration.php new file mode 100644 index 0000000..d81e94a --- /dev/null +++ b/tests/mongo-integration.php @@ -0,0 +1,88 @@ + + * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved. + * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * For any questions, please contact + */ + +require_once dirname(__DIR__) . '/vendor/autoload.php'; + +use MongoDB\Client; +use Triangle\Session\Handlers\MongoSessionHandler; + +function expectMongoIntegration(bool $condition, string $message): void +{ + if (!$condition) { + throw new RuntimeException($message); + } +} + +$uri = getenv('MONGODB_URI'); +if ($uri === false || $uri === '') { + throw new RuntimeException('MONGODB_URI must point to a MongoDB integration-test service.'); +} + +if (!extension_loaded('mongodb')) { + throw new RuntimeException('The mongodb PHP extension is required for this integration test.'); +} + +$databaseName = 'triangle_session_test_' . bin2hex(random_bytes(8)); +$collectionName = 'sessions'; +$sessionId = 'sessionmongo' . bin2hex(random_bytes(8)); +$client = new Client($uri, ['serverSelectionTimeoutMS' => 5000]); +$collection = $client->selectCollection($databaseName, $collectionName); +$handler = new MongoSessionHandler([ + 'url' => $uri, + 'database' => $databaseName, + 'collection' => $collectionName, + 'options' => ['serverSelectionTimeoutMS' => 5000], +]); + +try { + $payload = [ + 'user_id' => 41, + 'preferences' => ['theme' => 'dark'], + ]; + + expectMongoIntegration($handler->open('', 'PHPSESSID'), 'Mongo session handler should open.'); + expectMongoIntegration($handler->write($sessionId, serialize($payload)), 'Mongo session handler should write valid serialized arrays.'); + + $document = $collection->findOne(['_id' => $sessionId]); + expectMongoIntegration($document !== null, 'MongoDB should persist the session document.'); + expectMongoIntegration($document->user_id === 41, 'MongoDB should preserve scalar session values.'); + expectMongoIntegration($document->preferences->theme === 'dark', 'MongoDB should preserve nested session values.'); + expectMongoIntegration($document->updated_at instanceof MongoDB\BSON\UTCDateTime, 'MongoDB should persist the update timestamp as BSON UTCDateTime.'); + + $restored = unserialize($handler->read($sessionId), ['allowed_classes' => false]); + expectMongoIntegration($restored === $payload, 'Mongo session data should survive a BSON write/read round trip.'); + + expectMongoIntegration(!$handler->write($sessionId, 'not a serialized array'), 'Malformed session payloads should be rejected.'); + $unchanged = $collection->findOne(['_id' => $sessionId]); + expectMongoIntegration($unchanged->user_id === 41 && $unchanged->preferences->theme === 'dark', 'Rejected payloads must not overwrite stored session data.'); + + expectMongoIntegration($handler->destroy($sessionId), 'Mongo session handler should destroy a session.'); + expectMongoIntegration($collection->findOne(['_id' => $sessionId]) === null, 'Destroyed sessions should be removed from MongoDB.'); +} finally { + $client->dropDatabase($databaseName); +} + +echo "SESSION_MONGODB_INTEGRATION=ok\n"; diff --git a/tests/session-compatibility.php b/tests/session-compatibility.php index 3301cf9..12a9fb1 100644 --- a/tests/session-compatibility.php +++ b/tests/session-compatibility.php @@ -25,10 +25,12 @@ class Client class Collection { public static ?array $lastReplacement = null; + public static ?array $lastOptions = null; public static mixed $lastDocument = null; - public function findOne(array $filter): mixed + public function findOne(array $filter, array $options = []): mixed { + self::$lastOptions = $options; return self::$lastDocument; } @@ -121,13 +123,15 @@ function expect(bool $condition, string $message): void $property->setAccessible(true); $property->setValue($mongoHandler, $collection); - \MongoDB\Collection::$lastDocument = (object)[ + \MongoDB\Collection::$lastDocument = [ '_id' => $sessionId, 'updated_at' => new \MongoDB\BSON\UTCDateTime(), 'user_id' => 41, + 'preferences' => ['theme' => 'dark'], ]; $storedData = unserialize($mongoHandler->read($sessionId), ['allowed_classes' => false]); - expect($storedData === ['user_id' => 41], 'Mongo storage metadata must not appear in session data.'); + expect($storedData === ['user_id' => 41, 'preferences' => ['theme' => 'dark']], 'Mongo session reads must preserve nested arrays without storage metadata.'); + expect(\MongoDB\Collection::$lastOptions['typeMap'] === ['root' => 'array', 'document' => 'array', 'array' => 'array'], 'Mongo session reads must restore BSON documents and arrays as PHP arrays.'); SessionCompatibilityProbe::$woken = false; $validPayload = serialize(['name' => 'safe', 'payload' => new SessionCompatibilityProbe()]);