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: diff --git a/WebFiori/Framework/Session/CacheSessionStorage.php b/WebFiori/Framework/Session/CacheSessionStorage.php index d0b4f09a9..702650a84 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,7 @@ public function destroy(string $sessionId): void { } $this->storage->delete($this->indexKey($sessionId)); + $this->storage->delete($this->expiryKey($sessionId)); } /** @@ -60,6 +61,15 @@ public function gc(string $olderThan, int $maxCount = 0): void { $this->storage->purgeExpired(); } + /** + * {@inheritdoc} + */ + public function getExpiry(string $sessionId): ?int { + $value = $this->storage->read($this->expiryKey($sessionId), null); + + return is_int($value) ? $value : null; + } + public function getPrefix(): string { return $this->prefix; } @@ -112,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; } @@ -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..dc93b4302 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; /** @@ -76,6 +76,13 @@ public function getController(): SessionDB { return $this->dbController; } + /** + * {@inheritdoc} + */ + public function getExpiry(string $sessionId): ?int { + return $this->dbController->getExpiry($sessionId); + } + /** * {@inheritdoc} */ @@ -97,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 cb36adfc5..c9c870e37 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,11 @@ public function destroy(string $sessionId): void { if (file_exists($path)) { unlink($path); } + $expiryPath = $this->expiryPath($sessionId); + + if (file_exists($expiryPath)) { + unlink($expiryPath); + } } /** @@ -81,22 +87,57 @@ 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 ($expiry !== null) { + $expired = $expiry <= $now; + } else { + $mtime = filemtime($filePath); + $expired = $mtime !== false && $mtime < $threshold; + } - if ($mtime !== false && $mtime < $threshold) { - unlink($filePath); + if ($expired) { + $this->destroy($file); $removed++; } } } + /** + * {@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. */ @@ -186,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} */ @@ -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 @@ + + */ + private static array $expiry = []; /** * Shared in-process store keyed by [session_id][key] => [value, version]. * @@ -42,14 +48,36 @@ class InMemorySessionStorage implements SessionStorage { * @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; } /** @@ -92,6 +120,18 @@ public function remove(string $sessionId, string $key): void { */ public static function reset(): void { self::$store = []; + self::$expiry = []; + } + + /** + * {@inheritdoc} + */ + public function setExpiry(string $sessionId, ?int $expiresAt): void { + if ($expiresAt === null) { + unset(self::$expiry[$sessionId]); + } else { + self::$expiry[$sessionId] = $expiresAt; + } } /** diff --git a/WebFiori/Framework/Session/Session.php b/WebFiori/Framework/Session/Session.php index 9c98b9aae..0ab818e3a 100644 --- a/WebFiori/Framework/Session/Session.php +++ b/WebFiori/Framework/Session/Session.php @@ -44,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. * @@ -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(); + } } } } @@ -936,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()); @@ -963,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); @@ -1014,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(). * @@ -1199,6 +1233,7 @@ private function persistMeta(): void { null, ConflictStrategy::LAST_WRITE_WINS ); + $this->syncExpiry(); } /** * Persists the current session user to the reserved '_user' key. @@ -1222,24 +1257,28 @@ private function persistUser(): void { ); } /** - * Restores the session user from the reserved '_user' key, if present. + * 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 restoreUser(): void { - $entry = SessionsManager::getStorage()->read($this->getId(), '_user'); - - if ($entry === null) { - $this->sessionUser = null; + private function refreshExpiry(): void { + $storage = SessionsManager::getStorage(); + if (!$storage instanceof ExpiringSessionStorage) { return; } - $decrypted = $this->decryptValue($entry['value']); - - if (is_string($decrypted)) { - $restored = @unserialize($decrypted); + $target = $this->computeExpiry(); + $current = $storage->getExpiry($this->getId()); - $this->sessionUser = $restored instanceof SessionUser ? $restored : null; - } else { - $this->sessionUser = null; + 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); } } private function restoreFromPlaintext(string $plaintext): bool { @@ -1266,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); @@ -1284,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 2906329ff..0c4924e48 100644 --- a/WebFiori/Framework/Session/SessionDB.php +++ b/WebFiori/Framework/Session/SessionDB.php @@ -48,6 +48,18 @@ public function __construct($connection = 'sessions-connection') { // is acceptable — per-key operations will fail gracefully at use time. } } + /** + * 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(); + } /** * Creates all session tables (sessions, session_data, session_kv_data). * Called during test setup or initial deployment. @@ -55,6 +67,7 @@ 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(); } /** * 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); @@ -112,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. @@ -192,7 +271,6 @@ public function getSessionKeys(string $sId): array { return $result; } - /** * Returns an array that holds the IDs of sessions which are older than * specific date and time. @@ -294,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. * @@ -397,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. @@ -423,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/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..8fc97c43d --- /dev/null +++ b/tests/WebFiori/Framework/Tests/Session/ExpiringSessionStorageTest.php @@ -0,0 +1,225 @@ +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'); + $storage->setExpiry('destroy-me', time() + 3600); + + $storage->destroy('destroy-me'); + + $this->assertNull($storage->getExpiry('destroy-me')); + } + + /** + * @test + * @dataProvider storageProvider + */ + #[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 + */ + #[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 without a recorded expiry (created before upgrade, or with a + * 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'); + $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 + */ + #[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); + } + + /** + * Sessions that have an expiry are removed by gc() only once it passed, + * whatever the idle threshold says. + * + * @test + * @dataProvider storageProvider + */ + #[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 + * must add the column. + * + * @test + * @dataProvider databaseStorageProvider + */ + #[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')); + } + + /** + * 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); + } + 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 new file mode 100644 index 000000000..b0ceb91a9 --- /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 = ''; + /** @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'], + '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'], + ]; + } + + /** + * 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(); + } + + 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'."); + } + + /** + * 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 new file mode 100644 index 000000000..6d2bfe91b --- /dev/null +++ b/tests/WebFiori/Framework/Tests/Session/SessionExpiryTest.php @@ -0,0 +1,236 @@ +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 + */ + #[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 + */ + #[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 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); + $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. + * + * @test + * @dataProvider storageProvider + */ + #[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 + */ + #[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); + } + + /** + * setDuration() and setIsRefresh() on a running session update the + * recorded expiry (issue #431). + * + * @test + * @dataProvider storageProvider + */ + #[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); + } + + /** + * 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()); + } + use SessionDriversTrait; + + 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..43fdb8835 --- /dev/null +++ b/tests/WebFiori/Framework/Tests/Session/SessionLifetimeBugsTest.php @@ -0,0 +1,205 @@ +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 #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 + */ + #[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 #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 + */ + #[DataProvider('storageProvider')] + public function testIssue433ResumeExtendsExpiryOfRefreshSession(string $driver) { + $storage = $this->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 #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 + */ + #[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)." + ); + } + use SessionDriversTrait; + + 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/SessionUserPersistenceTest.php b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php new file mode 100644 index 000000000..180971d01 --- /dev/null +++ b/tests/WebFiori/Framework/Tests/Session/SessionUserPersistenceTest.php @@ -0,0 +1,94 @@ +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 + * it on resume, including user info modified after setUser(). + * + * @test + * @dataProvider storageProvider + */ + #[DataProvider('storageProvider')] + public function testUserIsRestoredOnResume(string $driver) { + SessionsManager::setStorage($this->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()); + } + use SessionDriversTrait; + + protected function setUp(): void { + parent::setUp(); + InMemorySessionStorage::reset(); + } + + protected function tearDown(): void { + $this->cleanupDrivers(); + SessionsManager::setStorage(new InMemorySessionStorage()); + parent::tearDown(); + } +}