From 31532336770eb34402b2764166a89fb895664936 Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Mon, 16 Nov 2026 20:18:29 +0300 Subject: [PATCH 1/6] test(session): verify session user persistence on all storage drivers (#418) Adds SessionDriversTrait, which builds every built-in storage driver (file, in-memory, cache, SQLite, MySQL, MSSQL) for driver-parametrized tests. Database drivers are skipped once per run when unreachable, and pooled connections are closed after each test. SessionUserPersistenceTest checks that setUser() writes the reserved _user key and that the user is restored on resume, on every driver. --- .../Tests/Session/SessionDriversTrait.php | 208 ++++++++++++++++++ .../Session/SessionUserPersistenceTest.php | 92 ++++++++ 2 files changed, 300 insertions(+) create mode 100644 tests/WebFiori/Framework/Tests/Session/SessionDriversTrait.php create mode 100644 tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php diff --git a/tests/WebFiori/Framework/Tests/Session/SessionDriversTrait.php b/tests/WebFiori/Framework/Tests/Session/SessionDriversTrait.php new file mode 100644 index 000000000..b7ed25808 --- /dev/null +++ b/tests/WebFiori/Framework/Tests/Session/SessionDriversTrait.php @@ -0,0 +1,208 @@ + */ + public static array $unavailable = []; +} + +/** + * Creates and cleans up every session storage driver for driver-parametrized + * tests. Drivers that need an external service (MySQL, MSSQL) skip the test + * when the service is not reachable. + * + * Environment overrides: MYSQL_PORT, SQL_SERVER_HOST (for MSSQL a port can be + * given as 'host,port'). + */ +trait SessionDriversTrait { + private string $cacheDir = ''; + private ?DatabaseSessionStorage $dbStorage = null; + /** @var string|ConnectionInfo|null Connection used by the last database driver created. */ + private $dbConnection = null; + private string $sqlitePath = ''; + + public static function storageProvider(): array { + return [ + 'default (file)' => ['default'], + 'in-memory' => ['memory'], + 'cache' => ['cache'], + 'sqlite' => ['sqlite'], + 'mysql' => ['mysql'], + 'mssql' => ['mssql'], + ]; + } + + /** + * Drivers whose garbage collection is driven by a last-use timestamp + * (file mtime or the 'last-used' column). + */ + public static function timestampStorageProvider(): array { + return [ + 'default (file)' => ['default'], + 'sqlite' => ['sqlite'], + 'mysql' => ['mysql'], + 'mssql' => ['mssql'], + ]; + } + + public static function databaseStorageProvider(): array { + return [ + 'sqlite' => ['sqlite'], + 'mysql' => ['mysql'], + 'mssql' => ['mssql'], + ]; + } + + /** + * Moves the last-use time of a session into the past. + */ + private function ageSession(SessionStorage $storage, string $sessionId, int $seconds): void { + $time = time() - $seconds; + + if ($storage instanceof DefaultSessionStorage) { + $m = new \ReflectionMethod($storage, 'filePath'); + $m->setAccessible(true); + touch($m->invoke($storage, $sessionId), $time); + + return; + } + $storage->getController()->table('sessions') + ->update(['last-used' => date('Y-m-d H:i:s', $time)]) + ->where('s-id', $sessionId)->execute(); + } + + /** + * Returns the last-use time of a session as a Unix timestamp. + */ + private function lastUsed(SessionStorage $storage, string $sessionId): int { + if ($storage instanceof DefaultSessionStorage) { + $m = new \ReflectionMethod($storage, 'filePath'); + $m->setAccessible(true); + clearstatcache(); + + return filemtime($m->invoke($storage, $sessionId)); + } + $rows = $storage->getController()->table('sessions')->select() + ->where('s-id', $sessionId)->execute()->getRows(); + + return strtotime($rows[0]['last-used'] ?? $rows[0]['last_used']); + } + + private function sessionExistsInStorage(SessionStorage $storage, string $sessionId): bool { + if ($storage instanceof DefaultSessionStorage) { + return $storage->isStorageFileExist($sessionId); + } + + if ($storage instanceof DatabaseSessionStorage) { + return $storage->getController()->isSessionExist($sessionId); + } + + return $storage->readAll($sessionId) !== []; + } + + private function cleanupDrivers(): void { + if ($this->dbStorage !== null) { + try { + $this->dbStorage->getController()->removeTables(); + } catch (\Throwable $e) { + } + // Close every pooled connection. Leaving them open exhausts the + // pool (max 100) mid-suite, and returning them as idle lets a later + // test reuse a SQLite handle whose database file was deleted. + $this->dbStorage->getController()->close(); + $this->dbStorage = null; + ConnectionPool::reset(); + } + + if ($this->sqlitePath !== '' && file_exists($this->sqlitePath)) { + unlink($this->sqlitePath); + } + + if ($this->cacheDir !== '' && is_dir($this->cacheDir)) { + foreach (glob($this->cacheDir.DIRECTORY_SEPARATOR.'*') as $file) { + if (is_file($file)) { + unlink($file); + } + } + rmdir($this->cacheDir); + } + $this->cacheDir = ''; + $this->sqlitePath = ''; + } + + private function createDbStorage(ConnectionInfo $conn, string $label, bool $register = true): SessionStorage { + if (isset(SessionDriversAvailability::$unavailable[$label])) { + $this->markTestSkipped(SessionDriversAvailability::$unavailable[$label]); + } + + try { + $conn->setName('test-sessions-conn'); + + if ($register) { + App::getConfig()->addOrUpdateDBConnection($conn); + } + $storage = new DatabaseSessionStorage($register ? 'test-sessions-conn' : $conn); + $storage->getController()->removeTables(); + $storage->getController()->createTables(); + $storage->write('probe', 'k', 'probe', null, ConflictStrategy::LAST_WRITE_WINS); + $storage->destroy('probe'); + } catch (\Throwable $e) { + SessionDriversAvailability::$unavailable[$label] = "$label not available: ".$e->getMessage(); + $this->markTestSkipped(SessionDriversAvailability::$unavailable[$label]); + } + $this->dbStorage = $storage; + $this->dbConnection = $register ? 'test-sessions-conn' : $conn; + + return $storage; + } + + private function createStorage(string $driver): SessionStorage { + switch ($driver) { + case 'default': + return new DefaultSessionStorage(); + case 'memory': + return new InMemorySessionStorage(); + case 'cache': + $this->cacheDir = sys_get_temp_dir().DIRECTORY_SEPARATOR.'wf-session-drv-test-'.uniqid(); + mkdir($this->cacheDir, 0755, true); + + return new CacheSessionStorage(new FileStorage($this->cacheDir)); + case 'sqlite': + $this->sqlitePath = sys_get_temp_dir().DIRECTORY_SEPARATOR.'wf_session_drv_'.getmypid().'.db'; + + return $this->createDbStorage(new ConnectionInfo('sqlite', '', '', $this->sqlitePath, ''), 'SQLite', false); + case 'mysql': + $port = getenv('MYSQL_PORT') !== false ? intval(getenv('MYSQL_PORT')) : 3306; + + return $this->createDbStorage( + new ConnectionInfo('mysql', 'root', MYSQL_ROOT_PASSWORD, 'testing_db', '127.0.0.1', $port), + 'MySQL' + ); + case 'mssql': + return $this->createDbStorage( + new ConnectionInfo('mssql', SQL_SERVER_USER, SQL_SERVER_PASS, SQL_SERVER_DB, SQL_SERVER_HOST, 1433, [ + 'TrustServerCertificate' => 'true', + ]), + 'MSSQL' + ); + } + $this->fail("Unknown driver '$driver'."); + } +} diff --git a/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php new file mode 100644 index 000000000..513d76023 --- /dev/null +++ b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php @@ -0,0 +1,92 @@ +createStorage($driver)); + + $name = 'user-resume-'.$driver; + $s1 = new Session(['name' => $name]); + $s1->start(); + $sid = $s1->getId(); + + $user = new User('jane.doe', 'secret', 'jane@example.com'); + $user->setID(42); + $user->setDisplayName('Jane Doe'); + $s1->setUser($user); + $s1->set('cart', ['apple', 'orange']); + + $this->assertNotNull($s1->getUser()); + $s1->close(); + + // A new request resuming the same session. + $s2 = new Session(['name' => $name, 'session-id' => $sid]); + $s2->start(); + + $this->assertSame(['apple', 'orange'], $s2->get('cart'), 'Session variables should survive resume.'); + $this->assertNotNull($s2->getUser(), "Issue #418: user was not restored on resume ($driver)."); + $this->assertEquals(42, $s2->getUser()->getId()); + $this->assertEquals('jane.doe', $s2->getUser()->getUserName()); + $this->assertEquals('jane@example.com', $s2->getUser()->getEmail()); + $this->assertEquals('Jane Doe', $s2->getUser()->getDisplayName()); + } + + /** + * The user must be readable straight from storage under the reserved + * '_user' key right after setUser(), without any close() call. + * + * @test + * @dataProvider storageProvider + */ + public function testSetUserWritesToStorage(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + + $s = new Session(['name' => 'user-write-'.$driver]); + $s->start(); + $this->assertNull($storage->read($s->getId(), '_user')); + + $s->setUser(new User('john', 'pass', 'john@example.com')); + + $this->assertNotNull( + $storage->read($s->getId(), '_user'), + "Issue #418: setUser() did not write '_user' to storage ($driver)." + ); + } + + protected function setUp(): void { + parent::setUp(); + InMemorySessionStorage::reset(); + } + + protected function tearDown(): void { + $this->cleanupDrivers(); + SessionsManager::setStorage(new InMemorySessionStorage()); + parent::tearDown(); + } +} From 2711f4e2cf511e47d27724905368188c6a5a6a6f Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Mon, 16 Nov 2026 20:18:29 +0300 Subject: [PATCH 2/6] feat(session): record session expiry in storage via ExpiringSessionStorage Session now computes each session's expiry (startedAt + duration, or now + duration with refresh) and hands it to storages that implement the new optional ExpiringSessionStorage interface. GC removes sessions whose own expiry has passed, and falls back to the idle threshold for sessions without one. All built-in drivers implement it: - DatabaseSessionStorage: nullable sessions.expires_at column with an index. SessionSchemaMigration::run() adds both. Unmigrated databases keep the old behavior. - DefaultSessionStorage: .exp sidecar file. - CacheSessionStorage: entry TTLs follow the remaining lifetime instead of a fixed 7200 seconds. - InMemorySessionStorage: expiry map; gc() now removes expired sessions. Also fixes: - setDuration() and setIsRefresh() persist _meta on a running session (#431). - Resuming a refresh session extends its stored expiry, at most once a minute (#433). - SESSION_GC is read as an idle period in seconds, not a Unix timestamp (#434). - A missing lifeTime in _meta falls back to 120 minutes, not 2 (#435). - SessionSchemaMigration called a non-existent createIfNotExists() and used ADD COLUMN, which SQL Server rejects. See ADR-0061 in webfiori/docs. Fixes #431 Fixes #432 Fixes #433 Fixes #434 Fixes #435 --- .../Framework/Session/CacheSessionStorage.php | 81 +++++-- .../Session/DatabaseSessionStorage.php | 16 +- .../Session/DefaultSessionStorage.php | 74 +++++- .../Session/ExpiringSessionStorage.php | 59 +++++ .../Session/InMemorySessionStorage.php | 49 +++- WebFiori/Framework/Session/Session.php | 72 +++++- WebFiori/Framework/Session/SessionDB.php | 100 +++++++- WebFiori/Framework/Session/SessionManager.php | 23 +- WebFiori/Framework/Session/SessionSchema.php | 5 + .../Session/SessionSchemaMigration.php | 35 +-- .../Session/ExpiringSessionStorageTest.php | 219 +++++++++++++++++ .../Tests/Session/SessionExpiryTest.php | 228 ++++++++++++++++++ .../Tests/Session/SessionLifetimeBugsTest.php | 201 +++++++++++++++ 13 files changed, 1112 insertions(+), 50 deletions(-) create mode 100644 WebFiori/Framework/Session/ExpiringSessionStorage.php create mode 100644 tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php create mode 100644 tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php create mode 100644 tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php diff --git a/WebFiori/Framework/Session/CacheSessionStorage.php b/WebFiori/Framework/Session/CacheSessionStorage.php index d0b4f09a9..e0c3dd9c8 100644 --- a/WebFiori/Framework/Session/CacheSessionStorage.php +++ b/WebFiori/Framework/Session/CacheSessionStorage.php @@ -29,7 +29,7 @@ * @author Ibrahim * @since 3.1.0 (per-key interface) */ -class CacheSessionStorage implements SessionStorage { +class CacheSessionStorage implements ExpiringSessionStorage { private string $prefix; private Storage $storage; private int $ttl; @@ -51,6 +51,48 @@ public function destroy(string $sessionId): void { } $this->storage->delete($this->indexKey($sessionId)); + $this->storage->delete($this->expiryKey($sessionId)); + } + + /** + * {@inheritdoc} + */ + public function getExpiry(string $sessionId): ?int { + $value = $this->storage->read($this->expiryKey($sessionId), null); + + return is_int($value) ? $value : null; + } + + /** + * {@inheritdoc} + * + * The expiry is enforced through the cache TTL: every entry of the session + * is stored again with a TTL equal to the remaining lifetime, and later + * writes use the same TTL. Clearing the expiry leaves existing entries + * with the TTL they already have. + */ + public function setExpiry(string $sessionId, ?int $expiresAt): void { + if ($expiresAt === null) { + $this->storage->delete($this->expiryKey($sessionId)); + + return; + } + $ttl = max(1, $expiresAt - time()); + $this->storeItem($this->expiryKey($sessionId), $expiresAt, $ttl); + + $keys = $this->readIndex($sessionId); + + foreach ($keys as $key) { + $entry = $this->read($sessionId, $key); + + if ($entry !== null) { + $this->storeItem($this->keyFor($sessionId, $key), $entry, $ttl); + } + } + + if ($keys !== []) { + $this->storeItem($this->indexKey($sessionId), $keys, $ttl); + } } /** @@ -140,31 +182,28 @@ public function write( $entry = ['value' => $value, 'version' => $newVersion]; $cacheKey = $this->keyFor($sessionId, $key); - $item = new Item($cacheKey, $entry, $this->ttl); - $secConfig = new SecurityConfig(); - $secConfig->setEncryptionEnabled(false); - $item->setSecurityConfig($secConfig); - $this->storage->store($item); + $ttl = $this->ttlFor($sessionId); + $this->storeItem($cacheKey, $entry, $ttl); // Update the key index. - $this->addToIndex($sessionId, $key); + $this->addToIndex($sessionId, $key, $ttl); return $newVersion; } - private function addToIndex(string $sessionId, string $key): void { + private function addToIndex(string $sessionId, string $key, int $ttl): void { $keys = $this->readIndex($sessionId); if (!in_array($key, $keys, true)) { $keys[] = $key; - $item = new Item($this->indexKey($sessionId), $keys, $this->ttl); - $secConfig = new SecurityConfig(); - $secConfig->setEncryptionEnabled(false); - $item->setSecurityConfig($secConfig); - $this->storage->store($item); + $this->storeItem($this->indexKey($sessionId), $keys, $ttl); } } + private function expiryKey(string $sessionId): string { + return $this->prefix.$sessionId.':_expires'; + } + private function indexKey(string $sessionId): string { return $this->prefix.$sessionId.':_keys'; } @@ -183,10 +222,24 @@ private function readIndex(string $sessionId): array { private function removeFromIndex(string $sessionId, string $key): void { $keys = $this->readIndex($sessionId); $keys = array_values(array_filter($keys, fn ($k) => $k !== $key)); - $item = new Item($this->indexKey($sessionId), $keys, $this->ttl); + $this->storeItem($this->indexKey($sessionId), $keys, $this->ttlFor($sessionId)); + } + + private function storeItem(string $cacheKey, mixed $data, int $ttl): void { + $item = new Item($cacheKey, $data, $ttl); $secConfig = new SecurityConfig(); $secConfig->setEncryptionEnabled(false); $item->setSecurityConfig($secConfig); $this->storage->store($item); } + + /** + * TTL for new entries of a session: the remaining lifetime if an expiry + * is recorded, the configured default otherwise. + */ + private function ttlFor(string $sessionId): int { + $expiry = $this->getExpiry($sessionId); + + return $expiry === null ? $this->ttl : max(1, $expiry - time()); + } } diff --git a/WebFiori/Framework/Session/DatabaseSessionStorage.php b/WebFiori/Framework/Session/DatabaseSessionStorage.php index 6dd393be3..546988d98 100644 --- a/WebFiori/Framework/Session/DatabaseSessionStorage.php +++ b/WebFiori/Framework/Session/DatabaseSessionStorage.php @@ -27,7 +27,7 @@ * @author Ibrahim * @since 2.1.0 (original), 3.1.0 (per-key interface) */ -class DatabaseSessionStorage implements SessionStorage { +class DatabaseSessionStorage implements ExpiringSessionStorage { private SessionDB $dbController; /** @@ -48,6 +48,20 @@ public function __construct($connection = 'sessions-connection') { } } + /** + * {@inheritdoc} + */ + public function getExpiry(string $sessionId): ?int { + return $this->dbController->getExpiry($sessionId); + } + + /** + * {@inheritdoc} + */ + public function setExpiry(string $sessionId, ?int $expiresAt): void { + $this->dbController->setExpiry($sessionId, $expiresAt); + } + /** * {@inheritdoc} */ diff --git a/WebFiori/Framework/Session/DefaultSessionStorage.php b/WebFiori/Framework/Session/DefaultSessionStorage.php index cb36adfc5..412a7c892 100644 --- a/WebFiori/Framework/Session/DefaultSessionStorage.php +++ b/WebFiori/Framework/Session/DefaultSessionStorage.php @@ -34,7 +34,8 @@ * @author Ibrahim * @since 3.1.0 (per-key interface) */ -class DefaultSessionStorage implements SessionStorage { +class DefaultSessionStorage implements ExpiringSessionStorage { + private const EXPIRY_SUFFIX = '.exp'; private string $storeLoc; public function __construct() { @@ -68,6 +69,47 @@ public function destroy(string $sessionId): void { if (file_exists($path)) { unlink($path); } + $expiryPath = $this->expiryPath($sessionId); + + if (file_exists($expiryPath)) { + unlink($expiryPath); + } + } + + /** + * {@inheritdoc} + * + * The expiry is kept in a sidecar file next to the session file, because + * the modification time of the session file changes on every write. + */ + public function getExpiry(string $sessionId): ?int { + $path = $this->expiryPath($sessionId); + + if (!file_exists($path)) { + return null; + } + $raw = @file_get_contents($path); + + return $raw !== false && ctype_digit(trim($raw)) ? (int) trim($raw) : null; + } + + /** + * {@inheritdoc} + */ + public function setExpiry(string $sessionId, ?int $expiresAt): void { + if (!$this->canWrite()) { + return; + } + $path = $this->expiryPath($sessionId); + + if ($expiresAt === null) { + if (file_exists($path)) { + unlink($path); + } + + return; + } + file_put_contents($path, (string) $expiresAt, LOCK_EX); } /** @@ -81,17 +123,35 @@ public function gc(string $olderThan, int $maxCount = 0): void { $files = array_diff(scandir($this->storeLoc), ['.', '..']); $removed = 0; $threshold = strtotime($olderThan); + $now = time(); foreach ($files as $file) { + $filePath = $this->storeLoc.DS.$file; + + if (substr($file, -strlen(self::EXPIRY_SUFFIX)) === self::EXPIRY_SUFFIX) { + // Remove expiry files whose session file is gone. + if (!file_exists(substr($filePath, 0, -strlen(self::EXPIRY_SUFFIX))) && file_exists($filePath)) { + unlink($filePath); + } + + continue; + } + if ($maxCount > 0 && $removed >= $maxCount) { break; } - $filePath = $this->storeLoc.DS.$file; - $mtime = filemtime($filePath); + $expiry = $this->getExpiry($file); - if ($mtime !== false && $mtime < $threshold) { - unlink($filePath); + if ($expiry !== null) { + $expired = $expiry <= $now; + } else { + $mtime = filemtime($filePath); + $expired = $mtime !== false && $mtime < $threshold; + } + + if ($expired) { + $this->destroy($file); $removed++; } } @@ -272,6 +332,10 @@ private function decode(string $raw, string $sessionId): array { return []; } + private function expiryPath(string $sessionId): string { + return $this->filePath($sessionId).self::EXPIRY_SUFFIX; + } + private function filePath(string $sessionId): string { return $this->storeLoc.DS.$sessionId; } diff --git a/WebFiori/Framework/Session/ExpiringSessionStorage.php b/WebFiori/Framework/Session/ExpiringSessionStorage.php new file mode 100644 index 000000000..433f1a8b7 --- /dev/null +++ b/WebFiori/Framework/Session/ExpiringSessionStorage.php @@ -0,0 +1,59 @@ + [value, version]. * @@ -36,20 +36,60 @@ class InMemorySessionStorage implements SessionStorage { */ private static array $store = []; + /** + * Recorded expiry times keyed by session id. + * + * @var array + */ + private static array $expiry = []; + /** * Destroys an entire session, removing all its keys. * * @param string $sessionId The session identifier. */ public function destroy(string $sessionId): void { - unset(self::$store[$sessionId]); + unset(self::$store[$sessionId], self::$expiry[$sessionId]); } /** - * No-op for in-memory storage (no TTL tracking). + * Removes sessions whose recorded expiry has passed. + * + * In-memory storage does not track idle time, so sessions without a + * recorded expiry are never removed. */ public function gc(string $olderThan, int $maxCount = 0): void { - // In-memory storage has no concept of expiry; GC is a no-op. + $now = time(); + $removed = 0; + + foreach (self::$expiry as $sessionId => $expiresAt) { + if ($maxCount > 0 && $removed >= $maxCount) { + break; + } + + if ($expiresAt <= $now) { + $this->destroy($sessionId); + $removed++; + } + } + } + + /** + * {@inheritdoc} + */ + public function getExpiry(string $sessionId): ?int { + return self::$expiry[$sessionId] ?? null; + } + + /** + * {@inheritdoc} + */ + public function setExpiry(string $sessionId, ?int $expiresAt): void { + if ($expiresAt === null) { + unset(self::$expiry[$sessionId]); + } else { + self::$expiry[$sessionId] = $expiresAt; + } } /** @@ -92,6 +132,7 @@ public function remove(string $sessionId, string $key): void { */ public static function reset(): void { self::$store = []; + self::$expiry = []; } /** diff --git a/WebFiori/Framework/Session/Session.php b/WebFiori/Framework/Session/Session.php index 9c98b9aae..a1f992c66 100644 --- a/WebFiori/Framework/Session/Session.php +++ b/WebFiori/Framework/Session/Session.php @@ -32,6 +32,13 @@ class Session implements JsonI { */ const DEFAULT_SESSION_DURATION = 120; + /** + * Minimum drift, in seconds, before the stored expiry of a resumed session + * is rewritten. Avoids a storage write on every request of a session that + * has refresh enabled. + */ + private const EXPIRY_REFRESH_INTERVAL = 60; + /** * Storage keys that are reserved for internal session use. * @@ -801,6 +808,10 @@ public function setDuration(float $time) : bool { $this->sessionCookie->setExpires($asFloat); $this->checkIfExpired(); + if ($this->isRunning()) { + $this->persistMeta(); + } + return true; } @@ -816,6 +827,10 @@ public function setDuration(float $time) : bool { */ public function setIsRefresh(bool $bool) { $this->isRef = $bool === true; + + if ($this->isRunning()) { + $this->persistMeta(); + } } /** * Sets the read strategy for this session. @@ -883,7 +898,7 @@ public function start() { } $this->startedAt = $meta['startedAt'] ?? time(); - $this->lifeTime = $meta['lifeTime'] ?? self::DEFAULT_SESSION_DURATION / 60; + $this->lifeTime = $meta['lifeTime'] ?? self::DEFAULT_SESSION_DURATION; $this->isRef = $meta['isRef'] ?? false; $this->langCode = $meta['langCode'] ?? ''; $this->resumedAt = time(); @@ -908,6 +923,10 @@ public function start() { } $this->checkIfExpired(); + + if ($this->sessionStatus === SessionStatus::RESUMED) { + $this->refreshExpiry(); + } } } } @@ -1199,6 +1218,57 @@ private function persistMeta(): void { null, ConflictStrategy::LAST_WRITE_WINS ); + $this->syncExpiry(); + } + /** + * Returns the time at which the session expires, as a Unix timestamp. + * + * Sessions with refresh enabled expire one full duration after now. Other + * sessions expire one full duration after they started. + * + * @return int|null Null if the session is not persistent (no lifetime). + */ + private function computeExpiry(): ?int { + if (!$this->isPersistent()) { + return null; + } + + return ($this->isRefresh() ? time() : $this->startedAt) + $this->getDuration(); + } + /** + * Records the expiry time in storage, if the storage supports it. + */ + private function syncExpiry(): void { + $storage = SessionsManager::getStorage(); + + if ($storage instanceof ExpiringSessionStorage) { + $storage->setExpiry($this->getId(), $this->computeExpiry()); + } + } + /** + * Updates the stored expiry of a resumed session. + * + * The write happens when no expiry is recorded yet (session created + * before expiry tracking existed) or when the recorded value drifts from + * the computed one by more than EXPIRY_REFRESH_INTERVAL seconds, which only + * happens for sessions with refresh enabled. + */ + private function refreshExpiry(): void { + $storage = SessionsManager::getStorage(); + + if (!$storage instanceof ExpiringSessionStorage) { + return; + } + $target = $this->computeExpiry(); + $current = $storage->getExpiry($this->getId()); + + if ($target === null) { + if ($current !== null) { + $storage->setExpiry($this->getId(), null); + } + } else if ($current === null || abs($target - $current) > self::EXPIRY_REFRESH_INTERVAL) { + $storage->setExpiry($this->getId(), $target); + } } /** * Persists the current session user to the reserved '_user' key. diff --git a/WebFiori/Framework/Session/SessionDB.php b/WebFiori/Framework/Session/SessionDB.php index 2906329ff..9e249dfde 100644 --- a/WebFiori/Framework/Session/SessionDB.php +++ b/WebFiori/Framework/Session/SessionDB.php @@ -55,6 +55,19 @@ public function __construct($connection = 'sessions-connection') { public function createTables(): void { // Use the parent DB class createTables() which creates all registered tables. parent::createTables(); + $this->createExpiryIndex(); + } + /** + * Creates the index on 'sessions.expires_at' that makes expiry-based + * garbage collection a range scan. Safe to call more than once. + */ + public function createExpiryIndex(): void { + try { + $this->raw('CREATE INDEX idx_sessions_expires_at ON sessions (expires_at)')->execute(); + } catch (\Throwable $e) { + // Index already exists, or the column has not been migrated yet. + } + $this->clear(); } /** * Drops all session-related tables. @@ -68,7 +81,11 @@ public function dropAllTables(): void { $this->table('sessions')->drop()->execute(); } /** - * Clears the sessions which are older than the given date. + * Removes expired sessions. + * + * A session with a recorded expiry is removed once that expiry has passed. + * A session without one is removed when its last use is at or before + * $olderThan. * * @param string $olderThan A date-time string in the format 'YYYY-MM-DD HH:MM:SS'. * @param int $maxCount Maximum number of sessions to remove. 0 means no limit. @@ -77,7 +94,7 @@ public function dropAllTables(): void { * @since 2.0 */ public function gc(string $olderThan, int $maxCount = 0) { - $ids = $this->getSessionsIDs($olderThan); + $ids = $this->getExpiredSessionsIDs(date('Y-m-d H:i:s'), $olderThan); if ($maxCount > 0) { $ids = array_slice($ids, 0, $maxCount); @@ -193,6 +210,85 @@ public function getSessionKeys(string $sId): array { return $result; } + /** + * Returns the recorded expiry time of a session. + * + * @param string $sId The ID of the session. + * + * @return int|null A Unix timestamp, or null if no expiry is recorded, the + * session does not exist, or the 'expires_at' column has not been migrated. + */ + public function getExpiry(string $sId): ?int { + try { + $rows = $this->table('sessions')->select()->where('s-id', $sId)->execute()->getRows(); + } catch (DatabaseException $e) { + return null; + } + + if (count($rows) === 0) { + return null; + } + $value = $rows[0]['expires-at'] ?? $rows[0]['expires_at'] ?? null; + + if ($value === null || $value === '') { + return null; + } + $time = strtotime((string) $value); + + return $time === false ? null : $time; + } + /** + * Returns the IDs of sessions that should be garbage-collected. + * + * @param string $now The current time as 'YYYY-MM-DD HH:MM:SS'. Sessions + * whose recorded expiry is at or before this time are returned. + * @param string $idleOlderThan Sessions with NO recorded expiry are + * returned if their last use is at or before this time. + * + * @return array + * + * @throws DatabaseException + */ + public function getExpiredSessionsIDs(string $now, string $idleOlderThan): array { + $mapId = function ($record) + { + return $record['s-id'] ?? $record['s_id'] ?? null; + }; + + try { + $expired = $this->table('sessions')->select() + ->where('expires-at', $now, '<=')->execute()->map($mapId)->toArray(); + $legacy = $this->table('sessions')->select() + ->where('last-used', $idleOlderThan, '<=')->whereNull('expires-at') + ->execute()->map($mapId)->toArray(); + } catch (DatabaseException $e) { + // The 'expires_at' column does not exist yet (schema not migrated): + // behave as before and use the idle threshold for every session. + $this->clear(); + + return $this->getSessionsIDs($idleOlderThan); + } + + return array_values(array_unique(array_merge($expired, $legacy))); + } + /** + * Records the time at which a session expires. + * + * Does nothing if the session row does not exist or the 'expires_at' + * column has not been migrated. + * + * @param string $sId The ID of the session. + * @param int|null $expiresAt A Unix timestamp, or null to clear. + */ + public function setExpiry(string $sId, ?int $expiresAt): void { + try { + $this->table('sessions')->update([ + 'expires-at' => $expiresAt === null ? null : date('Y-m-d H:i:s', $expiresAt), + ])->where('s-id', $sId)->execute(); + } catch (DatabaseException $e) { + $this->clear(); + } + } /** * Returns an array that holds the IDs of sessions which are older than * specific date and time. diff --git a/WebFiori/Framework/Session/SessionManager.php b/WebFiori/Framework/Session/SessionManager.php index d21a731f1..73cd36393 100644 --- a/WebFiori/Framework/Session/SessionManager.php +++ b/WebFiori/Framework/Session/SessionManager.php @@ -152,22 +152,31 @@ public function getGCProbability(): int { return $this->gcProbability; } /** - * Returns a date string that represents the GC threshold time. + * Returns a date string that represents the GC idle threshold. + * + * Sessions that have no recorded expiry (see {@see ExpiringSessionStorage}) + * are removed when they were last used at or before this time. + * + * The threshold is the current time minus an idle period. The period is + * 4 hours by default and can be changed with the 'SESSION_GC' environment + * variable or constant, whose value is a DURATION IN SECONDS (for example + * 604800 for one week). Versions before 3.2.0 read the value as an + * absolute Unix timestamp, which could not express a useful setting. * * @return string A date string in the format 'Y-m-d H:i:s'. */ public function getGCTime(): string { - $olderThan = time() - (Session::DEFAULT_SESSION_DURATION * 60 * 2); + $idleSeconds = Session::DEFAULT_SESSION_DURATION * 60 * 2; $fromEnv = getenv('SESSION_GC') !== false ? intval(getenv('SESSION_GC')) : 0; $fromConst = defined('SESSION_GC') && intval(SESSION_GC) > 0 ? intval(SESSION_GC) : 0; - if ($fromEnv != 0) { - $olderThan = $fromEnv; - } else if ($fromConst != 0) { - $olderThan = $fromConst; + if ($fromEnv > 0) { + $idleSeconds = $fromEnv; + } else if ($fromConst > 0) { + $idleSeconds = $fromConst; } - return date('Y-m-d H:i:s', $olderThan); + return date('Y-m-d H:i:s', time() - $idleSeconds); } /** * Returns the ID of a session from a cookie given its name. diff --git a/WebFiori/Framework/Session/SessionSchema.php b/WebFiori/Framework/Session/SessionSchema.php index a5af84fcb..34e137068 100644 --- a/WebFiori/Framework/Session/SessionSchema.php +++ b/WebFiori/Framework/Session/SessionSchema.php @@ -137,6 +137,11 @@ public static function createSessionsTable(string $dbType): Table { 'default' => 'now()', 'comment' => 'The date and time at which the user had activity during the session.', ], + 'expires_at' => [ + 'type' => 'datetime', + 'is-null' => true, + 'comment' => 'The date and time at which the session expires. Null if not recorded.', + ], ]); } } diff --git a/WebFiori/Framework/Session/SessionSchemaMigration.php b/WebFiori/Framework/Session/SessionSchemaMigration.php index 3df9f2ea4..5dd2df374 100644 --- a/WebFiori/Framework/Session/SessionSchemaMigration.php +++ b/WebFiori/Framework/Session/SessionSchemaMigration.php @@ -31,6 +31,10 @@ * if it does not exist. * 3. Adds a 'version' column to 'session_kv_data' if it is missing. * 4. Adds an 'updated_at' column to 'session_kv_data' if it is missing. + * 5. Adds a nullable 'expires_at' column (and an index on it) to 'sessions' + * if it is missing. Garbage collection uses it to remove sessions by their + * own expiry time (see {@see ExpiringSessionStorage}). Until the migration + * is run, garbage collection falls back to the idle-time threshold. * * The legacy 'session_data' table (chunked blob) is NOT modified or removed; * existing sessions stored in the blob format will be treated as new sessions @@ -52,22 +56,14 @@ public static function run(string|ConnectionInfo $connection = 'sessions-connect $db = new SessionDB($connection); $dbType = strtolower($db->getConnectionInfo()->getDatabaseType()); - // Create sessions table if not exists. - try { - $db->table('sessions')->createIfNotExists()->execute(); - } catch (DatabaseException $e) { - // Table may already exist; continue. - } - - // Create session_kv_data table if not exists. - try { - $db->table('session_kv_data')->createIfNotExists()->execute(); - } catch (DatabaseException $e) { - // May fail if CREATE IF NOT EXISTS is not supported; try plain CREATE. + // Create the tables if they do not exist. createTable() fails when a + // table already exists, which is the expected case on re-runs. + foreach (['sessions', 'session_kv_data'] as $tableName) { try { - $db->table('session_kv_data')->create()->execute(); - } catch (DatabaseException $innerEx) { - // Table already exists — run column-level migrations. + $db->table($tableName)->createTable()->execute(); + } catch (DatabaseException $e) { + // Table already exists; continue with column-level migrations. + $db->clear(); } } @@ -77,6 +73,10 @@ public static function run(string|ConnectionInfo $connection = 'sessions-connect // Add 'updated_at' column if missing. $updatedAtType = ($dbType === 'mssql') ? 'DATETIME DEFAULT GETDATE()' : 'DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP'; static::addColumnIfMissing($db, $dbType, 'session_kv_data', 'updated_at', $updatedAtType); + + // Add 'expires_at' column and its index to 'sessions' if missing. + static::addColumnIfMissing($db, $dbType, 'sessions', 'expires_at', 'DATETIME NULL'); + $db->createExpiryIndex(); } private static function addColumnIfMissing( @@ -87,9 +87,12 @@ private static function addColumnIfMissing( string $definition ): void { try { - $db->query("ALTER TABLE $table ADD COLUMN $column $definition")->execute(); + // SQL Server does not accept the COLUMN keyword in ADD. + $keyword = $dbType === 'mssql' ? 'ADD' : 'ADD COLUMN'; + $db->raw("ALTER TABLE $table $keyword $column $definition")->execute(); } catch (DatabaseException $e) { // Column likely already exists — ignore. + $db->clear(); } } } diff --git a/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php b/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php new file mode 100644 index 000000000..98669df64 --- /dev/null +++ b/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php @@ -0,0 +1,219 @@ +assertInstanceOf(ExpiringSessionStorage::class, $this->createStorage($driver)); + } + + /** + * @test + * @dataProvider storageProvider + */ + public function testDestroyClearsExpiry(string $driver) { + $storage = $this->createStorage($driver); + $this->write($storage, 'destroy-me'); + $storage->setExpiry('destroy-me', time() + 3600); + + $storage->destroy('destroy-me'); + + $this->assertNull($storage->getExpiry('destroy-me')); + } + + /** + * @test + * @dataProvider storageProvider + */ + public function testExpiryRoundTrip(string $driver) { + $storage = $this->createStorage($driver); + $this->write($storage, 'round-trip'); + $this->assertNull($storage->getExpiry('round-trip'), 'A new session has no recorded expiry.'); + + $at = time() + 3600; + $storage->setExpiry('round-trip', $at); + $this->assertSame($at, $storage->getExpiry('round-trip')); + + $storage->setExpiry('round-trip', $at + 100); + $this->assertSame($at + 100, $storage->getExpiry('round-trip'), 'A later call replaces the expiry.'); + + $storage->setExpiry('round-trip', null); + $this->assertNull($storage->getExpiry('round-trip'), 'Null clears the expiry.'); + } + + /** + * Writing to a session after its expiry was recorded must not lose the + * expiry or the data. + * + * @test + * @dataProvider storageProvider + */ + public function testExpirySurvivesLaterWrites(string $driver) { + $storage = $this->createStorage($driver); + $this->write($storage, 'later-writes'); + $at = time() + 3600; + $storage->setExpiry('later-writes', $at); + + $storage->write('later-writes', 'more', 'data', null, ConflictStrategy::LAST_WRITE_WINS); + + $this->assertSame($at, $storage->getExpiry('later-writes')); + $this->assertEquals('data', $storage->read('later-writes', 'more')['value']); + $this->assertEquals('v', $storage->read('later-writes', 'k')['value']); + } + + /** + * Sessions that have an expiry are removed by gc() only once it passed, + * whatever the idle threshold says. + * + * @test + * @dataProvider storageProvider + */ + public function testGcUsesRecordedExpiry(string $driver) { + $storage = $this->createStorage($driver); + $this->write($storage, 'expired'); + $this->write($storage, 'alive'); + $this->expireSession($driver, $storage, 'expired'); + $storage->setExpiry('alive', time() + 3600); + + // An idle threshold in the far future would delete every session + // that has no expiry. 'alive' has one, so it must stay. + $storage->gc(date('Y-m-d H:i:s', time() + 86400)); + + $this->assertFalse($this->sessionExistsInStorage($storage, 'expired'), 'Expired session should be removed.'); + $this->assertTrue($this->sessionExistsInStorage($storage, 'alive'), 'Unexpired session should be kept.'); + } + + /** + * Sessions without a recorded expiry (created before upgrade, or with a + * non-persistent lifetime) keep being removed by the idle threshold. + * + * @test + * @dataProvider timestampStorageProvider + */ + public function testGcFallsBackToIdleThresholdWithoutExpiry(string $driver) { + $storage = $this->createStorage($driver); + $this->write($storage, 'idle'); + $this->write($storage, 'fresh'); + $this->ageSession($storage, 'idle', 5 * 3600); + + $storage->gc(date('Y-m-d H:i:s', time() - 4 * 3600)); + + $this->assertFalse($this->sessionExistsInStorage($storage, 'idle')); + $this->assertTrue($this->sessionExistsInStorage($storage, 'fresh')); + } + + /** + * @test + * @dataProvider storageProvider + */ + public function testGcRespectsMaxCount(string $driver) { + if ($driver === 'cache') { + $this->markTestSkipped('The cache driver delegates expiry to cache TTLs; gc() has no count to limit.'); + } + $storage = $this->createStorage($driver); + + foreach (['a', 'b', 'c'] as $id) { + $this->write($storage, 'max-'.$id); + $this->expireSession($driver, $storage, 'max-'.$id); + } + + $storage->gc(date('Y-m-d H:i:s', time() - 86400), 2); + + $left = 0; + + foreach (['a', 'b', 'c'] as $id) { + $left += $this->sessionExistsInStorage($storage, 'max-'.$id) ? 1 : 0; + } + $this->assertSame(1, $left); + } + + /** + * A database whose 'sessions' table has no 'expires_at' column yet (not + * migrated) must keep working with idle-threshold GC, and the migration + * must add the column. + * + * @test + * @dataProvider databaseStorageProvider + */ + public function testUnmigratedDatabaseDegradesAndMigrationAddsColumn(string $driver) { + $storage = $this->createStorage($driver); + + // Turn the table into the pre-upgrade shape. + $db = $storage->getController(); + $dropIndex = $driver === 'sqlite' + ? 'DROP INDEX IF EXISTS idx_sessions_expires_at' + : 'DROP INDEX idx_sessions_expires_at ON sessions'; + $db->raw($dropIndex)->execute(); + $db->raw('ALTER TABLE sessions DROP COLUMN expires_at')->execute(); + + $this->write($storage, 'old-idle'); + $this->write($storage, 'old-fresh'); + $this->ageSession($storage, 'old-idle', 5 * 3600); + + $storage->setExpiry('old-fresh', time() + 3600); + $this->assertNull($storage->getExpiry('old-fresh'), 'Without the column no expiry can be recorded.'); + + $storage->gc(date('Y-m-d H:i:s', time() - 4 * 3600)); + $this->assertFalse($this->sessionExistsInStorage($storage, 'old-idle')); + $this->assertTrue($this->sessionExistsInStorage($storage, 'old-fresh')); + + SessionSchemaMigration::run($this->dbConnection); + + $at = time() + 3600; + $storage->setExpiry('old-fresh', $at); + $this->assertSame($at, $storage->getExpiry('old-fresh'), 'After the migration expiry can be recorded.'); + + // Running the migration twice is harmless. + SessionSchemaMigration::run($this->dbConnection); + $this->assertSame($at, $storage->getExpiry('old-fresh')); + } + + protected function setUp(): void { + parent::setUp(); + InMemorySessionStorage::reset(); + } + + protected function tearDown(): void { + $this->cleanupDrivers(); + parent::tearDown(); + } + + /** + * Makes a session's recorded expiry a time in the past. The cache driver + * enforces expiry through TTLs, so the test waits for the 1 second TTL to + * lapse. + */ + private function expireSession(string $driver, ExpiringSessionStorage $storage, string $sessionId): void { + $storage->setExpiry($sessionId, time() - 10); + + if ($driver === 'cache') { + sleep(2); + } + } + + private function write(ExpiringSessionStorage $storage, string $sessionId): void { + $storage->write($sessionId, 'k', 'v', null, ConflictStrategy::LAST_WRITE_WINS); + } +} diff --git a/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php b/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php new file mode 100644 index 000000000..9e6f015cc --- /dev/null +++ b/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php @@ -0,0 +1,228 @@ +inner->destroy($sessionId); + } + public function gc(string $olderThan, int $maxCount = 0): void { + $this->inner->gc($olderThan, $maxCount); + } + public function read(string $sessionId, string $key): ?array { + return $this->inner->read($sessionId, $key); + } + public function readAll(string $sessionId): array { + return $this->inner->readAll($sessionId); + } + public function remove(string $sessionId, string $key): void { + $this->inner->remove($sessionId, $key); + } + public function write(string $sessionId, string $key, mixed $value, string|int|null $expectedVersion, ConflictStrategy $strategy): string|int { + return $this->inner->write($sessionId, $key, $value, $expectedVersion, $strategy); + } + }; + SessionsManager::setStorage($plain); + + $s = new Session(['name' => 'plain-storage', 'duration' => 60, 'refresh' => true]); + $s->start(); + $s->set('k', 'v'); + $s->setDuration(120); + $s->close(); + + $r = new Session(['name' => 'plain-storage', 'session-id' => $s->getId()]); + $r->start(); + $this->assertEquals(SessionStatus::RESUMED, $r->getStatus()); + $this->assertEquals('v', $r->get('k')); + $this->assertEquals(7200, $r->getDuration()); + } + + /** + * A session with refresh expires one full duration after its latest write + * of metadata, not after it started. + * + * @test + * @dataProvider storageProvider + */ + public function testNewRefreshSessionExpiresOneDurationFromNow(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + + $s = new Session(['name' => 'exp-refresh-'.$driver, 'duration' => 30, 'refresh' => true]); + $s->start(); + + $this->assertEqualsWithDelta(time() + 1800, $storage->getExpiry($s->getId()), 5); + } + + /** + * A session without refresh expires one duration after it started. + * + * @test + * @dataProvider storageProvider + */ + public function testNewSessionExpiresOneDurationAfterStart(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + + $s = new Session(['name' => 'exp-new-'.$driver, 'duration' => 30]); + $s->start(); + + $this->assertEqualsWithDelta($s->getStartedAt() + 1800, $storage->getExpiry($s->getId()), 2); + } + + /** + * A session with duration 0 has no lifetime to enforce, so no expiry is + * recorded and it stays subject to the idle threshold. + * + * @test + * @dataProvider storageProvider + */ + public function testNonPersistentSessionHasNoExpiry(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + + $s = new Session(['name' => 'exp-none-'.$driver, 'duration' => 30]); + $s->start(); + $this->assertNotNull($storage->getExpiry($s->getId())); + + $s->setDuration(0); + + $this->assertNull($storage->getExpiry($s->getId())); + } + + /** + * A session created before expiry tracking existed has no recorded + * expiry. Resuming it records one. + * + * @test + * @dataProvider storageProvider + */ + public function testResumeRecordsMissingExpiry(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + + $s = new Session(['name' => 'exp-legacy-'.$driver, 'duration' => 30]); + $s->start(); + $sid = $s->getId(); + $storage->setExpiry($sid, null); + + $r = new Session(['name' => 'exp-legacy-'.$driver, 'session-id' => $sid]); + $r->start(); + + $this->assertEqualsWithDelta($r->getStartedAt() + 1800, $storage->getExpiry($sid), 2); + } + + /** + * Resuming a session with refresh enabled moves its expiry forward, but + * only when it drifted by more than a minute, to avoid a write on every + * request. + * + * @test + * @dataProvider storageProvider + */ + public function testResumeRefreshesExpiryOnlyWhenDriftExceedsOneMinute(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + $name = 'exp-throttle-'.$driver; + + $s = new Session(['name' => $name, 'duration' => 30, 'refresh' => true]); + $s->start(); + $sid = $s->getId(); + + // 20 seconds of drift: below the threshold, the stored value is kept. + $recent = time() + 1800 - 20; + $storage->setExpiry($sid, $recent); + (new Session(['name' => $name, 'session-id' => $sid]))->start(); + $this->assertSame($recent, $storage->getExpiry($sid)); + + // 10 minutes of drift: the stored value moves forward. + $storage->setExpiry($sid, time() + 1800 - 600); + (new Session(['name' => $name, 'session-id' => $sid]))->start(); + $this->assertEqualsWithDelta(time() + 1800, $storage->getExpiry($sid), 5); + } + + /** + * A session without refresh keeps its original expiry when resumed. + * + * @test + * @dataProvider storageProvider + */ + public function testResumeKeepsExpiryOfNonRefreshSession(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + $name = 'exp-keep-'.$driver; + + $s = new Session(['name' => $name, 'duration' => 30]); + $s->start(); + $sid = $s->getId(); + $before = $storage->getExpiry($sid); + + (new Session(['name' => $name, 'session-id' => $sid]))->start(); + + $this->assertSame($before, $storage->getExpiry($sid)); + } + + /** + * setDuration() and setIsRefresh() on a running session update the + * recorded expiry (issue #431). + * + * @test + * @dataProvider storageProvider + */ + public function testSetDurationAndRefreshUpdateRecordedExpiry(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + + $s = new Session(['name' => 'exp-set-'.$driver, 'duration' => 30]); + $s->start(); + $sid = $s->getId(); + + $s->setDuration(60); + $this->assertEqualsWithDelta($s->getStartedAt() + 3600, $storage->getExpiry($sid), 2); + + $s->setIsRefresh(true); + $this->assertEqualsWithDelta(time() + 3600, $storage->getExpiry($sid), 5); + } + + protected function setUp(): void { + parent::setUp(); + InMemorySessionStorage::reset(); + SessionsManager::reset(); + } + + protected function tearDown(): void { + $this->cleanupDrivers(); + SessionsManager::reset(); + SessionsManager::setStorage(new InMemorySessionStorage()); + parent::tearDown(); + } +} diff --git a/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php b/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php new file mode 100644 index 000000000..d2a8e73c6 --- /dev/null +++ b/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php @@ -0,0 +1,201 @@ +createStorage($driver); + SessionsManager::setStorage($storage); + $name = 'i433-'.$driver; + + $s = new Session(['name' => $name, 'duration' => 10080, 'refresh' => true]); + $s->start(); + $s->set('k', 'v'); + $sid = $s->getId(); + + // Simulate a session that was last refreshed almost a full lifetime + // ago: only 30 seconds of it are left. + $storage->setExpiry($sid, time() + 30); + + $resumed = new Session(['name' => $name, 'session-id' => $sid]); + $resumed->start(); + $this->assertEquals(SessionStatus::RESUMED, $resumed->getStatus()); + $this->assertEquals('v', $resumed->get('k')); + + $this->assertGreaterThan( + time() + 10080 * 60 - 300, + $storage->getExpiry($sid), + "Issue #433: resuming an active refresh session did not extend its expiry ($driver)." + ); + } + + /** + * Issue #432: GC must not delete a session that is idle for longer than + * the default threshold (4 hours) but whose own lifetime (7 days) has not + * expired. + * + * @test + * @dataProvider timestampStorageProvider + */ + public function testIssue432GcRespectsPerSessionLifetime(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + + $s = new Session(['name' => 'i432-'.$driver, 'duration' => 10080, 'refresh' => true]); + $s->start(); + $s->set('k', 'v'); + $sid = $s->getId(); + $s->close(); + + $this->ageSession($storage, $sid, 5 * 3600); + + $resumed = new Session(['name' => 'i432-'.$driver, 'session-id' => $sid]); + $resumed->start(); + $this->assertGreaterThan(0, $resumed->getRemainingTime(), 'Precondition: session lifetime has not expired.'); + + // Age it again: resuming may legitimately update the last-use time (#433). + $this->ageSession($storage, $sid, 5 * 3600); + $storage->gc(SessionsManager::getGCTime()); + + $this->assertTrue( + $this->sessionExistsInStorage($storage, $sid), + "Issue #432: GC deleted a session whose 7 day lifetime has not expired ($driver)." + ); + } + + /** + * Issue #431: setDuration() and setIsRefresh() on a running session must + * reach storage without an explicit close(), as in a normal request where + * StartSessionMiddleware::afterSend() only calls validateStorage(). + * + * @test + * @dataProvider storageProvider + */ + public function testIssue431DurationAndRefreshArePersisted(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::reset(); + SessionsManager::setStorage($storage); + $name = 'i431-'.$driver; + + SessionsManager::start($name); + $s = SessionsManager::getActiveSession(); + $sid = $s->getId(); + $s->setDuration(10080); + $s->setIsRefresh(true); + SessionsManager::validateStorage(); + + $meta = $storage->read($sid, '_meta')['value']; + $this->assertEquals(10080, $meta['lifeTime'], "Issue #431: lifeTime was not persisted ($driver)."); + $this->assertTrue($meta['isRef'], "Issue #431: isRef was not persisted ($driver)."); + + $next = new Session(['name' => $name, 'session-id' => $sid]); + $next->start(); + $this->assertEquals(604800, $next->getDuration(), "Issue #431: resumed session lost its duration ($driver)."); + $this->assertTrue($next->isRefresh(), "Issue #431: resumed session lost its refresh flag ($driver)."); + } + + /** + * Issue #434: SESSION_GC must be read as a duration in seconds, not as an + * absolute Unix timestamp. + * + * @test + */ + public function testIssue434SessionGcIsADuration() { + $previous = getenv('SESSION_GC'); + putenv('SESSION_GC=604800'); + + try { + $threshold = strtotime(SessionsManager::getGCTime()); + } finally { + if ($previous === false) { + putenv('SESSION_GC'); + } else { + putenv('SESSION_GC='.$previous); + } + } + + $this->assertEqualsWithDelta( + time() - 604800, + $threshold, + 5, + 'Issue #434: SESSION_GC=604800 should mean "older than one week", not the timestamp 604800.' + ); + } + + /** + * Issue #435: when '_meta' has no lifeTime, a resumed session must fall + * back to the default duration (120 minutes), not 2 minutes. + * + * @test + * @dataProvider storageProvider + */ + public function testIssue435MissingLifeTimeFallsBackToDefault(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::reset(); + SessionsManager::setStorage($storage); + $name = 'i435-'.$driver; + + SessionsManager::start($name); + $sid = SessionsManager::getActiveSession()->getId(); + $storage->write( + $sid, + '_meta', + ['startedAt' => time(), 'isRef' => false, 'langCode' => 'EN'], + null, + ConflictStrategy::LAST_WRITE_WINS + ); + + $r = new Session(['name' => $name, 'session-id' => $sid]); + $r->start(); + + $this->assertEquals( + Session::DEFAULT_SESSION_DURATION * 60, + $r->getDuration(), + "Issue #435: missing lifeTime fell back to {$r->getDuration()} seconds ($driver)." + ); + } + + protected function setUp(): void { + parent::setUp(); + InMemorySessionStorage::reset(); + SessionsManager::reset(); + } + + protected function tearDown(): void { + $this->cleanupDrivers(); + SessionsManager::reset(); + SessionsManager::setStorage(new InMemorySessionStorage()); + parent::tearDown(); + } +} From b86b94c3df4b1a87881644163d1e076aac6543f6 Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Mon, 16 Nov 2026 20:23:37 +0300 Subject: [PATCH 3/6] style(session): apply php-cs-fixer to files changed for session expiry No behavior change. Only the files touched by this work are formatted; most of the change is the fixer's method ordering. --- .../Framework/Session/CacheSessionStorage.php | 74 +++--- .../Session/DatabaseSessionStorage.php | 28 +-- .../Session/DefaultSessionStorage.php | 72 +++--- .../Session/InMemorySessionStorage.php | 35 ++- WebFiori/Framework/Session/Session.php | 168 +++++++------- WebFiori/Framework/Session/SessionDB.php | 216 +++++++++--------- .../Session/ExpiringSessionStorageTest.php | 69 +++--- .../Tests/Session/SessionDriversTrait.php | 76 +++--- .../Tests/Session/SessionExpiryTest.php | 134 +++++------ .../Tests/Session/SessionLifetimeBugsTest.php | 91 ++++---- .../Session/SessionUserPersistenceTest.php | 47 ++-- 11 files changed, 502 insertions(+), 508 deletions(-) diff --git a/WebFiori/Framework/Session/CacheSessionStorage.php b/WebFiori/Framework/Session/CacheSessionStorage.php index e0c3dd9c8..702650a84 100644 --- a/WebFiori/Framework/Session/CacheSessionStorage.php +++ b/WebFiori/Framework/Session/CacheSessionStorage.php @@ -57,49 +57,17 @@ public function destroy(string $sessionId): void { /** * {@inheritdoc} */ - public function getExpiry(string $sessionId): ?int { - $value = $this->storage->read($this->expiryKey($sessionId), null); - - return is_int($value) ? $value : null; + public function gc(string $olderThan, int $maxCount = 0): void { + $this->storage->purgeExpired(); } /** * {@inheritdoc} - * - * The expiry is enforced through the cache TTL: every entry of the session - * is stored again with a TTL equal to the remaining lifetime, and later - * writes use the same TTL. Clearing the expiry leaves existing entries - * with the TTL they already have. */ - public function setExpiry(string $sessionId, ?int $expiresAt): void { - if ($expiresAt === null) { - $this->storage->delete($this->expiryKey($sessionId)); - - return; - } - $ttl = max(1, $expiresAt - time()); - $this->storeItem($this->expiryKey($sessionId), $expiresAt, $ttl); - - $keys = $this->readIndex($sessionId); - - foreach ($keys as $key) { - $entry = $this->read($sessionId, $key); - - if ($entry !== null) { - $this->storeItem($this->keyFor($sessionId, $key), $entry, $ttl); - } - } - - if ($keys !== []) { - $this->storeItem($this->indexKey($sessionId), $keys, $ttl); - } - } + public function getExpiry(string $sessionId): ?int { + $value = $this->storage->read($this->expiryKey($sessionId), null); - /** - * {@inheritdoc} - */ - public function gc(string $olderThan, int $maxCount = 0): void { - $this->storage->purgeExpired(); + return is_int($value) ? $value : null; } public function getPrefix(): string { @@ -154,6 +122,38 @@ public function remove(string $sessionId, string $key): void { $this->removeFromIndex($sessionId, $key); } + /** + * {@inheritdoc} + * + * The expiry is enforced through the cache TTL: every entry of the session + * is stored again with a TTL equal to the remaining lifetime, and later + * writes use the same TTL. Clearing the expiry leaves existing entries + * with the TTL they already have. + */ + public function setExpiry(string $sessionId, ?int $expiresAt): void { + if ($expiresAt === null) { + $this->storage->delete($this->expiryKey($sessionId)); + + return; + } + $ttl = max(1, $expiresAt - time()); + $this->storeItem($this->expiryKey($sessionId), $expiresAt, $ttl); + + $keys = $this->readIndex($sessionId); + + foreach ($keys as $key) { + $entry = $this->read($sessionId, $key); + + if ($entry !== null) { + $this->storeItem($this->keyFor($sessionId, $key), $entry, $ttl); + } + } + + if ($keys !== []) { + $this->storeItem($this->indexKey($sessionId), $keys, $ttl); + } + } + public function setTTL(int $ttl): void { $this->ttl = $ttl; } diff --git a/WebFiori/Framework/Session/DatabaseSessionStorage.php b/WebFiori/Framework/Session/DatabaseSessionStorage.php index 546988d98..dc93b4302 100644 --- a/WebFiori/Framework/Session/DatabaseSessionStorage.php +++ b/WebFiori/Framework/Session/DatabaseSessionStorage.php @@ -48,20 +48,6 @@ public function __construct($connection = 'sessions-connection') { } } - /** - * {@inheritdoc} - */ - public function getExpiry(string $sessionId): ?int { - return $this->dbController->getExpiry($sessionId); - } - - /** - * {@inheritdoc} - */ - public function setExpiry(string $sessionId, ?int $expiresAt): void { - $this->dbController->setExpiry($sessionId, $expiresAt); - } - /** * {@inheritdoc} */ @@ -90,6 +76,13 @@ public function getController(): SessionDB { return $this->dbController; } + /** + * {@inheritdoc} + */ + public function getExpiry(string $sessionId): ?int { + return $this->dbController->getExpiry($sessionId); + } + /** * {@inheritdoc} */ @@ -111,6 +104,13 @@ public function remove(string $sessionId, string $key): void { $this->dbController->removeSessionKey($sessionId, $key); } + /** + * {@inheritdoc} + */ + public function setExpiry(string $sessionId, ?int $expiresAt): void { + $this->dbController->setExpiry($sessionId, $expiresAt); + } + /** * {@inheritdoc} */ diff --git a/WebFiori/Framework/Session/DefaultSessionStorage.php b/WebFiori/Framework/Session/DefaultSessionStorage.php index 412a7c892..c9c870e37 100644 --- a/WebFiori/Framework/Session/DefaultSessionStorage.php +++ b/WebFiori/Framework/Session/DefaultSessionStorage.php @@ -76,42 +76,6 @@ public function destroy(string $sessionId): void { } } - /** - * {@inheritdoc} - * - * The expiry is kept in a sidecar file next to the session file, because - * the modification time of the session file changes on every write. - */ - public function getExpiry(string $sessionId): ?int { - $path = $this->expiryPath($sessionId); - - if (!file_exists($path)) { - return null; - } - $raw = @file_get_contents($path); - - return $raw !== false && ctype_digit(trim($raw)) ? (int) trim($raw) : null; - } - - /** - * {@inheritdoc} - */ - public function setExpiry(string $sessionId, ?int $expiresAt): void { - if (!$this->canWrite()) { - return; - } - $path = $this->expiryPath($sessionId); - - if ($expiresAt === null) { - if (file_exists($path)) { - unlink($path); - } - - return; - } - file_put_contents($path, (string) $expiresAt, LOCK_EX); - } - /** * {@inheritdoc} */ @@ -157,6 +121,23 @@ public function gc(string $olderThan, int $maxCount = 0): void { } } + /** + * {@inheritdoc} + * + * The expiry is kept in a sidecar file next to the session file, because + * the modification time of the session file changes on every write. + */ + public function getExpiry(string $sessionId): ?int { + $path = $this->expiryPath($sessionId); + + if (!file_exists($path)) { + return null; + } + $raw = @file_get_contents($path); + + return $raw !== false && ctype_digit(trim($raw)) ? (int) trim($raw) : null; + } + /** * Checks if the storage directory exists and is writable. */ @@ -246,6 +227,25 @@ public function remove(string $sessionId, string $key): void { fclose($handle); } + /** + * {@inheritdoc} + */ + public function setExpiry(string $sessionId, ?int $expiresAt): void { + if (!$this->canWrite()) { + return; + } + $path = $this->expiryPath($sessionId); + + if ($expiresAt === null) { + if (file_exists($path)) { + unlink($path); + } + + return; + } + file_put_contents($path, (string) $expiresAt, LOCK_EX); + } + /** * {@inheritdoc} */ diff --git a/WebFiori/Framework/Session/InMemorySessionStorage.php b/WebFiori/Framework/Session/InMemorySessionStorage.php index f2d548bac..cbc253ec9 100644 --- a/WebFiori/Framework/Session/InMemorySessionStorage.php +++ b/WebFiori/Framework/Session/InMemorySessionStorage.php @@ -29,19 +29,18 @@ * @since 3.1.0 */ class InMemorySessionStorage implements ExpiringSessionStorage { - /** - * Shared in-process store keyed by [session_id][key] => [value, version]. - * - * @var array> - */ - private static array $store = []; - /** * Recorded expiry times keyed by session id. * * @var array */ private static array $expiry = []; + /** + * Shared in-process store keyed by [session_id][key] => [value, version]. + * + * @var array> + */ + private static array $store = []; /** * Destroys an entire session, removing all its keys. @@ -81,17 +80,6 @@ public function getExpiry(string $sessionId): ?int { return self::$expiry[$sessionId] ?? null; } - /** - * {@inheritdoc} - */ - public function setExpiry(string $sessionId, ?int $expiresAt): void { - if ($expiresAt === null) { - unset(self::$expiry[$sessionId]); - } else { - self::$expiry[$sessionId] = $expiresAt; - } - } - /** * Reads a single key from the session. * @@ -135,6 +123,17 @@ public static function reset(): void { self::$expiry = []; } + /** + * {@inheritdoc} + */ + public function setExpiry(string $sessionId, ?int $expiresAt): void { + if ($expiresAt === null) { + unset(self::$expiry[$sessionId]); + } else { + self::$expiry[$sessionId] = $expiresAt; + } + } + /** * Writes a single key to the session. * diff --git a/WebFiori/Framework/Session/Session.php b/WebFiori/Framework/Session/Session.php index a1f992c66..0ab818e3a 100644 --- a/WebFiori/Framework/Session/Session.php +++ b/WebFiori/Framework/Session/Session.php @@ -32,13 +32,6 @@ class Session implements JsonI { */ const DEFAULT_SESSION_DURATION = 120; - /** - * Minimum drift, in seconds, before the stored expiry of a resumed session - * is rewritten. Avoids a storage write on every request of a session that - * has refresh enabled. - */ - private const EXPIRY_REFRESH_INTERVAL = 60; - /** * Storage keys that are reserved for internal session use. * @@ -51,6 +44,13 @@ class Session implements JsonI { */ const RESERVED_KEYS = ['_meta', '_user']; + /** + * Minimum drift, in seconds, before the stored expiry of a resumed session + * is rewritten. Avoids a storage write on every request of a session that + * has refresh enabled. + */ + private const EXPIRY_REFRESH_INTERVAL = 60; + /** * Conflict strategy controlling how set() handles concurrent modifications. * @@ -955,6 +955,22 @@ public function toJSON() : Json { return $json; } + /** + * Throws a SessionException if the given key is reserved for internal use. + * + * Reserved keys (see Session::RESERVED_KEYS) hold internal session state + * and must not be mutated through the public variable API. Reading is + * allowed; writing, removing or pulling a reserved key is rejected. + * + * @param string $key The (already trimmed) key being written. + * + * @throws SessionException If the key is reserved. + */ + private function assertNotReserved(string $key): void { + if (in_array($key, self::RESERVED_KEYS, true)) { + throw new SessionException("The session key '$key' is reserved for internal use and cannot be modified."); + } + } private function checkIfExpired() { if ($this->getRemainingTime() < 0) { SessionsManager::getStorage()->destroy($this->getId()); @@ -982,6 +998,21 @@ private function cloneHelper(Session $session) { } $this->passedTime = $this->getResumedAt() - $this->getStartedAt(); } + /** + * Returns the time at which the session expires, as a Unix timestamp. + * + * Sessions with refresh enabled expire one full duration after now. Other + * sessions expire one full duration after they started. + * + * @return int|null Null if the session is not persistent (no lifetime). + */ + private function computeExpiry(): ?int { + if (!$this->isPersistent()) { + return null; + } + + return ($this->isRefresh() ? time() : $this->startedAt) + $this->getDuration(); + } private function decryptLegacy(string $serialized): ?string { $split = explode('_', $serialized, 2); @@ -1033,22 +1064,6 @@ private function decryptSession(string $encoded): ?string { return $plaintext !== false ? $plaintext : null; } - /** - * Throws a SessionException if the given key is reserved for internal use. - * - * Reserved keys (see Session::RESERVED_KEYS) hold internal session state - * and must not be mutated through the public variable API. Reading is - * allowed; writing, removing or pulling a reserved key is rejected. - * - * @param string $key The (already trimmed) key being written. - * - * @throws SessionException If the key is reserved. - */ - private function assertNotReserved(string $key): void { - if (in_array($key, self::RESERVED_KEYS, true)) { - throw new SessionException("The session key '$key' is reserved for internal use and cannot be modified."); - } - } /** * Decrypts a session value that was encrypted by encryptValue(). * @@ -1221,29 +1236,25 @@ private function persistMeta(): void { $this->syncExpiry(); } /** - * Returns the time at which the session expires, as a Unix timestamp. - * - * Sessions with refresh enabled expire one full duration after now. Other - * sessions expire one full duration after they started. + * Persists the current session user to the reserved '_user' key. * - * @return int|null Null if the session is not persistent (no lifetime). - */ - private function computeExpiry(): ?int { - if (!$this->isPersistent()) { - return null; - } - - return ($this->isRefresh() ? time() : $this->startedAt) + $this->getDuration(); - } - /** - * Records the expiry time in storage, if the storage supports it. + * The user (an object implementing SessionUser) is serialized and stored + * like any other value, so it is encrypted at rest when SESSION_KEY is + * defined. When no user is set, any previously stored user is removed. */ - private function syncExpiry(): void { - $storage = SessionsManager::getStorage(); + private function persistUser(): void { + if ($this->sessionUser === null) { + SessionsManager::getStorage()->remove($this->getId(), '_user'); - if ($storage instanceof ExpiringSessionStorage) { - $storage->setExpiry($this->getId(), $this->computeExpiry()); + return; } + SessionsManager::getStorage()->write( + $this->getId(), + '_user', + $this->encryptValue(serialize($this->sessionUser)), + null, + ConflictStrategy::LAST_WRITE_WINS + ); } /** * Updates the stored expiry of a resumed session. @@ -1270,48 +1281,6 @@ private function refreshExpiry(): void { $storage->setExpiry($this->getId(), $target); } } - /** - * Persists the current session user to the reserved '_user' key. - * - * The user (an object implementing SessionUser) is serialized and stored - * like any other value, so it is encrypted at rest when SESSION_KEY is - * defined. When no user is set, any previously stored user is removed. - */ - private function persistUser(): void { - if ($this->sessionUser === null) { - SessionsManager::getStorage()->remove($this->getId(), '_user'); - - return; - } - SessionsManager::getStorage()->write( - $this->getId(), - '_user', - $this->encryptValue(serialize($this->sessionUser)), - null, - ConflictStrategy::LAST_WRITE_WINS - ); - } - /** - * Restores the session user from the reserved '_user' key, if present. - */ - private function restoreUser(): void { - $entry = SessionsManager::getStorage()->read($this->getId(), '_user'); - - if ($entry === null) { - $this->sessionUser = null; - - return; - } - $decrypted = $this->decryptValue($entry['value']); - - if (is_string($decrypted)) { - $restored = @unserialize($decrypted); - - $this->sessionUser = $restored instanceof SessionUser ? $restored : null; - } else { - $this->sessionUser = null; - } - } private function restoreFromPlaintext(string $plaintext): bool { set_error_handler(function ($errNo, $errStr) { @@ -1336,6 +1305,27 @@ private function restoreFromPlaintext(string $plaintext): bool { return false; } + /** + * Restores the session user from the reserved '_user' key, if present. + */ + private function restoreUser(): void { + $entry = SessionsManager::getStorage()->read($this->getId(), '_user'); + + if ($entry === null) { + $this->sessionUser = null; + + return; + } + $decrypted = $this->decryptValue($entry['value']); + + if (is_string($decrypted)) { + $restored = @unserialize($decrypted); + + $this->sessionUser = $restored instanceof SessionUser ? $restored : null; + } else { + $this->sessionUser = null; + } + } private function setNameHelper($name): bool { $trimmed = trim($name); @@ -1354,6 +1344,16 @@ private function setNameHelper($name): bool { return true; } + /** + * Records the expiry time in storage, if the storage supports it. + */ + private function syncExpiry(): void { + $storage = SessionsManager::getStorage(); + + if ($storage instanceof ExpiringSessionStorage) { + $storage->setExpiry($this->getId(), $this->computeExpiry()); + } + } /** * Writes a key using RETRY_WITH_CALLBACK: re-reads current value and calls * the callback to compute the new value, retrying up to 5 times. diff --git a/WebFiori/Framework/Session/SessionDB.php b/WebFiori/Framework/Session/SessionDB.php index 9e249dfde..0c4924e48 100644 --- a/WebFiori/Framework/Session/SessionDB.php +++ b/WebFiori/Framework/Session/SessionDB.php @@ -48,15 +48,6 @@ public function __construct($connection = 'sessions-connection') { // is acceptable — per-key operations will fail gracefully at use time. } } - /** - * Creates all session tables (sessions, session_data, session_kv_data). - * Called during test setup or initial deployment. - */ - public function createTables(): void { - // Use the parent DB class createTables() which creates all registered tables. - parent::createTables(); - $this->createExpiryIndex(); - } /** * Creates the index on 'sessions.expires_at' that makes expiry-based * garbage collection a range scan. Safe to call more than once. @@ -69,6 +60,15 @@ public function createExpiryIndex(): void { } $this->clear(); } + /** + * Creates all session tables (sessions, session_data, session_kv_data). + * Called during test setup or initial deployment. + */ + public function createTables(): void { + // Use the parent DB class createTables() which creates all registered tables. + parent::createTables(); + $this->createExpiryIndex(); + } /** * Drops all session-related tables. */ @@ -129,6 +129,68 @@ public function getChunksCount(string $sId): int { return 0; } + /** + * Returns the IDs of sessions that should be garbage-collected. + * + * @param string $now The current time as 'YYYY-MM-DD HH:MM:SS'. Sessions + * whose recorded expiry is at or before this time are returned. + * @param string $idleOlderThan Sessions with NO recorded expiry are + * returned if their last use is at or before this time. + * + * @return array + * + * @throws DatabaseException + */ + public function getExpiredSessionsIDs(string $now, string $idleOlderThan): array { + $mapId = function ($record) + { + return $record['s-id'] ?? $record['s_id'] ?? null; + }; + + try { + $expired = $this->table('sessions')->select() + ->where('expires-at', $now, '<=')->execute()->map($mapId)->toArray(); + $legacy = $this->table('sessions')->select() + ->where('last-used', $idleOlderThan, '<=')->whereNull('expires-at') + ->execute()->map($mapId)->toArray(); + } catch (DatabaseException $e) { + // The 'expires_at' column does not exist yet (schema not migrated): + // behave as before and use the idle threshold for every session. + $this->clear(); + + return $this->getSessionsIDs($idleOlderThan); + } + + return array_values(array_unique(array_merge($expired, $legacy))); + } + + /** + * Returns the recorded expiry time of a session. + * + * @param string $sId The ID of the session. + * + * @return int|null A Unix timestamp, or null if no expiry is recorded, the + * session does not exist, or the 'expires_at' column has not been migrated. + */ + public function getExpiry(string $sId): ?int { + try { + $rows = $this->table('sessions')->select()->where('s-id', $sId)->execute()->getRows(); + } catch (DatabaseException $e) { + return null; + } + + if (count($rows) === 0) { + return null; + } + $value = $rows[0]['expires-at'] ?? $rows[0]['expires_at'] ?? null; + + if ($value === null || $value === '') { + return null; + } + $time = strtotime((string) $value); + + return $time === false ? null : $time; + } /** * Returns a record that holds session data given Its ID. @@ -209,86 +271,6 @@ public function getSessionKeys(string $sId): array { return $result; } - - /** - * Returns the recorded expiry time of a session. - * - * @param string $sId The ID of the session. - * - * @return int|null A Unix timestamp, or null if no expiry is recorded, the - * session does not exist, or the 'expires_at' column has not been migrated. - */ - public function getExpiry(string $sId): ?int { - try { - $rows = $this->table('sessions')->select()->where('s-id', $sId)->execute()->getRows(); - } catch (DatabaseException $e) { - return null; - } - - if (count($rows) === 0) { - return null; - } - $value = $rows[0]['expires-at'] ?? $rows[0]['expires_at'] ?? null; - - if ($value === null || $value === '') { - return null; - } - $time = strtotime((string) $value); - - return $time === false ? null : $time; - } - /** - * Returns the IDs of sessions that should be garbage-collected. - * - * @param string $now The current time as 'YYYY-MM-DD HH:MM:SS'. Sessions - * whose recorded expiry is at or before this time are returned. - * @param string $idleOlderThan Sessions with NO recorded expiry are - * returned if their last use is at or before this time. - * - * @return array - * - * @throws DatabaseException - */ - public function getExpiredSessionsIDs(string $now, string $idleOlderThan): array { - $mapId = function ($record) - { - return $record['s-id'] ?? $record['s_id'] ?? null; - }; - - try { - $expired = $this->table('sessions')->select() - ->where('expires-at', $now, '<=')->execute()->map($mapId)->toArray(); - $legacy = $this->table('sessions')->select() - ->where('last-used', $idleOlderThan, '<=')->whereNull('expires-at') - ->execute()->map($mapId)->toArray(); - } catch (DatabaseException $e) { - // The 'expires_at' column does not exist yet (schema not migrated): - // behave as before and use the idle threshold for every session. - $this->clear(); - - return $this->getSessionsIDs($idleOlderThan); - } - - return array_values(array_unique(array_merge($expired, $legacy))); - } - /** - * Records the time at which a session expires. - * - * Does nothing if the session row does not exist or the 'expires_at' - * column has not been migrated. - * - * @param string $sId The ID of the session. - * @param int|null $expiresAt A Unix timestamp, or null to clear. - */ - public function setExpiry(string $sId, ?int $expiresAt): void { - try { - $this->table('sessions')->update([ - 'expires-at' => $expiresAt === null ? null : date('Y-m-d H:i:s', $expiresAt), - ])->where('s-id', $sId)->execute(); - } catch (DatabaseException $e) { - $this->clear(); - } - } /** * Returns an array that holds the IDs of sessions which are older than * specific date and time. @@ -390,6 +372,24 @@ public function saveSession(string $sId, string $session) { $this->ensureSessionRow($sId); $this->storeChunks($sId, base64_encode($session)); } + /** + * Records the time at which a session expires. + * + * Does nothing if the session row does not exist or the 'expires_at' + * column has not been migrated. + * + * @param string $sId The ID of the session. + * @param int|null $expiresAt A Unix timestamp, or null to clear. + */ + public function setExpiry(string $sId, ?int $expiresAt): void { + try { + $this->table('sessions')->update([ + 'expires-at' => $expiresAt === null ? null : date('Y-m-d H:i:s', $expiresAt), + ])->where('s-id', $sId)->execute(); + } catch (DatabaseException $e) { + $this->clear(); + } + } /** * Writes a single key to session_kv_data with conflict detection. * @@ -493,6 +493,25 @@ private function ensureSessionRow(string $sId): void { ])->where('s-id', $sId)->execute(); } } + /** + * Split session data into smaller chunks. + * + * @param string $data + * @return array + */ + private function getChunks(string $data) : array { + $retVal = []; + $chunkSize = $this->getTable('session_data')->getColByKey('data')->getSize() - 50; + $dataLen = strlen($data); + $index = 0; + + while ($index < $dataLen) { + $retVal[] = substr($data, $index, $chunkSize); + $index += $chunkSize; + } + + return $retVal; + } /** * Checks whether a database exception represents a duplicate/primary-key * constraint violation across the supported database engines. @@ -519,25 +538,6 @@ private function isDuplicateKeyError(DatabaseException $ex): bool { || stripos($msg, 'PRIMARY KEY') !== false || stripos($msg, 'UNIQUE constraint') !== false; } - /** - * Split session data into smaller chunks. - * - * @param string $data - * @return array - */ - private function getChunks(string $data) : array { - $retVal = []; - $chunkSize = $this->getTable('session_data')->getColByKey('data')->getSize() - 50; - $dataLen = strlen($data); - $index = 0; - - while ($index < $dataLen) { - $retVal[] = substr($data, $index, $chunkSize); - $index += $chunkSize; - } - - return $retVal; - } /** * This method is used to remove any extra chunks which remains in the diff --git a/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php b/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php index 98669df64..de0c43168 100644 --- a/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php +++ b/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php @@ -5,8 +5,6 @@ use PHPUnit\Framework\TestCase; use WebFiori\Framework\Session\ConflictStrategy; -use WebFiori\Framework\Session\DatabaseSessionStorage; -use WebFiori\Framework\Session\DefaultSessionStorage; use WebFiori\Framework\Session\ExpiringSessionStorage; use WebFiori\Framework\Session\InMemorySessionStorage; use WebFiori\Framework\Session\SessionSchemaMigration; @@ -19,8 +17,6 @@ * service is not reachable. */ class ExpiringSessionStorageTest extends TestCase { - use SessionDriversTrait; - /** * @test * @dataProvider storageProvider @@ -83,28 +79,6 @@ public function testExpirySurvivesLaterWrites(string $driver) { $this->assertEquals('v', $storage->read('later-writes', 'k')['value']); } - /** - * Sessions that have an expiry are removed by gc() only once it passed, - * whatever the idle threshold says. - * - * @test - * @dataProvider storageProvider - */ - public function testGcUsesRecordedExpiry(string $driver) { - $storage = $this->createStorage($driver); - $this->write($storage, 'expired'); - $this->write($storage, 'alive'); - $this->expireSession($driver, $storage, 'expired'); - $storage->setExpiry('alive', time() + 3600); - - // An idle threshold in the far future would delete every session - // that has no expiry. 'alive' has one, so it must stay. - $storage->gc(date('Y-m-d H:i:s', time() + 86400)); - - $this->assertFalse($this->sessionExistsInStorage($storage, 'expired'), 'Expired session should be removed.'); - $this->assertTrue($this->sessionExistsInStorage($storage, 'alive'), 'Unexpired session should be kept.'); - } - /** * Sessions without a recorded expiry (created before upgrade, or with a * non-persistent lifetime) keep being removed by the idle threshold. @@ -149,6 +123,28 @@ public function testGcRespectsMaxCount(string $driver) { $this->assertSame(1, $left); } + /** + * Sessions that have an expiry are removed by gc() only once it passed, + * whatever the idle threshold says. + * + * @test + * @dataProvider storageProvider + */ + public function testGcUsesRecordedExpiry(string $driver) { + $storage = $this->createStorage($driver); + $this->write($storage, 'expired'); + $this->write($storage, 'alive'); + $this->expireSession($driver, $storage, 'expired'); + $storage->setExpiry('alive', time() + 3600); + + // An idle threshold in the far future would delete every session + // that has no expiry. 'alive' has one, so it must stay. + $storage->gc(date('Y-m-d H:i:s', time() + 86400)); + + $this->assertFalse($this->sessionExistsInStorage($storage, 'expired'), 'Expired session should be removed.'); + $this->assertTrue($this->sessionExistsInStorage($storage, 'alive'), 'Unexpired session should be kept.'); + } + /** * A database whose 'sessions' table has no 'expires_at' column yet (not * migrated) must keep working with idle-threshold GC, and the migration @@ -190,16 +186,6 @@ public function testUnmigratedDatabaseDegradesAndMigrationAddsColumn(string $dri $this->assertSame($at, $storage->getExpiry('old-fresh')); } - protected function setUp(): void { - parent::setUp(); - InMemorySessionStorage::reset(); - } - - protected function tearDown(): void { - $this->cleanupDrivers(); - parent::tearDown(); - } - /** * Makes a session's recorded expiry a time in the past. The cache driver * enforces expiry through TTLs, so the test waits for the 1 second TTL to @@ -216,4 +202,15 @@ private function expireSession(string $driver, ExpiringSessionStorage $storage, private function write(ExpiringSessionStorage $storage, string $sessionId): void { $storage->write($sessionId, 'k', 'v', null, ConflictStrategy::LAST_WRITE_WINS); } + use SessionDriversTrait; + + protected function setUp(): void { + parent::setUp(); + InMemorySessionStorage::reset(); + } + + protected function tearDown(): void { + $this->cleanupDrivers(); + parent::tearDown(); + } } diff --git a/tests/WebFiori/Framework/Tests/Session/SessionDriversTrait.php b/tests/WebFiori/Framework/Tests/Session/SessionDriversTrait.php index b7ed25808..b0ceb91a9 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionDriversTrait.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionDriversTrait.php @@ -33,11 +33,19 @@ final class SessionDriversAvailability { */ trait SessionDriversTrait { private string $cacheDir = ''; - private ?DatabaseSessionStorage $dbStorage = null; /** @var string|ConnectionInfo|null Connection used by the last database driver created. */ private $dbConnection = null; + private ?DatabaseSessionStorage $dbStorage = null; private string $sqlitePath = ''; + public static function databaseStorageProvider(): array { + return [ + 'sqlite' => ['sqlite'], + 'mysql' => ['mysql'], + 'mssql' => ['mssql'], + ]; + } + public static function storageProvider(): array { return [ 'default (file)' => ['default'], @@ -62,14 +70,6 @@ public static function timestampStorageProvider(): array { ]; } - public static function databaseStorageProvider(): array { - return [ - 'sqlite' => ['sqlite'], - 'mysql' => ['mysql'], - 'mssql' => ['mssql'], - ]; - } - /** * Moves the last-use time of a session into the past. */ @@ -88,35 +88,6 @@ private function ageSession(SessionStorage $storage, string $sessionId, int $sec ->where('s-id', $sessionId)->execute(); } - /** - * Returns the last-use time of a session as a Unix timestamp. - */ - private function lastUsed(SessionStorage $storage, string $sessionId): int { - if ($storage instanceof DefaultSessionStorage) { - $m = new \ReflectionMethod($storage, 'filePath'); - $m->setAccessible(true); - clearstatcache(); - - return filemtime($m->invoke($storage, $sessionId)); - } - $rows = $storage->getController()->table('sessions')->select() - ->where('s-id', $sessionId)->execute()->getRows(); - - return strtotime($rows[0]['last-used'] ?? $rows[0]['last_used']); - } - - private function sessionExistsInStorage(SessionStorage $storage, string $sessionId): bool { - if ($storage instanceof DefaultSessionStorage) { - return $storage->isStorageFileExist($sessionId); - } - - if ($storage instanceof DatabaseSessionStorage) { - return $storage->getController()->isSessionExist($sessionId); - } - - return $storage->readAll($sessionId) !== []; - } - private function cleanupDrivers(): void { if ($this->dbStorage !== null) { try { @@ -205,4 +176,33 @@ private function createStorage(string $driver): SessionStorage { } $this->fail("Unknown driver '$driver'."); } + + /** + * Returns the last-use time of a session as a Unix timestamp. + */ + private function lastUsed(SessionStorage $storage, string $sessionId): int { + if ($storage instanceof DefaultSessionStorage) { + $m = new \ReflectionMethod($storage, 'filePath'); + $m->setAccessible(true); + clearstatcache(); + + return filemtime($m->invoke($storage, $sessionId)); + } + $rows = $storage->getController()->table('sessions')->select() + ->where('s-id', $sessionId)->execute()->getRows(); + + return strtotime($rows[0]['last-used'] ?? $rows[0]['last_used']); + } + + private function sessionExistsInStorage(SessionStorage $storage, string $sessionId): bool { + if ($storage instanceof DefaultSessionStorage) { + return $storage->isStorageFileExist($sessionId); + } + + if ($storage instanceof DatabaseSessionStorage) { + return $storage->getController()->isSessionExist($sessionId); + } + + return $storage->readAll($sessionId) !== []; + } } diff --git a/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php b/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php index 9e6f015cc..30296389d 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php @@ -19,53 +19,6 @@ * service is not reachable. */ class SessionExpiryTest extends TestCase { - use SessionDriversTrait; - - /** - * A session whose storage does not implement ExpiringSessionStorage must - * keep working: nothing calls the expiry methods. - * - * @test - */ - public function testStorageWithoutExpirySupportStillWorks() { - $inner = new InMemorySessionStorage(); - $plain = new class($inner) implements SessionStorage { - public function __construct(private SessionStorage $inner) { - } - public function destroy(string $sessionId): void { - $this->inner->destroy($sessionId); - } - public function gc(string $olderThan, int $maxCount = 0): void { - $this->inner->gc($olderThan, $maxCount); - } - public function read(string $sessionId, string $key): ?array { - return $this->inner->read($sessionId, $key); - } - public function readAll(string $sessionId): array { - return $this->inner->readAll($sessionId); - } - public function remove(string $sessionId, string $key): void { - $this->inner->remove($sessionId, $key); - } - public function write(string $sessionId, string $key, mixed $value, string|int|null $expectedVersion, ConflictStrategy $strategy): string|int { - return $this->inner->write($sessionId, $key, $value, $expectedVersion, $strategy); - } - }; - SessionsManager::setStorage($plain); - - $s = new Session(['name' => 'plain-storage', 'duration' => 60, 'refresh' => true]); - $s->start(); - $s->set('k', 'v'); - $s->setDuration(120); - $s->close(); - - $r = new Session(['name' => 'plain-storage', 'session-id' => $s->getId()]); - $r->start(); - $this->assertEquals(SessionStatus::RESUMED, $r->getStatus()); - $this->assertEquals('v', $r->get('k')); - $this->assertEquals(7200, $r->getDuration()); - } - /** * A session with refresh expires one full duration after its latest write * of metadata, not after it started. @@ -119,6 +72,27 @@ public function testNonPersistentSessionHasNoExpiry(string $driver) { $this->assertNull($storage->getExpiry($s->getId())); } + /** + * A session without refresh keeps its original expiry when resumed. + * + * @test + * @dataProvider storageProvider + */ + public function testResumeKeepsExpiryOfNonRefreshSession(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + $name = 'exp-keep-'.$driver; + + $s = new Session(['name' => $name, 'duration' => 30]); + $s->start(); + $sid = $s->getId(); + $before = $storage->getExpiry($sid); + + (new Session(['name' => $name, 'session-id' => $sid]))->start(); + + $this->assertSame($before, $storage->getExpiry($sid)); + } + /** * A session created before expiry tracking existed has no recorded * expiry. Resuming it records one. @@ -171,47 +145,73 @@ public function testResumeRefreshesExpiryOnlyWhenDriftExceedsOneMinute(string $d } /** - * A session without refresh keeps its original expiry when resumed. + * setDuration() and setIsRefresh() on a running session update the + * recorded expiry (issue #431). * * @test * @dataProvider storageProvider */ - public function testResumeKeepsExpiryOfNonRefreshSession(string $driver) { + public function testSetDurationAndRefreshUpdateRecordedExpiry(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); - $name = 'exp-keep-'.$driver; - $s = new Session(['name' => $name, 'duration' => 30]); + $s = new Session(['name' => 'exp-set-'.$driver, 'duration' => 30]); $s->start(); $sid = $s->getId(); - $before = $storage->getExpiry($sid); - (new Session(['name' => $name, 'session-id' => $sid]))->start(); + $s->setDuration(60); + $this->assertEqualsWithDelta($s->getStartedAt() + 3600, $storage->getExpiry($sid), 2); - $this->assertSame($before, $storage->getExpiry($sid)); + $s->setIsRefresh(true); + $this->assertEqualsWithDelta(time() + 3600, $storage->getExpiry($sid), 5); } /** - * setDuration() and setIsRefresh() on a running session update the - * recorded expiry (issue #431). + * A session whose storage does not implement ExpiringSessionStorage must + * keep working: nothing calls the expiry methods. * * @test - * @dataProvider storageProvider */ - public function testSetDurationAndRefreshUpdateRecordedExpiry(string $driver) { - $storage = $this->createStorage($driver); - SessionsManager::setStorage($storage); + public function testStorageWithoutExpirySupportStillWorks() { + $inner = new InMemorySessionStorage(); + $plain = new class($inner) implements SessionStorage + { + public function __construct(private SessionStorage $inner) { + } + public function destroy(string $sessionId): void { + $this->inner->destroy($sessionId); + } + public function gc(string $olderThan, int $maxCount = 0): void { + $this->inner->gc($olderThan, $maxCount); + } + public function read(string $sessionId, string $key): ?array { + return $this->inner->read($sessionId, $key); + } + public function readAll(string $sessionId): array { + return $this->inner->readAll($sessionId); + } + public function remove(string $sessionId, string $key): void { + $this->inner->remove($sessionId, $key); + } + public function write(string $sessionId, string $key, mixed $value, string|int|null $expectedVersion, ConflictStrategy $strategy): string|int { + return $this->inner->write($sessionId, $key, $value, $expectedVersion, $strategy); + } + }; + SessionsManager::setStorage($plain); - $s = new Session(['name' => 'exp-set-'.$driver, 'duration' => 30]); + $s = new Session(['name' => 'plain-storage', 'duration' => 60, 'refresh' => true]); $s->start(); - $sid = $s->getId(); - - $s->setDuration(60); - $this->assertEqualsWithDelta($s->getStartedAt() + 3600, $storage->getExpiry($sid), 2); + $s->set('k', 'v'); + $s->setDuration(120); + $s->close(); - $s->setIsRefresh(true); - $this->assertEqualsWithDelta(time() + 3600, $storage->getExpiry($sid), 5); + $r = new Session(['name' => 'plain-storage', 'session-id' => $s->getId()]); + $r->start(); + $this->assertEquals(SessionStatus::RESUMED, $r->getStatus()); + $this->assertEquals('v', $r->get('k')); + $this->assertEquals(7200, $r->getDuration()); } + use SessionDriversTrait; protected function setUp(): void { parent::setUp(); diff --git a/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php b/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php index d2a8e73c6..4dda5dc95 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php @@ -19,45 +19,35 @@ * service is not reachable. */ class SessionLifetimeBugsTest extends TestCase { - use SessionDriversTrait; - /** - * Issue #433: an active session with refresh enabled must not be treated - * as idle. Resuming it must extend its stored expiry, so garbage - * collection keeps it. - * - * The original report was about the last-use timestamp. With - * ExpiringSessionStorage (ADR-0061) garbage collection no longer depends - * on that timestamp for sessions that have a recorded expiry, so the test - * checks the expiry that GC actually uses. + * Issue #431: setDuration() and setIsRefresh() on a running session must + * reach storage without an explicit close(), as in a normal request where + * StartSessionMiddleware::afterSend() only calls validateStorage(). * * @test * @dataProvider storageProvider */ - public function testIssue433ResumeExtendsExpiryOfRefreshSession(string $driver) { + public function testIssue431DurationAndRefreshArePersisted(string $driver) { $storage = $this->createStorage($driver); + SessionsManager::reset(); SessionsManager::setStorage($storage); - $name = 'i433-'.$driver; + $name = 'i431-'.$driver; - $s = new Session(['name' => $name, 'duration' => 10080, 'refresh' => true]); - $s->start(); - $s->set('k', 'v'); + SessionsManager::start($name); + $s = SessionsManager::getActiveSession(); $sid = $s->getId(); + $s->setDuration(10080); + $s->setIsRefresh(true); + SessionsManager::validateStorage(); - // Simulate a session that was last refreshed almost a full lifetime - // ago: only 30 seconds of it are left. - $storage->setExpiry($sid, time() + 30); - - $resumed = new Session(['name' => $name, 'session-id' => $sid]); - $resumed->start(); - $this->assertEquals(SessionStatus::RESUMED, $resumed->getStatus()); - $this->assertEquals('v', $resumed->get('k')); + $meta = $storage->read($sid, '_meta')['value']; + $this->assertEquals(10080, $meta['lifeTime'], "Issue #431: lifeTime was not persisted ($driver)."); + $this->assertTrue($meta['isRef'], "Issue #431: isRef was not persisted ($driver)."); - $this->assertGreaterThan( - time() + 10080 * 60 - 300, - $storage->getExpiry($sid), - "Issue #433: resuming an active refresh session did not extend its expiry ($driver)." - ); + $next = new Session(['name' => $name, 'session-id' => $sid]); + $next->start(); + $this->assertEquals(604800, $next->getDuration(), "Issue #431: resumed session lost its duration ($driver)."); + $this->assertTrue($next->isRefresh(), "Issue #431: resumed session lost its refresh flag ($driver)."); } /** @@ -95,34 +85,42 @@ public function testIssue432GcRespectsPerSessionLifetime(string $driver) { } /** - * Issue #431: setDuration() and setIsRefresh() on a running session must - * reach storage without an explicit close(), as in a normal request where - * StartSessionMiddleware::afterSend() only calls validateStorage(). + * Issue #433: an active session with refresh enabled must not be treated + * as idle. Resuming it must extend its stored expiry, so garbage + * collection keeps it. + * + * The original report was about the last-use timestamp. With + * ExpiringSessionStorage (ADR-0061) garbage collection no longer depends + * on that timestamp for sessions that have a recorded expiry, so the test + * checks the expiry that GC actually uses. * * @test * @dataProvider storageProvider */ - public function testIssue431DurationAndRefreshArePersisted(string $driver) { + public function testIssue433ResumeExtendsExpiryOfRefreshSession(string $driver) { $storage = $this->createStorage($driver); - SessionsManager::reset(); SessionsManager::setStorage($storage); - $name = 'i431-'.$driver; + $name = 'i433-'.$driver; - SessionsManager::start($name); - $s = SessionsManager::getActiveSession(); + $s = new Session(['name' => $name, 'duration' => 10080, 'refresh' => true]); + $s->start(); + $s->set('k', 'v'); $sid = $s->getId(); - $s->setDuration(10080); - $s->setIsRefresh(true); - SessionsManager::validateStorage(); - $meta = $storage->read($sid, '_meta')['value']; - $this->assertEquals(10080, $meta['lifeTime'], "Issue #431: lifeTime was not persisted ($driver)."); - $this->assertTrue($meta['isRef'], "Issue #431: isRef was not persisted ($driver)."); + // Simulate a session that was last refreshed almost a full lifetime + // ago: only 30 seconds of it are left. + $storage->setExpiry($sid, time() + 30); - $next = new Session(['name' => $name, 'session-id' => $sid]); - $next->start(); - $this->assertEquals(604800, $next->getDuration(), "Issue #431: resumed session lost its duration ($driver)."); - $this->assertTrue($next->isRefresh(), "Issue #431: resumed session lost its refresh flag ($driver)."); + $resumed = new Session(['name' => $name, 'session-id' => $sid]); + $resumed->start(); + $this->assertEquals(SessionStatus::RESUMED, $resumed->getStatus()); + $this->assertEquals('v', $resumed->get('k')); + + $this->assertGreaterThan( + time() + 10080 * 60 - 300, + $storage->getExpiry($sid), + "Issue #433: resuming an active refresh session did not extend its expiry ($driver)." + ); } /** @@ -185,6 +183,7 @@ public function testIssue435MissingLifeTimeFallsBackToDefault(string $driver) { "Issue #435: missing lifeTime fell back to {$r->getDuration()} seconds ($driver)." ); } + use SessionDriversTrait; protected function setUp(): void { parent::setUp(); diff --git a/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php index 513d76023..3498fcae8 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php @@ -18,7 +18,28 @@ * service is not reachable. */ class SessionUserPersistenceTest extends TestCase { - use SessionDriversTrait; + /** + * The user must be readable straight from storage under the reserved + * '_user' key right after setUser(), without any close() call. + * + * @test + * @dataProvider storageProvider + */ + public function testSetUserWritesToStorage(string $driver) { + $storage = $this->createStorage($driver); + SessionsManager::setStorage($storage); + + $s = new Session(['name' => 'user-write-'.$driver]); + $s->start(); + $this->assertNull($storage->read($s->getId(), '_user')); + + $s->setUser(new User('john', 'pass', 'john@example.com')); + + $this->assertNotNull( + $storage->read($s->getId(), '_user'), + "Issue #418: setUser() did not write '_user' to storage ($driver)." + ); + } /** * Issue #418: setUser() must persist the user, and start() must restore @@ -55,29 +76,7 @@ public function testUserIsRestoredOnResume(string $driver) { $this->assertEquals('jane@example.com', $s2->getUser()->getEmail()); $this->assertEquals('Jane Doe', $s2->getUser()->getDisplayName()); } - - /** - * The user must be readable straight from storage under the reserved - * '_user' key right after setUser(), without any close() call. - * - * @test - * @dataProvider storageProvider - */ - public function testSetUserWritesToStorage(string $driver) { - $storage = $this->createStorage($driver); - SessionsManager::setStorage($storage); - - $s = new Session(['name' => 'user-write-'.$driver]); - $s->start(); - $this->assertNull($storage->read($s->getId(), '_user')); - - $s->setUser(new User('john', 'pass', 'john@example.com')); - - $this->assertNotNull( - $storage->read($s->getId(), '_user'), - "Issue #418: setUser() did not write '_user' to storage ($driver)." - ); - } + use SessionDriversTrait; protected function setUp(): void { parent::setUp(); From d02e8340db546e3357ffd005b3ed34cebee2f2e4 Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Mon, 16 Nov 2026 21:06:02 +0300 Subject: [PATCH 4/6] test(session): use DataProvider attributes for PHPUnit 12 compatibility PHPUnit 12 (used by the PHP 8.5 CI job) ignores @dataProvider annotations, so the driver-parametrized tests ran without arguments. Attributes work on PHPUnit 10 and 12. --- .../Session/ExpiringSessionStorageTest.php | 17 +++++++++-------- .../Tests/Session/SessionExpiryTest.php | 15 ++++++++------- .../Tests/Session/SessionLifetimeBugsTest.php | 9 +++++---- .../Session/SessionUserPersistenceTest.php | 5 +++-- 4 files changed, 25 insertions(+), 21 deletions(-) diff --git a/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php b/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php index de0c43168..cc080933c 100644 --- a/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php +++ b/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php @@ -3,6 +3,7 @@ require_once __DIR__.'/SessionDriversTrait.php'; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use WebFiori\Framework\Session\ConflictStrategy; use WebFiori\Framework\Session\ExpiringSessionStorage; @@ -19,16 +20,16 @@ class ExpiringSessionStorageTest extends TestCase { /** * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testBuiltInDriversAreExpiring(string $driver) { $this->assertInstanceOf(ExpiringSessionStorage::class, $this->createStorage($driver)); } /** * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testDestroyClearsExpiry(string $driver) { $storage = $this->createStorage($driver); $this->write($storage, 'destroy-me'); @@ -41,8 +42,8 @@ public function testDestroyClearsExpiry(string $driver) { /** * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testExpiryRoundTrip(string $driver) { $storage = $this->createStorage($driver); $this->write($storage, 'round-trip'); @@ -64,8 +65,8 @@ public function testExpiryRoundTrip(string $driver) { * expiry or the data. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testExpirySurvivesLaterWrites(string $driver) { $storage = $this->createStorage($driver); $this->write($storage, 'later-writes'); @@ -84,8 +85,8 @@ public function testExpirySurvivesLaterWrites(string $driver) { * non-persistent lifetime) keep being removed by the idle threshold. * * @test - * @dataProvider timestampStorageProvider */ + #[DataProvider('timestampStorageProvider')] public function testGcFallsBackToIdleThresholdWithoutExpiry(string $driver) { $storage = $this->createStorage($driver); $this->write($storage, 'idle'); @@ -100,8 +101,8 @@ public function testGcFallsBackToIdleThresholdWithoutExpiry(string $driver) { /** * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testGcRespectsMaxCount(string $driver) { if ($driver === 'cache') { $this->markTestSkipped('The cache driver delegates expiry to cache TTLs; gc() has no count to limit.'); @@ -128,8 +129,8 @@ public function testGcRespectsMaxCount(string $driver) { * whatever the idle threshold says. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testGcUsesRecordedExpiry(string $driver) { $storage = $this->createStorage($driver); $this->write($storage, 'expired'); @@ -151,8 +152,8 @@ public function testGcUsesRecordedExpiry(string $driver) { * must add the column. * * @test - * @dataProvider databaseStorageProvider */ + #[DataProvider('databaseStorageProvider')] public function testUnmigratedDatabaseDegradesAndMigrationAddsColumn(string $driver) { $storage = $this->createStorage($driver); diff --git a/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php b/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php index 30296389d..cfd32f4e0 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php @@ -3,6 +3,7 @@ require_once __DIR__.'/SessionDriversTrait.php'; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use WebFiori\Framework\Session\ConflictStrategy; use WebFiori\Framework\Session\InMemorySessionStorage; @@ -24,8 +25,8 @@ class SessionExpiryTest extends TestCase { * of metadata, not after it started. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testNewRefreshSessionExpiresOneDurationFromNow(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); @@ -40,8 +41,8 @@ public function testNewRefreshSessionExpiresOneDurationFromNow(string $driver) { * A session without refresh expires one duration after it started. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testNewSessionExpiresOneDurationAfterStart(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); @@ -57,8 +58,8 @@ public function testNewSessionExpiresOneDurationAfterStart(string $driver) { * recorded and it stays subject to the idle threshold. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testNonPersistentSessionHasNoExpiry(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); @@ -76,8 +77,8 @@ public function testNonPersistentSessionHasNoExpiry(string $driver) { * A session without refresh keeps its original expiry when resumed. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testResumeKeepsExpiryOfNonRefreshSession(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); @@ -98,8 +99,8 @@ public function testResumeKeepsExpiryOfNonRefreshSession(string $driver) { * expiry. Resuming it records one. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testResumeRecordsMissingExpiry(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); @@ -121,8 +122,8 @@ public function testResumeRecordsMissingExpiry(string $driver) { * request. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testResumeRefreshesExpiryOnlyWhenDriftExceedsOneMinute(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); @@ -149,8 +150,8 @@ public function testResumeRefreshesExpiryOnlyWhenDriftExceedsOneMinute(string $d * recorded expiry (issue #431). * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testSetDurationAndRefreshUpdateRecordedExpiry(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); diff --git a/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php b/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php index 4dda5dc95..f128bc786 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php @@ -3,6 +3,7 @@ require_once __DIR__.'/SessionDriversTrait.php'; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use WebFiori\Framework\Session\ConflictStrategy; use WebFiori\Framework\Session\InMemorySessionStorage; @@ -25,8 +26,8 @@ class SessionLifetimeBugsTest extends TestCase { * StartSessionMiddleware::afterSend() only calls validateStorage(). * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testIssue431DurationAndRefreshArePersisted(string $driver) { $storage = $this->createStorage($driver); SessionsManager::reset(); @@ -56,8 +57,8 @@ public function testIssue431DurationAndRefreshArePersisted(string $driver) { * expired. * * @test - * @dataProvider timestampStorageProvider */ + #[DataProvider('timestampStorageProvider')] public function testIssue432GcRespectsPerSessionLifetime(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); @@ -95,8 +96,8 @@ public function testIssue432GcRespectsPerSessionLifetime(string $driver) { * checks the expiry that GC actually uses. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testIssue433ResumeExtendsExpiryOfRefreshSession(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); @@ -156,8 +157,8 @@ public function testIssue434SessionGcIsADuration() { * back to the default duration (120 minutes), not 2 minutes. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testIssue435MissingLifeTimeFallsBackToDefault(string $driver) { $storage = $this->createStorage($driver); SessionsManager::reset(); diff --git a/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php index 3498fcae8..af2493769 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php @@ -3,6 +3,7 @@ require_once __DIR__.'/SessionDriversTrait.php'; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use WebFiori\Framework\Session\InMemorySessionStorage; use WebFiori\Framework\Session\Session; @@ -23,8 +24,8 @@ class SessionUserPersistenceTest extends TestCase { * '_user' key right after setUser(), without any close() call. * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testSetUserWritesToStorage(string $driver) { $storage = $this->createStorage($driver); SessionsManager::setStorage($storage); @@ -46,8 +47,8 @@ public function testSetUserWritesToStorage(string $driver) { * it on resume, including user info modified after setUser(). * * @test - * @dataProvider storageProvider */ + #[DataProvider('storageProvider')] public function testUserIsRestoredOnResume(string $driver) { SessionsManager::setStorage($this->createStorage($driver)); From d9e30e67cb0dac3a00f28b5a1f318ba4a37ce271 Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Tue, 17 Nov 2026 09:16:23 +0300 Subject: [PATCH 5/6] test(session): declare data providers for PHPUnit 9, 10 and 12 CI runs PHPUnit 9.5 (PHP 8.1, 8.2), 10 (PHP 8.3, 8.4) and 12 (PHP 8.5). PHPUnit 9 only reads @dataProvider annotations and PHPUnit 12 only reads #[DataProvider] attributes, so declare both. --- .../Tests/Session/ExpiringSessionStorageTest.php | 8 ++++++++ .../Framework/Tests/Session/SessionExpiryTest.php | 7 +++++++ .../Framework/Tests/Session/SessionLifetimeBugsTest.php | 4 ++++ .../Tests/Session/SessionUserPersistenceTest.php | 2 ++ 4 files changed, 21 insertions(+) diff --git a/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php b/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php index cc080933c..8fc97c43d 100644 --- a/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php +++ b/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php @@ -20,6 +20,7 @@ class ExpiringSessionStorageTest extends TestCase { /** * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testBuiltInDriversAreExpiring(string $driver) { @@ -28,6 +29,7 @@ public function testBuiltInDriversAreExpiring(string $driver) { /** * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testDestroyClearsExpiry(string $driver) { @@ -42,6 +44,7 @@ public function testDestroyClearsExpiry(string $driver) { /** * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testExpiryRoundTrip(string $driver) { @@ -65,6 +68,7 @@ public function testExpiryRoundTrip(string $driver) { * expiry or the data. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testExpirySurvivesLaterWrites(string $driver) { @@ -85,6 +89,7 @@ public function testExpirySurvivesLaterWrites(string $driver) { * non-persistent lifetime) keep being removed by the idle threshold. * * @test + * @dataProvider timestampStorageProvider */ #[DataProvider('timestampStorageProvider')] public function testGcFallsBackToIdleThresholdWithoutExpiry(string $driver) { @@ -101,6 +106,7 @@ public function testGcFallsBackToIdleThresholdWithoutExpiry(string $driver) { /** * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testGcRespectsMaxCount(string $driver) { @@ -129,6 +135,7 @@ public function testGcRespectsMaxCount(string $driver) { * whatever the idle threshold says. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testGcUsesRecordedExpiry(string $driver) { @@ -152,6 +159,7 @@ public function testGcUsesRecordedExpiry(string $driver) { * must add the column. * * @test + * @dataProvider databaseStorageProvider */ #[DataProvider('databaseStorageProvider')] public function testUnmigratedDatabaseDegradesAndMigrationAddsColumn(string $driver) { diff --git a/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php b/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php index cfd32f4e0..6d2bfe91b 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php @@ -25,6 +25,7 @@ class SessionExpiryTest extends TestCase { * of metadata, not after it started. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testNewRefreshSessionExpiresOneDurationFromNow(string $driver) { @@ -41,6 +42,7 @@ public function testNewRefreshSessionExpiresOneDurationFromNow(string $driver) { * A session without refresh expires one duration after it started. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testNewSessionExpiresOneDurationAfterStart(string $driver) { @@ -58,6 +60,7 @@ public function testNewSessionExpiresOneDurationAfterStart(string $driver) { * recorded and it stays subject to the idle threshold. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testNonPersistentSessionHasNoExpiry(string $driver) { @@ -77,6 +80,7 @@ public function testNonPersistentSessionHasNoExpiry(string $driver) { * A session without refresh keeps its original expiry when resumed. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testResumeKeepsExpiryOfNonRefreshSession(string $driver) { @@ -99,6 +103,7 @@ public function testResumeKeepsExpiryOfNonRefreshSession(string $driver) { * expiry. Resuming it records one. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testResumeRecordsMissingExpiry(string $driver) { @@ -122,6 +127,7 @@ public function testResumeRecordsMissingExpiry(string $driver) { * request. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testResumeRefreshesExpiryOnlyWhenDriftExceedsOneMinute(string $driver) { @@ -150,6 +156,7 @@ public function testResumeRefreshesExpiryOnlyWhenDriftExceedsOneMinute(string $d * recorded expiry (issue #431). * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testSetDurationAndRefreshUpdateRecordedExpiry(string $driver) { diff --git a/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php b/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php index f128bc786..43fdb8835 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php @@ -26,6 +26,7 @@ class SessionLifetimeBugsTest extends TestCase { * StartSessionMiddleware::afterSend() only calls validateStorage(). * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testIssue431DurationAndRefreshArePersisted(string $driver) { @@ -57,6 +58,7 @@ public function testIssue431DurationAndRefreshArePersisted(string $driver) { * expired. * * @test + * @dataProvider timestampStorageProvider */ #[DataProvider('timestampStorageProvider')] public function testIssue432GcRespectsPerSessionLifetime(string $driver) { @@ -96,6 +98,7 @@ public function testIssue432GcRespectsPerSessionLifetime(string $driver) { * checks the expiry that GC actually uses. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testIssue433ResumeExtendsExpiryOfRefreshSession(string $driver) { @@ -157,6 +160,7 @@ public function testIssue434SessionGcIsADuration() { * back to the default duration (120 minutes), not 2 minutes. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testIssue435MissingLifeTimeFallsBackToDefault(string $driver) { diff --git a/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php index af2493769..180971d01 100644 --- a/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php +++ b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php @@ -24,6 +24,7 @@ class SessionUserPersistenceTest extends TestCase { * '_user' key right after setUser(), without any close() call. * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testSetUserWritesToStorage(string $driver) { @@ -47,6 +48,7 @@ public function testSetUserWritesToStorage(string $driver) { * it on resume, including user info modified after setUser(). * * @test + * @dataProvider storageProvider */ #[DataProvider('storageProvider')] public function testUserIsRestoredOnResume(string $driver) { From c6a11f9d218002705f3cba6510a280320975ec37 Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Tue, 17 Nov 2026 09:22:04 +0300 Subject: [PATCH 6/6] ci: pin PHPUnit jobs to ubuntu-24.04 ubuntu-latest moved to Ubuntu 26.04, which no longer provides mysql-client-core-8.0, so every PHP job failed in 'Setup MySQL Client' before running tests. --- .github/workflows/php81.yml | 2 +- .github/workflows/php82.yml | 2 +- .github/workflows/php83.yml | 2 +- .github/workflows/php84.yml | 2 +- .github/workflows/php85.yml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/php81.yml b/.github/workflows/php81.yml index 040645d83..1d2a115cb 100644 --- a/.github/workflows/php81.yml +++ b/.github/workflows/php81.yml @@ -13,7 +13,7 @@ concurrency: jobs: test: if: ${{ !contains(github.event.head_commit.message, 'release-please--branches--main') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 10 env: diff --git a/.github/workflows/php82.yml b/.github/workflows/php82.yml index 4202c987d..12a7998b9 100644 --- a/.github/workflows/php82.yml +++ b/.github/workflows/php82.yml @@ -13,7 +13,7 @@ concurrency: jobs: test: if: ${{ !contains(github.event.head_commit.message, 'release-please--branches--main') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 10 env: diff --git a/.github/workflows/php83.yml b/.github/workflows/php83.yml index 376cce07f..152dbcf03 100644 --- a/.github/workflows/php83.yml +++ b/.github/workflows/php83.yml @@ -13,7 +13,7 @@ concurrency: jobs: test: if: ${{ !contains(github.event.head_commit.message, 'release-please--branches--main') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 10 env: diff --git a/.github/workflows/php84.yml b/.github/workflows/php84.yml index cb9b13c8c..90695c3ef 100644 --- a/.github/workflows/php84.yml +++ b/.github/workflows/php84.yml @@ -13,7 +13,7 @@ concurrency: jobs: test: if: ${{ !contains(github.event.head_commit.message, 'release-please--branches--main') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 10 env: diff --git a/.github/workflows/php85.yml b/.github/workflows/php85.yml index db19512aa..6ae7a6fb6 100644 --- a/.github/workflows/php85.yml +++ b/.github/workflows/php85.yml @@ -13,7 +13,7 @@ concurrency: jobs: test: if: ${{ !contains(github.event.head_commit.message, 'release-please--branches--main') }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 10 env: