From 33e6daddd8b14ab9a9f353e8011930a674e11905 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Thu, 12 Nov 2026 00:37:24 +0100 Subject: [PATCH 1/4] fix(Cache): reject directory traversal sequences and separators in FileHandler::validateKey() The file handler concatenates the cache key with the cache store path, so a key that contains a directory separator or a traversal sequence can address files outside the cache directory. BaseHandler::validateKey() only rejects such characters when Config\Cache::$reservedCharacters happens to contain them, and that setting is commonly emptied when several handlers share the same keys (for example file storage next to Redis). FileHandler::validateKey() now always rejects "/", "\", a null byte, and traversal sequences ("..") in both the key and the prefix, independently of the configured reservedCharacters, throwing CodeIgniter\Exceptions\InvalidArgumentException. Valid keys keep the existing PSR-6 validation and hashing behaviour. --- system/Cache/Handlers/FileHandler.php | 29 ++++++++ .../system/Cache/Handlers/FileHandlerTest.php | 70 +++++++++++++++++++ 2 files changed, 99 insertions(+) diff --git a/system/Cache/Handlers/FileHandler.php b/system/Cache/Handlers/FileHandler.php index 9c00998c1f85..38678dad4b0c 100644 --- a/system/Cache/Handlers/FileHandler.php +++ b/system/Cache/Handlers/FileHandler.php @@ -14,6 +14,7 @@ namespace CodeIgniter\Cache\Handlers; use CodeIgniter\Cache\Exceptions\CacheException; +use CodeIgniter\Exceptions\InvalidArgumentException; use CodeIgniter\I18n\Time; use Config\Cache; use FilesystemIterator; @@ -76,6 +77,34 @@ public function initialize(): void { } + /** + * Validates a cache key, ensuring it contains no directory traversal sequences + * or path separators, regardless of the configured reservedCharacters setting. + * + * @param mixed $key The key to validate + * @param string $prefix Optional prefix to include in length calculations + * + * @throws InvalidArgumentException When $key is not valid or contains path separators + */ + public static function validateKey($key, $prefix = ''): string + { + if (! is_string($key)) { + throw new InvalidArgumentException('Cache key must be a string'); + } + + $target = $prefix . $key; + + if ( + $target === '' + || strpbrk($target, "/\\:\0") !== false + || trim($target, '. ') === '' + ) { + throw new InvalidArgumentException('Cache key cannot contain directory separators or traversal sequences.'); + } + + return parent::validateKey($key, $prefix); + } + public function get(string $key): mixed { $key = static::validateKey($key, $this->prefix); diff --git a/tests/system/Cache/Handlers/FileHandlerTest.php b/tests/system/Cache/Handlers/FileHandlerTest.php index 310b5a7ebce7..0cf47adc9b8a 100644 --- a/tests/system/Cache/Handlers/FileHandlerTest.php +++ b/tests/system/Cache/Handlers/FileHandlerTest.php @@ -16,6 +16,7 @@ use CodeIgniter\Cache\CacheFactory; use CodeIgniter\Cache\Exceptions\CacheException; use CodeIgniter\CLI\CLI; +use CodeIgniter\Exceptions\InvalidArgumentException; use CodeIgniter\I18n\Time; use Config\Cache; use PHPUnit\Framework\Attributes\DataProvider; @@ -504,4 +505,73 @@ public function testReconnect(): void { $this->assertTrue($this->handler->reconnect()); } + + #[DataProvider('provideValidateKeyRejectsTraversalAndSeparatorsEvenWithEmptyReservedCharacters')] + public function testValidateKeyRejectsTraversalAndSeparatorsEvenWithEmptyReservedCharacters(string $key): void + { + $config = config('Cache'); + $originalReservedCharacters = $config->reservedCharacters; + + // Multi-store setups often empty this setting to share keys between + // handlers, which must not weaken the file handler's own validation. + $config->reservedCharacters = ''; + + try { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key cannot contain directory separators or traversal sequences.'); + + FileHandler::validateKey($key); + } finally { + $config->reservedCharacters = $originalReservedCharacters; + } + } + + /** + * @return iterable + */ + public static function provideValidateKeyRejectsTraversalAndSeparatorsEvenWithEmptyReservedCharacters(): iterable + { + yield 'parent traversal only' => ['..']; + + yield 'current directory only' => ['.']; + + yield 'multiple dots' => ['...']; + + yield 'dots with trailing space' => ['.. ']; + + yield 'parent directory' => ['../evil']; + + yield 'nested traversal' => ['sub/../../evil']; + + yield 'forward slash separator' => ['sub/key']; + + yield 'backslash separator' => ['sub\\key']; + + yield 'null byte' => ["sub\0key"]; + + yield 'colon character' => ['test:stream']; + + yield 'drive letter' => ['C:file']; + + yield 'spaces and dots' => [' . ']; + } + + public function testValidateKeyRejectsTraversalInPrefix(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key cannot contain directory separators or traversal sequences.'); + + FileHandler::validateKey('valid_key', '../'); + } + + public function testValidateKeySuccess(): void + { + $this->assertSame('valid_key', FileHandler::validateKey('valid_key')); + $this->assertSame('foo..json', FileHandler::validateKey('foo..json')); + $this->assertSame('user..settings', FileHandler::validateKey('user..settings')); + $this->assertSame('..item', FileHandler::validateKey('..item')); + $this->assertSame('..item', FileHandler::validateKey('item', '..')); + $this->assertSame('item..', FileHandler::validateKey('item..')); + $this->assertSame('..foo', FileHandler::validateKey('..foo')); + } } From 3657a1848f201e9cde45095a6d77d4ccca37920a Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sun, 15 Nov 2026 02:49:54 +0100 Subject: [PATCH 2/4] fix(Cache): reject separators and dot-only prefixes in validateKey() - validate the file name returned by parent::validateKey(), so keys over MAX_KEY_LENGTH are still hashed before validation - reject only "/", "\" and null bytes, keeping characters that are valid in file names on Linux and macOS - reject a prefix that consists only of dots and spaces, because such a prefix makes every cache file hidden: getCacheInfo() does not report it, deleteMatching() does not remove it and clean() does not delete it - document the risks of relaxing reservedCharacters and the behavior change --- docs/installation/upgrade_477.md | 6 + docs/libraries/caching.md | 18 +- system/Cache/Handlers/FileHandler.php | 39 +- .../system/Cache/Handlers/FileHandlerTest.php | 389 ++++++++++++++++-- 4 files changed, 400 insertions(+), 52 deletions(-) diff --git a/docs/installation/upgrade_477.md b/docs/installation/upgrade_477.md index 082aa62c50e8..2cc4f116300a 100644 --- a/docs/installation/upgrade_477.md +++ b/docs/installation/upgrade_477.md @@ -10,6 +10,12 @@ Please refer to the upgrade instructions corresponding to your installation meth ## Breaking Changes +### File Cache Rejects Directory Separators and Dot-Only Prefixes + +For security reasons, `FileHandler::validateKey()` now rejects `/`, `\` and null bytes in the cache item file name, independently of the `Config\Cache::$reservedCharacters` setting. A cache key can no longer point outside the cache directory when that setting is relaxed. + +With the default configuration most applications are unaffected, because `/`, `\` and `:` are already reserved characters. Applications that emptied `$reservedCharacters` to share one key namespace between handlers and used directory separators in File cache keys now get an `InvalidArgumentException`. Build keys from identifiers with a controlled format, or hash the input, instead of relaxing `$reservedCharacters`. See [Caching](../libraries/caching.md). A `$prefix` that consists only of dots and spaces is rejected as well, because it would make every cache file a hidden file that `getCacheInfo()` does not report, `deleteMatching()` does not remove and `clean()` does not delete. + ## Breaking Enhancements ## Project Files diff --git a/docs/libraries/caching.md b/docs/libraries/caching.md index b9109dcdd4ca..1ef55681a2de 100644 --- a/docs/libraries/caching.md +++ b/docs/libraries/caching.md @@ -46,12 +46,28 @@ In the case that the first choice `$handler` is not available, this is the next If you have more than one application using the same cache storage, you can add a custom prefix string here that is prepended to all key names. +The File handler rejects a prefix that consists only of dots and spaces. Such a prefix would turn every cache file into a hidden file, which `getCacheInfo()` does not report, `deleteMatching()` does not remove and `clean()` does not delete. A prefix that merely starts with a dot, such as `.app`, is still accepted for backward compatibility, even though it also produces hidden files. + ### $ttl The default number of seconds to save items when none is specified. WARNING: This is not used by framework handlers where 60 seconds is hard-coded, but may be useful to projects and modules. This will replace the hard-coded value in a future release. +### $reservedCharacters + +A string of characters that are not allowed in cache keys or tags. Handlers throw an `InvalidArgumentException` when a key contains one of them. The default, `{}()/\@:`, is required for PSR-6 compliance. + +Relaxing `$reservedCharacters` relaxes key validation for every cache handler. The File handler still rejects `/`, `\` and null bytes in the resulting file name, so a cache key cannot point outside the cache directory. The characters left in `$reservedCharacters` still keep keys from being interpreted differently by a handler or by the file system. + +On Windows, keep `:` reserved: it separates an NTFS alternate data stream, so a key such as `file:stream` refers to a stream of a file in the cache directory rather than to a new cache item. + +Do not use unvalidated user input directly as a cache key. Build keys from identifiers with a controlled format, or hash the input: + +```php +$key = 'search_' . hash('sha256', $userInput); +``` + ### $file This is an array of settings specific to the **File** handler to determine how it should save the cache files. @@ -310,7 +326,7 @@ var_dump($cache->getMetadata('my_cached_item')); - **Return type**: `string` -This method is used by handler methods to check that keys are valid. It will throw an `InvalidArgumentException` for non-strings, invalid characters, and empty lengths. +This method is used by handler methods to check that keys are valid. It will throw an `InvalidArgumentException` for non-strings, invalid characters, and empty lengths. The File handler additionally rejects `/`, `\` and null bytes in the resulting file name, even when `Config\Cache::$reservedCharacters` is relaxed. It also rejects a prefix that consists only of dots and spaces. Example: diff --git a/system/Cache/Handlers/FileHandler.php b/system/Cache/Handlers/FileHandler.php index 38678dad4b0c..39cef78b47d5 100644 --- a/system/Cache/Handlers/FileHandler.php +++ b/system/Cache/Handlers/FileHandler.php @@ -78,31 +78,42 @@ public function initialize(): void } /** - * Validates a cache key, ensuring it contains no directory traversal sequences - * or path separators, regardless of the configured reservedCharacters setting. + * Validates a cache key and returns the file name the item is stored under. + * + * The file name must not contain a directory separator or a null byte, so a + * cache item can never be written outside the cache directory, even when + * `Config\Cache::$reservedCharacters` is relaxed. Other characters are left + * to the configured reserved characters, because rejecting characters that + * are valid in file names on some platforms would break existing keys. + * + * A prefix made only of dots and spaces is rejected as well, because it + * would turn every cache file into a hidden file that `getCacheInfo()` does + * not report, `deleteMatching()` does not remove and + * `clean()` does not delete. * * @param mixed $key The key to validate * @param string $prefix Optional prefix to include in length calculations * - * @throws InvalidArgumentException When $key is not valid or contains path separators + * @throws InvalidArgumentException When $key is not valid, the resulting + * file name contains a directory separator + * or a null byte, or $prefix consists only + * of dots and spaces */ public static function validateKey($key, $prefix = ''): string { - if (! is_string($key)) { - throw new InvalidArgumentException('Cache key must be a string'); - } + // Parent validation also hashes keys that exceed MAX_KEY_LENGTH, so + // validate the returned file name and not the raw key. + $key = parent::validateKey($key, $prefix); - $target = $prefix . $key; + if ($prefix !== '' && trim($prefix, '. ') === '') { + throw new InvalidArgumentException('Cache key prefix cannot consist only of dots and spaces.'); + } - if ( - $target === '' - || strpbrk($target, "/\\:\0") !== false - || trim($target, '. ') === '' - ) { - throw new InvalidArgumentException('Cache key cannot contain directory separators or traversal sequences.'); + if (strpbrk($key, '/\\') !== false || str_contains($key, "\0")) { + throw new InvalidArgumentException('Cache key cannot contain directory separators or null bytes.'); } - return parent::validateKey($key, $prefix); + return $key; } public function get(string $key): mixed diff --git a/tests/system/Cache/Handlers/FileHandlerTest.php b/tests/system/Cache/Handlers/FileHandlerTest.php index 0cf47adc9b8a..784233ec3647 100644 --- a/tests/system/Cache/Handlers/FileHandlerTest.php +++ b/tests/system/Cache/Handlers/FileHandlerTest.php @@ -31,6 +31,7 @@ final class FileHandlerTest extends AbstractHandlerTestCase { private static string $directory = 'FileHandler'; private Cache $config; + private string $originalReservedCharacters; protected function setUp(): void { @@ -40,6 +41,9 @@ protected function setUp(): void helper('filesystem'); } + // Restored in tearDown() so a relaxed setting cannot leak into another test. + $this->originalReservedCharacters = config('Cache')->reservedCharacters; + // Initialize path $this->config = new Cache(); $this->config->file['storePath'] .= self::$directory; @@ -53,6 +57,10 @@ protected function setUp(): void protected function tearDown(): void { + if (isset($this->originalReservedCharacters)) { + config('Cache')->reservedCharacters = $this->originalReservedCharacters; + } + parent::tearDown(); if (is_dir($this->config->file['storePath'])) { @@ -506,72 +514,379 @@ public function testReconnect(): void $this->assertTrue($this->handler->reconnect()); } - #[DataProvider('provideValidateKeyRejectsTraversalAndSeparatorsEvenWithEmptyReservedCharacters')] - public function testValidateKeyRejectsTraversalAndSeparatorsEvenWithEmptyReservedCharacters(string $key): void + #[DataProvider('provideValidateKeyRejectsSeparatorsAndNullBytes')] + public function testValidateKeyRejectsSeparatorsAndNullBytes(string $key, string $prefix): void { - $config = config('Cache'); - $originalReservedCharacters = $config->reservedCharacters; - // Multi-store setups often empty this setting to share keys between // handlers, which must not weaken the file handler's own validation. - $config->reservedCharacters = ''; + config('Cache')->reservedCharacters = ''; - try { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Cache key cannot contain directory separators or traversal sequences.'); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key cannot contain directory separators or null bytes.'); - FileHandler::validateKey($key); - } finally { - $config->reservedCharacters = $originalReservedCharacters; - } + FileHandler::validateKey($key, $prefix); } /** - * @return iterable + * @return iterable */ - public static function provideValidateKeyRejectsTraversalAndSeparatorsEvenWithEmptyReservedCharacters(): iterable + public static function provideValidateKeyRejectsSeparatorsAndNullBytes(): iterable + { + yield 'parent traversal' => ['../evil', '']; + + yield 'nested traversal' => ['sub/../../evil', '']; + + yield 'backslash traversal' => ['..\\evil', '']; + + yield 'forward slash separator' => ['sub/key', '']; + + yield 'backslash separator' => ['sub\\key', '']; + + yield 'forward slash only' => ['/', '']; + + yield 'backslash only' => ['\\', '']; + + yield 'null byte only' => ["\0", '']; + + yield 'null byte inside key' => ["sub\0key", '']; + + yield 'parent traversal in prefix' => ['key', '../']; + + yield 'backslash traversal in prefix' => ['key', '..\\']; + + yield 'null byte in prefix' => ['key', "a\0b"]; + + yield 'forward slash in prefix' => ['key', 'pre/']; + + yield 'absolute path' => ['/etc/passwd', '']; + + yield 'trailing slash in key' => ['key/', '']; + + yield 'mixed separators' => ['a/b\\c', '']; + + yield 'backslash and zero at start' => ['\\0key', '']; + + yield 'backslash and zero at end' => ['key\\0', '']; + + yield 'single slash prefix' => ['key', '/']; + + yield 'backslash zero prefix' => ['key', '\\0']; + + // trim() strips the leading and trailing dots only, so the remaining + // backslashes make this prefix pass the dot-only check. + yield 'escaped traversal in prefix' => ['key', '..\\\\..\\\\']; + } + + #[DataProvider('provideValidateKeyRejectsDotOnlyPrefix')] + public function testValidateKeyRejectsDotOnlyPrefix(string $key, string $prefix): void + { + config('Cache')->reservedCharacters = ''; + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key prefix cannot consist only of dots and spaces.'); + + FileHandler::validateKey($key, $prefix); + } + + /** + * @return iterable + */ + public static function provideValidateKeyRejectsDotOnlyPrefix(): iterable + { + yield 'dot' => ['key', '.']; + + yield 'two dots' => ['key', '..']; + + yield 'three dots' => ['key', '...']; + + yield 'two dots and a space' => ['key', '.. ']; + + yield 'spaces around a dot' => ['key', ' . ']; + + yield 'space only' => ['key', ' ']; + + yield 'spaces only' => ['key', ' ']; + + yield 'prefix with dots and plain key' => ['item', '..']; + } + + #[DataProvider('provideValidateKeyAcceptsHarmlessNames')] + public function testValidateKeyAcceptsHarmlessNames(string $key, string $prefix, string $expected): void + { + config('Cache')->reservedCharacters = ''; + + $this->assertSame($expected, FileHandler::validateKey($key, $prefix)); + } + + /** + * @return iterable + */ + public static function provideValidateKeyAcceptsHarmlessNames(): iterable + { + yield 'plain key' => ['valid_key', '', 'valid_key']; + + yield 'dots before extension' => ['foo..json', '', 'foo..json']; + + yield 'dots inside name' => ['user..settings', '', 'user..settings']; + + yield 'leading dots' => ['..item', '', '..item']; + + yield 'trailing dots' => ['item..', '', 'item..']; + + yield 'double leading dots' => ['..foo', '', '..foo']; + + yield 'three dots' => ['...', '', '...']; + + yield 'single dot' => ['.', '', '.']; + + yield 'two dots' => ['..', '', '..']; + + yield 'dots with trailing space' => ['.. ', '', '.. ']; + + yield 'spaces and dots' => [' . ', '', ' . ']; + + yield 'colon character' => ['test:stream', '', 'test:stream']; + + yield 'drive letter' => ['C:file', '', 'C:file']; + + yield 'dot but not dot-only prefix' => ['key', '.app', '.appkey']; + + yield 'colon in prefix' => ['key', 'app:', 'app:key']; + + yield 'underscore in prefix' => ['key', 'app_', 'app_key']; + + yield 'non-ASCII key' => ['zażółć_gęślą_jaźń', '', 'zażółć_gęślą_jaźń']; + } + + public function testValidateKeyHashesLongKeyBeforeValidatingName(): void + { + config('Cache')->reservedCharacters = ''; + + // A key of nothing but dots used to be rejected before hashing. + $dots = str_repeat('.', 500); + $this->assertSame(md5($dots), FileHandler::validateKey($dots)); + + // The parent hashes the key before the file name is validated. + $key = str_repeat('a', 300) . '/evil'; + $this->assertSame(md5($key), FileHandler::validateKey($key)); + + $longKey = str_repeat('a', 300); + $this->assertSame('pre_' . md5($longKey), FileHandler::validateKey($longKey, 'pre_')); + } + + public function testValidateKeyKeepsMaxLengthBoundary(): void { - yield 'parent traversal only' => ['..']; + $atLimit = str_repeat('a', 255); + $this->assertSame($atLimit, FileHandler::validateKey($atLimit)); - yield 'current directory only' => ['.']; + // One byte over the limit is hashed, so the file name stays short. + $overLimit = str_repeat('a', 256); + $this->assertSame(md5($overLimit), FileHandler::validateKey($overLimit)); - yield 'multiple dots' => ['...']; + // The prefix is counted in the limit but is never hashed. + $prefixKey = str_repeat('a', 251); + $this->assertSame('pre_' . $prefixKey, FileHandler::validateKey($prefixKey, 'pre_')); - yield 'dots with trailing space' => ['.. ']; + $prefixOver = str_repeat('a', 252); + $this->assertSame('pre_' . md5($prefixOver), FileHandler::validateKey($prefixOver, 'pre_')); + } - yield 'parent directory' => ['../evil']; + public function testValidateKeyRejectsTraversalInPrefixOfHashedKey(): void + { + config('Cache')->reservedCharacters = ''; - yield 'nested traversal' => ['sub/../../evil']; + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key cannot contain directory separators or null bytes.'); - yield 'forward slash separator' => ['sub/key']; + // The prefix is not hashed, so a separator in it must still be rejected. + FileHandler::validateKey(str_repeat('a', 300), '../'); + } - yield 'backslash separator' => ['sub\\key']; + public function testValidateKeyRejectsDotOnlyPrefixOfHashedKey(): void + { + config('Cache')->reservedCharacters = ''; - yield 'null byte' => ["sub\0key"]; + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key prefix cannot consist only of dots and spaces.'); - yield 'colon character' => ['test:stream']; + // Hashing the key must not bypass the prefix check. + FileHandler::validateKey(str_repeat('a', 300), '.'); + } - yield 'drive letter' => ['C:file']; + public function testValidateKeyRejectsEmptyKey(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key cannot be empty.'); - yield 'spaces and dots' => [' . ']; + FileHandler::validateKey(''); } - public function testValidateKeyRejectsTraversalInPrefix(): void + public function testValidateKeyRejectsNonStringKey(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Cache key cannot contain directory separators or traversal sequences.'); + $this->expectExceptionMessage('Cache key must be a string'); - FileHandler::validateKey('valid_key', '../'); + FileHandler::validateKey(42); } - public function testValidateKeySuccess(): void + public function testValidateKeyRejectsReservedCharacters(): void + { + // Set the default explicitly: this test documents the default reserved + // characters, so it must not depend on the configured app value. + config('Cache')->reservedCharacters = '{}()/\@:'; + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key contains reserved characters {}()/\@:'); + + FileHandler::validateKey('sub/key'); + } + + #[DataProvider('provideValidateKeyRejectsEveryDefaultReservedCharacter')] + public function testValidateKeyRejectsEveryDefaultReservedCharacter(string $char): void + { + config('Cache')->reservedCharacters = '{}()/\@:'; + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key contains reserved characters {}()/\@:'); + + FileHandler::validateKey('a' . $char . 'b'); + } + + /** + * @return iterable + */ + public static function provideValidateKeyRejectsEveryDefaultReservedCharacter(): iterable + { + return [ + ['{'], + ['}'], + ['('], + [')'], + ['/'], + ['\\'], + ['@'], + [':'], + ]; + } + + public function testValidateKeyAcceptsValidKeyWithDefaultConfig(): void { $this->assertSame('valid_key', FileHandler::validateKey('valid_key')); - $this->assertSame('foo..json', FileHandler::validateKey('foo..json')); - $this->assertSame('user..settings', FileHandler::validateKey('user..settings')); - $this->assertSame('..item', FileHandler::validateKey('..item')); - $this->assertSame('..item', FileHandler::validateKey('item', '..')); - $this->assertSame('item..', FileHandler::validateKey('item..')); - $this->assertSame('..foo', FileHandler::validateKey('..foo')); + } + + public function testValidateKeyAcceptsFalsyStringKey(): void + { + // "0" is falsy but a perfectly valid cache key. + $this->assertSame('0', FileHandler::validateKey('0')); + } + + public function testValidateKeySuccessWithPrefix(): void + { + $this->assertSame('prefixvalid_key', FileHandler::validateKey('valid_key', 'prefix')); + } + + public function testDottedKeySurvivesFullLifecycle(): void + { + $this->assertTrue($this->handler->save('..item', 'value')); + $this->assertSame('value', $this->handler->get('..item')); + $this->assertTrue($this->handler->delete('..item')); + } + + public function testDottedDirectoryKeyIsNotWritten(): void + { + // No regression from before the pull request: the path resolves to a + // directory, so is_file() and fopen() keep the item from being stored. + $this->assertFalse($this->handler->save('..', 'value')); + $this->assertNull($this->handler->get('..')); + $this->assertFalse($this->handler->delete('..')); + } + + public function testIncrementRejectsTraversalKey(): void + { + config('Cache')->reservedCharacters = ''; + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key cannot contain directory separators or null bytes.'); + + $this->handler->increment('../counter'); + } + + public function testPublicApiRejectsSeparatorWithDefaultConfig(): void + { + config('Cache')->reservedCharacters = '{}()/\@:'; + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key contains reserved characters {}()/\@:'); + + $this->handler->save('../evil', 'value'); + } + + public function testDotOnlyPrefixFromConfigIsRejectedByPublicApi(): void + { + $config = new Cache(); + $config->prefix = '..'; + $config->file['storePath'] = $this->config->file['storePath']; + + $handler = CacheFactory::getHandler($config, 'file'); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cache key prefix cannot consist only of dots and spaces.'); + + $handler->save('key', 'value'); + } + + /** + * A relaxed reserved character list must not turn the public API into a way + * to read or write files outside the cache directory. + */ + public function testTraversalThroughPublicApiDoesNotLeaveCacheDirectory(): void + { + // The weakened configuration is the very scenario the separators check + // has to cover, so it must not be rejected by the reserved list instead. + config('Cache')->reservedCharacters = ''; + + $victim = dirname($this->config->file['storePath']) . DIRECTORY_SEPARATOR . 'victim_' . uniqid('', true); + $this->assertNotFalse(file_put_contents($victim, 'original')); + + try { + foreach (['../' . basename($victim), '..\\' . basename($victim)] as $key) { + try { + $this->handler->save($key, 'overwritten'); + $this->fail('save() accepted the traversal key "' . $key . '".'); + } catch (InvalidArgumentException $e) { + $this->assertSame('Cache key cannot contain directory separators or null bytes.', $e->getMessage()); + } + + try { + $this->handler->delete($key); + $this->fail('delete() accepted the traversal key "' . $key . '".'); + } catch (InvalidArgumentException $e) { + $this->assertSame('Cache key cannot contain directory separators or null bytes.', $e->getMessage()); + } + + try { + $this->handler->getMetaData($key); + $this->fail('getMetaData() accepted the traversal key "' . $key . '".'); + } catch (InvalidArgumentException $e) { + $this->assertSame('Cache key cannot contain directory separators or null bytes.', $e->getMessage()); + } + } + + $this->assertSame('original', file_get_contents($victim)); + } finally { + @unlink($victim); + } + } + + #[RequiresOperatingSystem('Linux|Darwin')] + public function testWeakenedReservedCharactersAllowsColonInFileName(): void + { + // Rejecting separators must not reject characters that are valid in + // file names, otherwise relaxing the reserved list would do nothing. + config('Cache')->reservedCharacters = ''; + + $this->assertTrue($this->handler->save('test:stream', 'value')); + $this->assertSame('value', $this->handler->get('test:stream')); + $this->assertTrue($this->handler->delete('test:stream')); } } From 685658769819f1bc79a6a172199ed7dd425acf51 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sun, 15 Nov 2026 19:52:23 +0100 Subject: [PATCH 3/4] revert restriction on dot-only cache key prefixes in FileHandler --- docs/installation/upgrade_477.md | 4 +- docs/libraries/caching.md | 4 +- system/Cache/Handlers/FileHandler.php | 14 +--- .../system/Cache/Handlers/FileHandlerTest.php | 68 +++++++------------ 4 files changed, 28 insertions(+), 62 deletions(-) diff --git a/docs/installation/upgrade_477.md b/docs/installation/upgrade_477.md index 2cc4f116300a..bfa87dc80d72 100644 --- a/docs/installation/upgrade_477.md +++ b/docs/installation/upgrade_477.md @@ -10,11 +10,11 @@ Please refer to the upgrade instructions corresponding to your installation meth ## Breaking Changes -### File Cache Rejects Directory Separators and Dot-Only Prefixes +### File Cache Rejects Directory Separators For security reasons, `FileHandler::validateKey()` now rejects `/`, `\` and null bytes in the cache item file name, independently of the `Config\Cache::$reservedCharacters` setting. A cache key can no longer point outside the cache directory when that setting is relaxed. -With the default configuration most applications are unaffected, because `/`, `\` and `:` are already reserved characters. Applications that emptied `$reservedCharacters` to share one key namespace between handlers and used directory separators in File cache keys now get an `InvalidArgumentException`. Build keys from identifiers with a controlled format, or hash the input, instead of relaxing `$reservedCharacters`. See [Caching](../libraries/caching.md). A `$prefix` that consists only of dots and spaces is rejected as well, because it would make every cache file a hidden file that `getCacheInfo()` does not report, `deleteMatching()` does not remove and `clean()` does not delete. +With the default configuration most applications are unaffected, because `/`, `\` and `:` are already reserved characters. Applications that emptied `$reservedCharacters` to share one key namespace between handlers and used directory separators in File cache keys now get an `InvalidArgumentException`. Build keys from identifiers with a controlled format, or hash the input, instead of relaxing `$reservedCharacters`. See [Caching](../libraries/caching.md). ## Breaking Enhancements diff --git a/docs/libraries/caching.md b/docs/libraries/caching.md index 1ef55681a2de..5a1394908f0a 100644 --- a/docs/libraries/caching.md +++ b/docs/libraries/caching.md @@ -46,8 +46,6 @@ In the case that the first choice `$handler` is not available, this is the next If you have more than one application using the same cache storage, you can add a custom prefix string here that is prepended to all key names. -The File handler rejects a prefix that consists only of dots and spaces. Such a prefix would turn every cache file into a hidden file, which `getCacheInfo()` does not report, `deleteMatching()` does not remove and `clean()` does not delete. A prefix that merely starts with a dot, such as `.app`, is still accepted for backward compatibility, even though it also produces hidden files. - ### $ttl The default number of seconds to save items when none is specified. @@ -326,7 +324,7 @@ var_dump($cache->getMetadata('my_cached_item')); - **Return type**: `string` -This method is used by handler methods to check that keys are valid. It will throw an `InvalidArgumentException` for non-strings, invalid characters, and empty lengths. The File handler additionally rejects `/`, `\` and null bytes in the resulting file name, even when `Config\Cache::$reservedCharacters` is relaxed. It also rejects a prefix that consists only of dots and spaces. +This method is used by handler methods to check that keys are valid. It will throw an `InvalidArgumentException` for non-strings, invalid characters, and empty lengths. The File handler additionally rejects `/`, `\` and null bytes in the resulting file name, even when `Config\Cache::$reservedCharacters` is relaxed. Example: diff --git a/system/Cache/Handlers/FileHandler.php b/system/Cache/Handlers/FileHandler.php index 39cef78b47d5..cc24df2c1219 100644 --- a/system/Cache/Handlers/FileHandler.php +++ b/system/Cache/Handlers/FileHandler.php @@ -86,18 +86,12 @@ public function initialize(): void * to the configured reserved characters, because rejecting characters that * are valid in file names on some platforms would break existing keys. * - * A prefix made only of dots and spaces is rejected as well, because it - * would turn every cache file into a hidden file that `getCacheInfo()` does - * not report, `deleteMatching()` does not remove and - * `clean()` does not delete. - * * @param mixed $key The key to validate * @param string $prefix Optional prefix to include in length calculations * - * @throws InvalidArgumentException When $key is not valid, the resulting + * @throws InvalidArgumentException When $key is not valid or the resulting * file name contains a directory separator - * or a null byte, or $prefix consists only - * of dots and spaces + * or a null byte */ public static function validateKey($key, $prefix = ''): string { @@ -105,10 +99,6 @@ public static function validateKey($key, $prefix = ''): string // validate the returned file name and not the raw key. $key = parent::validateKey($key, $prefix); - if ($prefix !== '' && trim($prefix, '. ') === '') { - throw new InvalidArgumentException('Cache key prefix cannot consist only of dots and spaces.'); - } - if (strpbrk($key, '/\\') !== false || str_contains($key, "\0")) { throw new InvalidArgumentException('Cache key cannot contain directory separators or null bytes.'); } diff --git a/tests/system/Cache/Handlers/FileHandlerTest.php b/tests/system/Cache/Handlers/FileHandlerTest.php index 784233ec3647..5a0e057bb349 100644 --- a/tests/system/Cache/Handlers/FileHandlerTest.php +++ b/tests/system/Cache/Handlers/FileHandlerTest.php @@ -572,44 +572,9 @@ public static function provideValidateKeyRejectsSeparatorsAndNullBytes(): iterab yield 'backslash zero prefix' => ['key', '\\0']; - // trim() strips the leading and trailing dots only, so the remaining - // backslashes make this prefix pass the dot-only check. yield 'escaped traversal in prefix' => ['key', '..\\\\..\\\\']; } - #[DataProvider('provideValidateKeyRejectsDotOnlyPrefix')] - public function testValidateKeyRejectsDotOnlyPrefix(string $key, string $prefix): void - { - config('Cache')->reservedCharacters = ''; - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Cache key prefix cannot consist only of dots and spaces.'); - - FileHandler::validateKey($key, $prefix); - } - - /** - * @return iterable - */ - public static function provideValidateKeyRejectsDotOnlyPrefix(): iterable - { - yield 'dot' => ['key', '.']; - - yield 'two dots' => ['key', '..']; - - yield 'three dots' => ['key', '...']; - - yield 'two dots and a space' => ['key', '.. ']; - - yield 'spaces around a dot' => ['key', ' . ']; - - yield 'space only' => ['key', ' ']; - - yield 'spaces only' => ['key', ' ']; - - yield 'prefix with dots and plain key' => ['item', '..']; - } - #[DataProvider('provideValidateKeyAcceptsHarmlessNames')] public function testValidateKeyAcceptsHarmlessNames(string $key, string $prefix, string $expected): void { @@ -649,6 +614,20 @@ public static function provideValidateKeyAcceptsHarmlessNames(): iterable yield 'drive letter' => ['C:file', '', 'C:file']; + yield 'dot prefix' => ['key', '.', '.key']; + + yield 'two dots prefix' => ['item', '..', '..item']; + + yield 'three dots prefix' => ['key', '...', '...key']; + + yield 'two dots and a space prefix' => ['key', '.. ', '.. key']; + + yield 'spaces around a dot prefix' => ['key', ' . ', ' . key']; + + yield 'space only prefix' => ['key', ' ', ' key']; + + yield 'spaces only prefix' => ['key', ' ', ' key']; + yield 'dot but not dot-only prefix' => ['key', '.app', '.appkey']; yield 'colon in prefix' => ['key', 'app:', 'app:key']; @@ -702,15 +681,13 @@ public function testValidateKeyRejectsTraversalInPrefixOfHashedKey(): void FileHandler::validateKey(str_repeat('a', 300), '../'); } - public function testValidateKeyRejectsDotOnlyPrefixOfHashedKey(): void + public function testValidateKeyHashesLongKeyWithDotPrefix(): void { config('Cache')->reservedCharacters = ''; - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Cache key prefix cannot consist only of dots and spaces.'); + $key = str_repeat('a', 300); - // Hashing the key must not bypass the prefix check. - FileHandler::validateKey(str_repeat('a', 300), '.'); + $this->assertSame('.' . md5($key), FileHandler::validateKey($key, '.')); } public function testValidateKeyRejectsEmptyKey(): void @@ -821,18 +798,19 @@ public function testPublicApiRejectsSeparatorWithDefaultConfig(): void $this->handler->save('../evil', 'value'); } - public function testDotOnlyPrefixFromConfigIsRejectedByPublicApi(): void + public function testDotPrefixFromConfigIsHandledSafelyByPublicApi(): void { + config('Cache')->reservedCharacters = ''; + $config = new Cache(); $config->prefix = '..'; $config->file['storePath'] = $this->config->file['storePath']; $handler = CacheFactory::getHandler($config, 'file'); - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Cache key prefix cannot consist only of dots and spaces.'); - - $handler->save('key', 'value'); + $this->assertTrue($handler->save('key', 'value')); + $this->assertSame('value', $handler->get('key')); + $this->assertTrue($handler->delete('key')); } /** From 81de0c6f7cffc115d43c9ae60942f0bfab875323 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Mon, 16 Nov 2026 21:01:58 +0100 Subject: [PATCH 4/4] docs(Cache): document dot-leading cache file limitation --- docs/changelogs/v4.7.7.md | 2 ++ docs/libraries/caching.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/changelogs/v4.7.7.md b/docs/changelogs/v4.7.7.md index 6623106d9e5e..a1bfb1b6ff51 100644 --- a/docs/changelogs/v4.7.7.md +++ b/docs/changelogs/v4.7.7.md @@ -6,6 +6,8 @@ Release Date: Unreleased ## BREAKING +- **Cache:** `FileHandler::validateKey()` now rejects `/`, `\` and null bytes in the cache item file name, independently of `Config\Cache::$reservedCharacters`, so a cache key can no longer point outside the cache directory when that setting is relaxed. See [File Cache Rejects Directory Separators](../installation/upgrade_477.md#file-cache-rejects-directory-separators) for migration instructions. + ## Message Changes - Added the `HTTP.invalidFileName` language string. diff --git a/docs/libraries/caching.md b/docs/libraries/caching.md index 5a1394908f0a..d89313718864 100644 --- a/docs/libraries/caching.md +++ b/docs/libraries/caching.md @@ -70,6 +70,8 @@ $key = 'search_' . hash('sha256', $userInput); This is an array of settings specific to the **File** handler to determine how it should save the cache files. +Cache files whose names start with a dot are not fully supported by the File handler: `getCacheInfo()` does not report them, `deleteMatching()` wildcard patterns do not match them, and `clean()` / `cache:clear` do not delete them. Avoid keys and prefixes that produce a leading dot. + ### $memcached This is an array of servers that will be used when using the **Memcached** handler.