From ca12cf0985d56ea55d6a35ca6189f9e27686f048 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sun, 1 Nov 2026 23:36:11 +0100 Subject: [PATCH 1/6] perf: pipeline HMSET and EXPIREAT in Redis and Predis cache handlers Send HMSET and EXPIREAT together in a single pipeline round trip rather than issuing two sequential network requests on every cache save. For normal cache usage, behavior and data structures remain identical. In error scenarios where HMSET fails (e.g. key contains a non-hash type), the pipelined EXPIREAT will still execute on the existing key, while save() returns false as expected. --- system/Cache/Handlers/PredisHandler.php | 15 ++++++++++----- system/Cache/Handlers/RedisHandler.php | 19 ++++++++++++++----- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/system/Cache/Handlers/PredisHandler.php b/system/Cache/Handlers/PredisHandler.php index 79e7ae98f916..bc7a092441af 100644 --- a/system/Cache/Handlers/PredisHandler.php +++ b/system/Cache/Handlers/PredisHandler.php @@ -118,15 +118,20 @@ public function save(string $key, mixed $value, int $ttl = 60): bool return false; } - if (! $this->redis->hmset($key, ['__ci_type' => $dataType, '__ci_value' => $value]) instanceof Status) { - return false; - } + $fields = ['__ci_type' => $dataType, '__ci_value' => $value]; if ($ttl !== 0) { - $this->redis->expireat($key, Time::now()->getTimestamp() + $ttl); + // Send HMSET and EXPIREAT in a single round trip. + $expiresAt = Time::now()->getTimestamp() + $ttl; + $results = $this->redis->pipeline(static function ($pipe) use ($key, $fields, $expiresAt): void { + $pipe->hmset($key, $fields); + $pipe->expireat($key, $expiresAt); + }); + + return is_array($results) && ($results[0] ?? null) instanceof Status; } - return true; + return $this->redis->hmset($key, $fields) instanceof Status; } public function delete(string $key): bool diff --git a/system/Cache/Handlers/RedisHandler.php b/system/Cache/Handlers/RedisHandler.php index ccbb29bcd032..3e62f2b1ab83 100644 --- a/system/Cache/Handlers/RedisHandler.php +++ b/system/Cache/Handlers/RedisHandler.php @@ -134,15 +134,24 @@ public function save(string $key, mixed $value, int $ttl = 60): bool return false; } - if (! $this->redis->hMset($key, ['__ci_type' => $dataType, '__ci_value' => $value])) { - return false; - } + $fields = ['__ci_type' => $dataType, '__ci_value' => $value]; if ($ttl !== 0) { - $this->redis->expireAt($key, Time::now()->getTimestamp() + $ttl); + // Send HMSET and EXPIREAT in a single round trip. + $pipeline = $this->redis->multi(Redis::PIPELINE); + + if ($pipeline === false) { + return false; + } + + $pipeline->hMset($key, $fields); + $pipeline->expireAt($key, Time::now()->getTimestamp() + $ttl); + $results = $pipeline->exec(); + + return is_array($results) && (bool) ($results[0] ?? false); } - return true; + return (bool) $this->redis->hMset($key, $fields); } public function delete(string $key): bool From 061a1f3b32e98f0d6715e673e3a3c1f40b7b4ab3 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Thu, 5 Nov 2026 20:52:31 +0100 Subject: [PATCH 2/6] fix: make expiration conditional on successful save in Redis and Predis handlers Execute HMSET and EXPIREAT atomically via a Lua script so that EXPIREAT is never executed when HMSET fails (e.g. WRONGTYPE error on non-hash keys). Falls back to sequential execution if EVAL is unsupported or blocked. Adds regression tests verifying non-hash keys preserve value and TTL. --- system/Cache/Handlers/PredisHandler.php | 39 ++++++++++++--- system/Cache/Handlers/RedisHandler.php | 38 ++++++++++---- .../Cache/Handlers/PredisHandlerTest.php | 50 +++++++++++++++++++ .../Cache/Handlers/RedisHandlerTest.php | 48 ++++++++++++++++++ 4 files changed, 159 insertions(+), 16 deletions(-) diff --git a/system/Cache/Handlers/PredisHandler.php b/system/Cache/Handlers/PredisHandler.php index bc7a092441af..2eae6dda20a6 100644 --- a/system/Cache/Handlers/PredisHandler.php +++ b/system/Cache/Handlers/PredisHandler.php @@ -20,12 +20,26 @@ use Predis\Client; use Predis\Collection\Iterator\Keyspace; use Predis\Response\Status; +use Throwable; /** * Predis cache handler */ class PredisHandler extends BaseHandler { + /** + * Lua script to conditionally execute HMSET and EXPIREAT in a single round trip. + * Prevents EXPIREAT from mutating TTL or expiring keys when HMSET fails (e.g. WRONGTYPE). + */ + private const SAVE_SCRIPT = <<<'LUA' + local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3]) + if type(res) == 'table' and res.err then + return 0 + end + redis.call('EXPIREAT', KEYS[1], ARGV[1]) + return 1 + LUA; + /** * Default config * @@ -121,14 +135,27 @@ public function save(string $key, mixed $value, int $ttl = 60): bool $fields = ['__ci_type' => $dataType, '__ci_value' => $value]; if ($ttl !== 0) { - // Send HMSET and EXPIREAT in a single round trip. $expiresAt = Time::now()->getTimestamp() + $ttl; - $results = $this->redis->pipeline(static function ($pipe) use ($key, $fields, $expiresAt): void { - $pipe->hmset($key, $fields); - $pipe->expireat($key, $expiresAt); - }); - return is_array($results) && ($results[0] ?? null) instanceof Status; + try { + return (bool) $this->redis->eval( + self::SAVE_SCRIPT, + 1, + $key, + (string) $expiresAt, + $dataType, + (string) $value, + ); + } catch (Throwable) { + // If EVAL is unsupported or blocked, fallback to sequential execution. + if (! $this->redis->hmset($key, $fields) instanceof Status) { + return false; + } + + $this->redis->expireat($key, $expiresAt); + + return true; + } } return $this->redis->hmset($key, $fields) instanceof Status; diff --git a/system/Cache/Handlers/RedisHandler.php b/system/Cache/Handlers/RedisHandler.php index 3e62f2b1ab83..e008a35c59c4 100644 --- a/system/Cache/Handlers/RedisHandler.php +++ b/system/Cache/Handlers/RedisHandler.php @@ -18,12 +18,26 @@ use Config\Cache; use Redis; use RedisException; +use Throwable; /** * Redis cache handler */ class RedisHandler extends BaseHandler { + /** + * Lua script to conditionally execute HMSET and EXPIREAT in a single round trip. + * Prevents EXPIREAT from mutating TTL or expiring keys when HMSET fails (e.g. WRONGTYPE). + */ + private const SAVE_SCRIPT = <<<'LUA' + local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3]) + if type(res) == 'table' and res.err then + return 0 + end + redis.call('EXPIREAT', KEYS[1], ARGV[1]) + return 1 + LUA; + /** * Default config * @@ -137,18 +151,22 @@ public function save(string $key, mixed $value, int $ttl = 60): bool $fields = ['__ci_type' => $dataType, '__ci_value' => $value]; if ($ttl !== 0) { - // Send HMSET and EXPIREAT in a single round trip. - $pipeline = $this->redis->multi(Redis::PIPELINE); + $expiresAt = Time::now()->getTimestamp() + $ttl; - if ($pipeline === false) { - return false; + try { + return (bool) $this->redis->eval( + self::SAVE_SCRIPT, + [$key, $expiresAt, $dataType, (string) $value], + 1, + ); + } catch (Throwable) { + // If EVAL is unsupported or blocked, fallback to sequential execution. + if (! $this->redis->hMset($key, $fields)) { + return false; + } + + return $this->redis->expireAt($key, $expiresAt); } - - $pipeline->hMset($key, $fields); - $pipeline->expireAt($key, Time::now()->getTimestamp() + $ttl); - $results = $pipeline->exec(); - - return is_array($results) && (bool) ($results[0] ?? false); } return (bool) $this->redis->hMset($key, $fields); diff --git a/tests/system/Cache/Handlers/PredisHandlerTest.php b/tests/system/Cache/Handlers/PredisHandlerTest.php index 91949f53238f..501839477a3e 100644 --- a/tests/system/Cache/Handlers/PredisHandlerTest.php +++ b/tests/system/Cache/Handlers/PredisHandlerTest.php @@ -18,6 +18,8 @@ use CodeIgniter\I18n\Time; use Config\Cache; use PHPUnit\Framework\Attributes\Group; +use Predis\Client; +use RuntimeException; /** * @internal @@ -196,4 +198,52 @@ public function testReconnect(): void $this->assertSame('value', $this->handler->get(self::$key1)); } + + public function testSaveFailsOnNonHashKeyPreservingValueAndTtl(): void + { + /** @var Client $redis */ + $redis = $this->getPrivateProperty($this->handler, 'redis'); + + $prefixedKey = $this->config->prefix . 'non_hash_key'; + $redis->set($prefixedKey, 'raw_string_value'); + $redis->expire($prefixedKey, 300); + + $this->assertFalse($this->handler->save('non_hash_key', 'new_value', 60)); + + $this->assertSame('raw_string_value', $redis->get($prefixedKey)); + $this->assertGreaterThan(250, $redis->ttl($prefixedKey)); + + // Handler remains usable for subsequent operations + $this->assertTrue($this->handler->save(self::$key1, 'usable_value')); + $this->assertSame('usable_value', $this->handler->get(self::$key1)); + + $redis->del([$prefixedKey]); + } + + public function testSaveFallbackWhenEvalThrowsException(): void + { + /** @var Client $originalClient */ + $originalClient = $this->getPrivateProperty($this->handler, 'redis'); + + $failingClient = new class ($originalClient->getConnection()->getParameters()) extends Client { + /** + * @param string $script + * @param int $numkeys + * @param mixed ...$arguments + */ + public function eval($script, $numkeys, ...$arguments): never + { + throw new RuntimeException('ERR unknown command EVAL'); + } + }; + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingClient); + + $this->assertTrue($this->handler->save(self::$key1, 'fallback_value', 120)); + $this->assertSame('fallback_value', $this->handler->get(self::$key1)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalClient); + } + } } diff --git a/tests/system/Cache/Handlers/RedisHandlerTest.php b/tests/system/Cache/Handlers/RedisHandlerTest.php index 1f85ecc28349..d52c7de1bd02 100644 --- a/tests/system/Cache/Handlers/RedisHandlerTest.php +++ b/tests/system/Cache/Handlers/RedisHandlerTest.php @@ -19,6 +19,8 @@ use Config\Cache; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; +use Redis; +use RedisException; /** * @internal @@ -238,4 +240,50 @@ public function testReconnect(): void $this->assertSame('value', $this->handler->get(self::$key1)); } + + public function testSaveFailsOnNonHashKeyPreservingValueAndTtl(): void + { + /** @var Redis $redis */ + $redis = $this->getPrivateProperty($this->handler, 'redis'); + + $prefixedKey = $this->config->prefix . 'non_hash_key'; + $redis->set($prefixedKey, 'raw_string_value'); + $redis->expire($prefixedKey, 300); + + $this->assertFalse($this->handler->save('non_hash_key', 'new_value', 60)); + + $this->assertSame('raw_string_value', $redis->get($prefixedKey)); + $this->assertGreaterThan(250, $redis->ttl($prefixedKey)); + + // Handler remains usable for subsequent operations + $this->assertTrue($this->handler->save(self::$key1, 'usable_value')); + $this->assertSame('usable_value', $this->handler->get(self::$key1)); + + $redis->del($prefixedKey); + } + + public function testSaveFallbackWhenEvalThrowsException(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('eval') + ->willThrowException(new RedisException('ERR unknown command EVAL')); + $failingRedis->expects($this->once()) + ->method('hMset') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('expireAt') + ->willReturn(true); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->assertTrue($this->handler->save(self::$key1, 'fallback_value', 120)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } } From c92b6e0dc6fc9be09844895af3bec156e93af8c4 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sun, 15 Nov 2026 00:12:58 +0100 Subject: [PATCH 3/6] fix(Cache): handle unavailable EVAL and preserve Predis exception behavior RedisHandler: treat `false` from phpredis EVAL (e.g. EVAL disabled via `rename-command`) as unavailable and fall back to sequential hMset and expireAt. Integer 0 still means HMSET failed inside the script and must not trigger the fallback. PredisHandler: call HMSET and EXPIREAT with redis.call so a WRONGTYPE error aborts the script before EXPIREAT and is propagated to the client as ServerException again. Add regression tests for both behaviors. --- system/Cache/Handlers/PredisHandler.php | 10 ++-- system/Cache/Handlers/RedisHandler.php | 18 +++++-- .../Cache/Handlers/PredisHandlerTest.php | 10 +++- .../Cache/Handlers/RedisHandlerTest.php | 48 +++++++++++++++++++ 4 files changed, 73 insertions(+), 13 deletions(-) diff --git a/system/Cache/Handlers/PredisHandler.php b/system/Cache/Handlers/PredisHandler.php index 2eae6dda20a6..6f4873f2a540 100644 --- a/system/Cache/Handlers/PredisHandler.php +++ b/system/Cache/Handlers/PredisHandler.php @@ -28,14 +28,12 @@ class PredisHandler extends BaseHandler { /** - * Lua script to conditionally execute HMSET and EXPIREAT in a single round trip. - * Prevents EXPIREAT from mutating TTL or expiring keys when HMSET fails (e.g. WRONGTYPE). + * Lua script to execute HMSET and EXPIREAT in a single round trip. + * An HMSET error (e.g. WRONGTYPE) aborts the script before EXPIREAT runs and + * is propagated to the client as an exception reply. */ private const SAVE_SCRIPT = <<<'LUA' - local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3]) - if type(res) == 'table' and res.err then - return 0 - end + redis.call('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3]) redis.call('EXPIREAT', KEYS[1], ARGV[1]) return 1 LUA; diff --git a/system/Cache/Handlers/RedisHandler.php b/system/Cache/Handlers/RedisHandler.php index e008a35c59c4..eddc340864fe 100644 --- a/system/Cache/Handlers/RedisHandler.php +++ b/system/Cache/Handlers/RedisHandler.php @@ -154,19 +154,27 @@ public function save(string $key, mixed $value, int $ttl = 60): bool $expiresAt = Time::now()->getTimestamp() + $ttl; try { - return (bool) $this->redis->eval( + $result = $this->redis->eval( self::SAVE_SCRIPT, [$key, $expiresAt, $dataType, (string) $value], 1, ); + + // phpredis returns false when EVAL is unavailable (e.g. disabled via + // rename-command). Integer 0 means HMSET failed inside the script and + // must not trigger the fallback. + if ($result !== false) { + return (bool) $result; + } } catch (Throwable) { // If EVAL is unsupported or blocked, fallback to sequential execution. - if (! $this->redis->hMset($key, $fields)) { - return false; - } + } - return $this->redis->expireAt($key, $expiresAt); + if (! $this->redis->hMset($key, $fields)) { + return false; } + + return $this->redis->expireAt($key, $expiresAt); } return (bool) $this->redis->hMset($key, $fields); diff --git a/tests/system/Cache/Handlers/PredisHandlerTest.php b/tests/system/Cache/Handlers/PredisHandlerTest.php index 501839477a3e..b1ae6b7d2c88 100644 --- a/tests/system/Cache/Handlers/PredisHandlerTest.php +++ b/tests/system/Cache/Handlers/PredisHandlerTest.php @@ -19,6 +19,7 @@ use Config\Cache; use PHPUnit\Framework\Attributes\Group; use Predis\Client; +use Predis\Response\ServerException; use RuntimeException; /** @@ -199,7 +200,7 @@ public function testReconnect(): void $this->assertSame('value', $this->handler->get(self::$key1)); } - public function testSaveFailsOnNonHashKeyPreservingValueAndTtl(): void + public function testSaveThrowsServerExceptionOnNonHashKeyPreservingValueAndTtl(): void { /** @var Client $redis */ $redis = $this->getPrivateProperty($this->handler, 'redis'); @@ -208,7 +209,12 @@ public function testSaveFailsOnNonHashKeyPreservingValueAndTtl(): void $redis->set($prefixedKey, 'raw_string_value'); $redis->expire($prefixedKey, 300); - $this->assertFalse($this->handler->save('non_hash_key', 'new_value', 60)); + try { + $this->handler->save('non_hash_key', 'new_value', 60); + $this->fail('Predis\Response\ServerException was not thrown for a non-hash key.'); + } catch (ServerException $e) { + $this->assertSame('WRONGTYPE', $e->getErrorType()); + } $this->assertSame('raw_string_value', $redis->get($prefixedKey)); $this->assertGreaterThan(250, $redis->ttl($prefixedKey)); diff --git a/tests/system/Cache/Handlers/RedisHandlerTest.php b/tests/system/Cache/Handlers/RedisHandlerTest.php index d52c7de1bd02..d1d35dd3074b 100644 --- a/tests/system/Cache/Handlers/RedisHandlerTest.php +++ b/tests/system/Cache/Handlers/RedisHandlerTest.php @@ -286,4 +286,52 @@ public function testSaveFallbackWhenEvalThrowsException(): void $this->setPrivateProperty($this->handler, 'redis', $originalRedis); } } + + public function testSaveFallbackWhenEvalReturnsFalse(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('eval') + ->willReturn(false); + $failingRedis->expects($this->once()) + ->method('hMset') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('expireAt') + ->willReturn(true); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->assertTrue($this->handler->save(self::$key1, 'fallback_value', 120)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } + + public function testSaveDoesNotFallbackWhenScriptReportsHmsetFailure(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('eval') + ->willReturn(0); + $failingRedis->expects($this->never()) + ->method('hMset'); + $failingRedis->expects($this->never()) + ->method('expireAt'); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->assertFalse($this->handler->save(self::$key1, 'new_value', 60)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } } From 81bef53e73b07781f3495042d4548b77b7fe7d37 Mon Sep 17 00:00:00 2001 From: Bogdan Date: Sun, 15 Nov 2026 15:11:17 +0100 Subject: [PATCH 4/6] fix(Cache): preserve client error behaviour in atomic Redis save Return the pcall error reply from the Lua script instead of 0, so HMSET errors keep their original message and type, and detect an unavailable or denied EVAL via clearLastError()/getLastError() instead of treating every failure as a reason to retry the write. PredisHandler now falls back to sequential writes only when the server reports an unavailable or denied EVAL, and rethrows every other server error without issuing a second HMSET/EXPIREAT. Restore the pre-PR return semantics of the sequential fallback, cover WRONGTYPE, NOPERM (hmset and eval), a stale last error and a prefixed key with regression tests, and document the partial-write behaviour when EXPIREAT is rejected. --- system/Cache/Handlers/PredisHandler.php | 77 ++++--- system/Cache/Handlers/RedisHandler.php | 86 +++++--- .../Cache/Handlers/PredisHandlerTest.php | 196 ++++++++++++++++-- .../Cache/Handlers/RedisHandlerTest.php | 195 ++++++++++++++++- 4 files changed, 482 insertions(+), 72 deletions(-) diff --git a/system/Cache/Handlers/PredisHandler.php b/system/Cache/Handlers/PredisHandler.php index 6f4873f2a540..a2bc32e8498c 100644 --- a/system/Cache/Handlers/PredisHandler.php +++ b/system/Cache/Handlers/PredisHandler.php @@ -19,8 +19,8 @@ use Exception; use Predis\Client; use Predis\Collection\Iterator\Keyspace; +use Predis\Response\ServerException; use Predis\Response\Status; -use Throwable; /** * Predis cache handler @@ -29,11 +29,20 @@ class PredisHandler extends BaseHandler { /** * Lua script to execute HMSET and EXPIREAT in a single round trip. - * An HMSET error (e.g. WRONGTYPE) aborts the script before EXPIREAT runs and - * is propagated to the client as an exception reply. + * + * The pcall error reply is returned to the client, so an HMSET error (e.g. + * WRONGTYPE) never runs EXPIREAT, keeps its original error type, and is not + * retried by the sequential fallback in save(). + * + * If HMSET succeeds and EXPIREAT is rejected, the hash is stored without a + * TTL, exactly as with the previous sequential implementation (Redis does + * not roll back script effects). */ private const SAVE_SCRIPT = <<<'LUA' - redis.call('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3]) + local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3]) + if type(res) == 'table' and res.err then + return res + end redis.call('EXPIREAT', KEYS[1], ARGV[1]) return 1 LUA; @@ -132,31 +141,47 @@ public function save(string $key, mixed $value, int $ttl = 60): bool $fields = ['__ci_type' => $dataType, '__ci_value' => $value]; - if ($ttl !== 0) { - $expiresAt = Time::now()->getTimestamp() + $ttl; - - try { - return (bool) $this->redis->eval( - self::SAVE_SCRIPT, - 1, - $key, - (string) $expiresAt, - $dataType, - (string) $value, - ); - } catch (Throwable) { - // If EVAL is unsupported or blocked, fallback to sequential execution. - if (! $this->redis->hmset($key, $fields) instanceof Status) { - return false; - } - - $this->redis->expireat($key, $expiresAt); - - return true; + if ($ttl === 0) { + return $this->redis->hmset($key, $fields) instanceof Status; + } + + $expiresAt = Time::now()->getTimestamp() + $ttl; + + try { + return (bool) $this->redis->eval( + self::SAVE_SCRIPT, + 1, + $key, + (string) $expiresAt, + $dataType, + (string) $value, + ); + } catch (ServerException $e) { + if (! self::isEvalUnavailable($e->getMessage())) { + throw $e; } } - return $this->redis->hmset($key, $fields) instanceof Status; + // EVAL is unavailable (renamed command or ACL denial): run both commands sequentially. + if (! $this->redis->hmset($key, $fields) instanceof Status) { + return false; + } + + $this->redis->expireat($key, $expiresAt); + + return true; + } + + /** + * Checks whether the exception only means that the EVAL command itself is not + * available to this client, either because it was renamed or because ACL denies it. + * + * Keep the patterns in sync with RedisHandler::isEvalUnavailable(). + */ + private static function isEvalUnavailable(string $message): bool + { + return preg_match("/unknown command [`']?eval\\b/i", $message) === 1 + || preg_match("/no permissions to run the [`']eval[`'] command/i", $message) === 1; } public function delete(string $key): bool diff --git a/system/Cache/Handlers/RedisHandler.php b/system/Cache/Handlers/RedisHandler.php index eddc340864fe..3703d7f62b12 100644 --- a/system/Cache/Handlers/RedisHandler.php +++ b/system/Cache/Handlers/RedisHandler.php @@ -18,7 +18,6 @@ use Config\Cache; use Redis; use RedisException; -use Throwable; /** * Redis cache handler @@ -26,13 +25,21 @@ class RedisHandler extends BaseHandler { /** - * Lua script to conditionally execute HMSET and EXPIREAT in a single round trip. - * Prevents EXPIREAT from mutating TTL or expiring keys when HMSET fails (e.g. WRONGTYPE). + * Lua script to execute HMSET and EXPIREAT in a single round trip. + * + * The pcall error reply is returned to the client, so a failing HMSET never + * runs EXPIREAT and the original error message and type are preserved: + * clients that throw on error replies raise RedisException, phpredis exposes + * the message through Redis::getLastError(). + * + * If HMSET succeeds and EXPIREAT is rejected, the hash is stored without a + * TTL, exactly as with the previous sequential implementation (Redis does + * not roll back script effects). */ private const SAVE_SCRIPT = <<<'LUA' local res = redis.pcall('HMSET', KEYS[1], '__ci_type', ARGV[2], '__ci_value', ARGV[3]) if type(res) == 'table' and res.err then - return 0 + return res end redis.call('EXPIREAT', KEYS[1], ARGV[1]) return 1 @@ -150,34 +157,63 @@ public function save(string $key, mixed $value, int $ttl = 60): bool $fields = ['__ci_type' => $dataType, '__ci_value' => $value]; - if ($ttl !== 0) { - $expiresAt = Time::now()->getTimestamp() + $ttl; + if ($ttl === 0) { + return (bool) $this->redis->hMset($key, $fields); + } + + $expiresAt = Time::now()->getTimestamp() + $ttl; - try { - $result = $this->redis->eval( - self::SAVE_SCRIPT, - [$key, $expiresAt, $dataType, (string) $value], - 1, - ); - - // phpredis returns false when EVAL is unavailable (e.g. disabled via - // rename-command). Integer 0 means HMSET failed inside the script and - // must not trigger the fallback. - if ($result !== false) { - return (bool) $result; - } - } catch (Throwable) { - // If EVAL is unsupported or blocked, fallback to sequential execution. + $shouldFallback = false; + + $this->redis->clearLastError(); + + try { + $result = $this->redis->eval( + self::SAVE_SCRIPT, + [$key, (string) $expiresAt, $dataType, (string) $value], + 1, + ); + + if ($result !== false) { + return (bool) $result; } - if (! $this->redis->hMset($key, $fields)) { - return false; + // phpredis reports server errors as false and keeps the message in getLastError(). + $error = $this->redis->getLastError(); + + $shouldFallback = is_string($error) && self::isEvalUnavailable($error); + } catch (RedisException $e) { + if (! self::isEvalUnavailable($e->getMessage())) { + throw $e; } - return $this->redis->expireAt($key, $expiresAt); + $shouldFallback = true; + } + + if (! $shouldFallback) { + return false; + } + + // EVAL is unavailable (renamed command or ACL denial): run both commands sequentially. + if (! $this->redis->hMset($key, $fields)) { + return false; } - return (bool) $this->redis->hMset($key, $fields); + $this->redis->expireAt($key, $expiresAt); + + return true; + } + + /** + * Checks whether the message only means that the EVAL command itself is not + * available to this client, either because it was renamed or because ACL denies it. + * + * Keep the patterns in sync with PredisHandler::isEvalUnavailable(). + */ + private static function isEvalUnavailable(string $message): bool + { + return preg_match("/unknown command [`']?eval\\b/i", $message) === 1 + || preg_match("/no permissions to run the [`']eval[`'] command/i", $message) === 1; } public function delete(string $key): bool diff --git a/tests/system/Cache/Handlers/PredisHandlerTest.php b/tests/system/Cache/Handlers/PredisHandlerTest.php index b1ae6b7d2c88..855ea9e5ad68 100644 --- a/tests/system/Cache/Handlers/PredisHandlerTest.php +++ b/tests/system/Cache/Handlers/PredisHandlerTest.php @@ -20,7 +20,7 @@ use PHPUnit\Framework\Attributes\Group; use Predis\Client; use Predis\Response\ServerException; -use RuntimeException; +use Throwable; /** * @internal @@ -205,25 +205,54 @@ public function testSaveThrowsServerExceptionOnNonHashKeyPreservingValueAndTtl() /** @var Client $redis */ $redis = $this->getPrivateProperty($this->handler, 'redis'); + $originalClient = $redis; + $prefix = $this->config->prefix; + + $spy = new class ($originalClient->getConnection()->getParameters(), ['prefix' => $prefix]) extends Client { + /** + * @var list + */ + public array $commands = []; + + /** + * @param string $commandID + * @param array $arguments + */ + public function __call($commandID, $arguments) + { + $this->commands[] = strtolower($commandID); + + return parent::__call($commandID, $arguments); + } + }; + $prefixedKey = $this->config->prefix . 'non_hash_key'; $redis->set($prefixedKey, 'raw_string_value'); $redis->expire($prefixedKey, 300); try { - $this->handler->save('non_hash_key', 'new_value', 60); - $this->fail('Predis\Response\ServerException was not thrown for a non-hash key.'); - } catch (ServerException $e) { - $this->assertSame('WRONGTYPE', $e->getErrorType()); - } + $this->setPrivateProperty($this->handler, 'redis', $spy); - $this->assertSame('raw_string_value', $redis->get($prefixedKey)); - $this->assertGreaterThan(250, $redis->ttl($prefixedKey)); + try { + $this->handler->save('non_hash_key', 'new_value', 60); + $this->fail('Predis\Response\ServerException was not thrown for a non-hash key.'); + } catch (ServerException $e) { + $this->assertSame('WRONGTYPE', $e->getErrorType()); + } + + // The Lua script must be the only command attempted. + $this->assertSame(['eval'], $spy->commands); - // Handler remains usable for subsequent operations - $this->assertTrue($this->handler->save(self::$key1, 'usable_value')); - $this->assertSame('usable_value', $this->handler->get(self::$key1)); + $this->assertSame('raw_string_value', $redis->get($prefixedKey)); + $this->assertGreaterThan(250, $redis->ttl($prefixedKey)); - $redis->del([$prefixedKey]); + // Handler remains usable for subsequent operations + $this->assertTrue($this->handler->save(self::$key1, 'usable_value')); + $this->assertSame('usable_value', $this->handler->get(self::$key1)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalClient); + $redis->del([$prefixedKey]); + } } public function testSaveFallbackWhenEvalThrowsException(): void @@ -231,25 +260,156 @@ public function testSaveFallbackWhenEvalThrowsException(): void /** @var Client $originalClient */ $originalClient = $this->getPrivateProperty($this->handler, 'redis'); - $failingClient = new class ($originalClient->getConnection()->getParameters()) extends Client { + $prefix = $this->config->prefix; + + $failingClient = new class ($originalClient->getConnection()->getParameters(), ['prefix' => $prefix]) extends Client { /** - * @param string $script - * @param int $numkeys - * @param mixed ...$arguments + * @var list */ - public function eval($script, $numkeys, ...$arguments): never + public array $commands = []; + + public ?Throwable $evalException = null; + + /** + * @param string $commandID + * @param array $arguments + */ + public function __call($commandID, $arguments) { - throw new RuntimeException('ERR unknown command EVAL'); + $this->commands[] = strtolower($commandID); + + if (strtolower($commandID) === 'eval' && $this->evalException instanceof Throwable) { + throw $this->evalException; + } + + return parent::__call($commandID, $arguments); } }; + $failingClient->evalException = new ServerException("ERR unknown command 'EVAL', with args beginning with: 'local res = redis.pcall(...)"); + try { $this->setPrivateProperty($this->handler, 'redis', $failingClient); $this->assertTrue($this->handler->save(self::$key1, 'fallback_value', 120)); + $this->assertSame(['eval', 'hmset', 'expireat'], $failingClient->commands); + $this->assertSame('fallback_value', $this->handler->get(self::$key1)); } finally { $this->setPrivateProperty($this->handler, 'redis', $originalClient); } } + + public function testSaveFallsBackWhenEvalIsDeniedByAcl(): void + { + /** @var Client $originalClient */ + $originalClient = $this->getPrivateProperty($this->handler, 'redis'); + + $prefix = $this->config->prefix; + + $failingClient = new class ($originalClient->getConnection()->getParameters(), ['prefix' => $prefix]) extends Client { + /** + * @var list + */ + public array $commands = []; + + public ?Throwable $evalException = null; + + /** + * @param string $commandID + * @param array $arguments + */ + public function __call($commandID, $arguments) + { + $this->commands[] = strtolower($commandID); + + if (strtolower($commandID) === 'eval' && $this->evalException instanceof Throwable) { + throw $this->evalException; + } + + return parent::__call($commandID, $arguments); + } + }; + + $failingClient->evalException = new ServerException("NOPERM this user has no permissions to run the 'eval' command"); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingClient); + + $this->assertTrue($this->handler->save(self::$key1, 'acl_fallback_value', 120)); + $this->assertSame(['eval', 'hmset', 'expireat'], $failingClient->commands); + + $this->assertSame('acl_fallback_value', $this->handler->get(self::$key1)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalClient); + } + } + + public function testSaveRethrowsWhenHmsetIsDeniedInsideScript(): void + { + /** @var Client $originalClient */ + $originalClient = $this->getPrivateProperty($this->handler, 'redis'); + + $prefix = $this->config->prefix; + + $failingClient = new class ($originalClient->getConnection()->getParameters(), ['prefix' => $prefix]) extends Client { + /** + * @var list + */ + public array $commands = []; + + public ?Throwable $evalException = null; + + /** + * @param string $commandID + * @param array $arguments + */ + public function __call($commandID, $arguments) + { + $this->commands[] = strtolower($commandID); + + if (strtolower($commandID) === 'eval' && $this->evalException instanceof Throwable) { + throw $this->evalException; + } + + return parent::__call($commandID, $arguments); + } + }; + + $failingClient->evalException = new ServerException("NOPERM this user has no permissions to run the 'hmset' command"); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingClient); + + try { + $this->handler->save(self::$key1, 'denied_value', 120); + $this->fail('Predis\Response\ServerException was not thrown when HMSET is denied inside the script.'); + } catch (ServerException $e) { + $this->assertStringContainsString('NOPERM', $e->getMessage()); + } + + // Only the script ran: no sequential fallback was attempted. + $this->assertSame(['eval'], $failingClient->commands); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalClient); + } + } + + public function testSaveUsesConfiguredPrefixInScript(): void + { + $config = new Cache(); + $config->prefix = 'ci4_'; + $handler = CacheFactory::getHandler($config, 'predis'); + + try { + $this->assertTrue($handler->save('prefixed_key', 'prefixed_value', 120)); + $this->assertSame('prefixed_value', $handler->get('prefixed_key')); + + $metadata = $handler->getMetaData('prefixed_key'); + $this->assertNotNull($metadata); + $this->assertNotNull($metadata['expire']); + } finally { + $handler->clean(); + } + } } diff --git a/tests/system/Cache/Handlers/RedisHandlerTest.php b/tests/system/Cache/Handlers/RedisHandlerTest.php index d1d35dd3074b..16f369aa7952 100644 --- a/tests/system/Cache/Handlers/RedisHandlerTest.php +++ b/tests/system/Cache/Handlers/RedisHandlerTest.php @@ -262,15 +262,48 @@ public function testSaveFailsOnNonHashKeyPreservingValueAndTtl(): void $redis->del($prefixedKey); } + public function testSaveIgnoresStaleLastErrorOnSuccessfulEval(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('eval') + ->willReturn(1); + // A message left behind by an earlier command on the same connection must not be read. + $failingRedis->expects($this->never()) + ->method('getLastError') + ->willReturn("ERR unknown command 'EVAL', with args beginning with: 'local res = redis.pcall(...)"); + $failingRedis->expects($this->never()) + ->method('hMset'); + $failingRedis->expects($this->never()) + ->method('expireAt'); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->assertTrue($this->handler->save(self::$key1, 'stale_error_value', 120)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } + public function testSaveFallbackWhenEvalThrowsException(): void { /** @var Redis $originalRedis */ $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); $failingRedis->expects($this->once()) ->method('eval') - ->willThrowException(new RedisException('ERR unknown command EVAL')); + ->willThrowException(new RedisException("ERR unknown command 'EVAL', with args beginning with: 'local res = redis.pcall(...)")); $failingRedis->expects($this->once()) ->method('hMset') ->willReturn(true); @@ -293,9 +326,15 @@ public function testSaveFallbackWhenEvalReturnsFalse(): void $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); $failingRedis->expects($this->once()) ->method('eval') ->willReturn(false); + $failingRedis->expects($this->once()) + ->method('getLastError') + ->willReturn("ERR unknown command 'EVAL', with args beginning with: 'local res = redis.pcall(...)"); $failingRedis->expects($this->once()) ->method('hMset') ->willReturn(true); @@ -312,15 +351,21 @@ public function testSaveFallbackWhenEvalReturnsFalse(): void } } - public function testSaveDoesNotFallbackWhenScriptReportsHmsetFailure(): void + public function testSaveReturnsFalseWithoutFallbackWhenScriptReportsHmsetError(): void { /** @var Redis $originalRedis */ $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); $failingRedis->expects($this->once()) ->method('eval') - ->willReturn(0); + ->willReturn(false); + $failingRedis->expects($this->once()) + ->method('getLastError') + ->willReturn('WRONGTYPE Operation against a key holding the wrong kind of value'); $failingRedis->expects($this->never()) ->method('hMset'); $failingRedis->expects($this->never()) @@ -334,4 +379,148 @@ public function testSaveDoesNotFallbackWhenScriptReportsHmsetFailure(): void $this->setPrivateProperty($this->handler, 'redis', $originalRedis); } } + + public function testSaveReturnsFalseWithoutFallbackWhenEvalFailsWithoutError(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('eval') + ->willReturn(false); + $failingRedis->expects($this->once()) + ->method('getLastError') + ->willReturn(null); + $failingRedis->expects($this->never()) + ->method('hMset'); + $failingRedis->expects($this->never()) + ->method('expireAt'); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->assertFalse($this->handler->save(self::$key1, 'new_value', 60)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } + + public function testSaveReturnsFalseWithoutFallbackWhenHmsetIsDeniedInsideScript(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('eval') + ->willReturn(false); + $failingRedis->expects($this->once()) + ->method('getLastError') + ->willReturn("NOPERM this user has no permissions to run the 'hmset' command"); + $failingRedis->expects($this->never()) + ->method('hMset'); + $failingRedis->expects($this->never()) + ->method('expireAt'); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->assertFalse($this->handler->save(self::$key1, 'new_value', 60)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } + + public function testSaveRethrowsRedisExceptionFromEval(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('eval') + ->willThrowException(new RedisException('WRONGTYPE Operation against a key holding the wrong kind of value')); + $failingRedis->expects($this->never()) + ->method('hMset'); + $failingRedis->expects($this->never()) + ->method('expireAt'); + + $this->expectException(RedisException::class); + $this->expectExceptionMessage('WRONGTYPE'); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->handler->save(self::$key1, 'new_value', 60); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } + + public function testSaveRethrowsWhenHmsetIsDeniedInsideScript(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('eval') + ->willThrowException(new RedisException("NOPERM this user has no permissions to run the 'hmset' command")); + $failingRedis->expects($this->never()) + ->method('hMset'); + $failingRedis->expects($this->never()) + ->method('expireAt'); + + $this->expectException(RedisException::class); + $this->expectExceptionMessage('NOPERM'); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->handler->save(self::$key1, 'new_value', 60); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } + + public function testSaveFallsBackWhenEvalIsDeniedByAcl(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('eval') + ->willThrowException(new RedisException("NOPERM this user has no permissions to run the 'eval' command")); + $failingRedis->expects($this->once()) + ->method('hMset') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('expireAt') + ->willReturn(true); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->assertTrue($this->handler->save(self::$key1, 'fallback_value', 120)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } } From 1eef8667aacb63a6c2cabcf56ab7994ec6a43c6d Mon Sep 17 00:00:00 2001 From: Bogdan Date: Tue, 17 Nov 2026 22:23:31 +0100 Subject: [PATCH 5/6] fix(Cache): throw on ACL errors inside the atomic save script ACL (NOPERM) failures of HMSET and EXPIREAT raised inside the Lua script now surface as client-native exceptions (RedisException for phpredis, ServerException for Predis), matching the pre-PR sequential behavior, while WRONGTYPE and other errors keep the false + getLastError() path. EXPIREAT is wrapped in redis.pcall and returns the error reply in both handlers. Adds regression tests for ACL errors, branch ordering, real in-script message shapes and pcall coverage. --- system/Cache/Handlers/PredisHandler.php | 13 +- system/Cache/Handlers/RedisHandler.php | 42 ++++++- .../Cache/Handlers/PredisHandlerTest.php | 64 +++++++++- .../Cache/Handlers/RedisHandlerTest.php | 113 +++++++++++++++++- 4 files changed, 219 insertions(+), 13 deletions(-) diff --git a/system/Cache/Handlers/PredisHandler.php b/system/Cache/Handlers/PredisHandler.php index a2bc32e8498c..f7408c8dc284 100644 --- a/system/Cache/Handlers/PredisHandler.php +++ b/system/Cache/Handlers/PredisHandler.php @@ -30,9 +30,11 @@ class PredisHandler extends BaseHandler /** * Lua script to execute HMSET and EXPIREAT in a single round trip. * - * The pcall error reply is returned to the client, so an HMSET error (e.g. - * WRONGTYPE) never runs EXPIREAT, keeps its original error type, and is not - * retried by the sequential fallback in save(). + * Both commands run through pcall and their error reply is returned as-is, + * so an HMSET error (e.g. WRONGTYPE) stops the script before EXPIREAT and + * every error keeps its original type and message. Predis raises + * ServerException for such a reply, which save() only swallows when it is + * about EVAL itself, so an ACL denial is never retried sequentially. * * If HMSET succeeds and EXPIREAT is rejected, the hash is stored without a * TTL, exactly as with the previous sequential implementation (Redis does @@ -43,7 +45,10 @@ class PredisHandler extends BaseHandler if type(res) == 'table' and res.err then return res end - redis.call('EXPIREAT', KEYS[1], ARGV[1]) + local exp = redis.pcall('EXPIREAT', KEYS[1], ARGV[1]) + if type(exp) == 'table' and exp.err then + return exp + end return 1 LUA; diff --git a/system/Cache/Handlers/RedisHandler.php b/system/Cache/Handlers/RedisHandler.php index 3703d7f62b12..faf992d19abd 100644 --- a/system/Cache/Handlers/RedisHandler.php +++ b/system/Cache/Handlers/RedisHandler.php @@ -27,10 +27,12 @@ class RedisHandler extends BaseHandler /** * Lua script to execute HMSET and EXPIREAT in a single round trip. * - * The pcall error reply is returned to the client, so a failing HMSET never - * runs EXPIREAT and the original error message and type are preserved: - * clients that throw on error replies raise RedisException, phpredis exposes - * the message through Redis::getLastError(). + * Both commands run through pcall and their error reply is returned as-is, + * so a failing HMSET never runs EXPIREAT and the original error message and + * type are preserved. phpredis exposes the message through + * Redis::getLastError(); save() rethrows a permission error as + * RedisException, as the sequential implementation did, and keeps reporting + * any other error (e.g. WRONGTYPE) as false. * * If HMSET succeeds and EXPIREAT is rejected, the hash is stored without a * TTL, exactly as with the previous sequential implementation (Redis does @@ -41,7 +43,10 @@ class RedisHandler extends BaseHandler if type(res) == 'table' and res.err then return res end - redis.call('EXPIREAT', KEYS[1], ARGV[1]) + local exp = redis.pcall('EXPIREAT', KEYS[1], ARGV[1]) + if type(exp) == 'table' and exp.err then + return exp + end return 1 LUA; @@ -181,7 +186,15 @@ public function save(string $key, mixed $value, int $ttl = 60): bool // phpredis reports server errors as false and keeps the message in getLastError(). $error = $this->redis->getLastError(); - $shouldFallback = is_string($error) && self::isEvalUnavailable($error); + if (is_string($error)) { + if (self::isEvalUnavailable($error)) { + $shouldFallback = true; + } elseif (self::isDataCommandPermissionError($error)) { + // HMSET or EXPIREAT was denied by an ACL: the script itself ran, + // so keep throwing exactly like the sequential implementation did. + throw new RedisException($error); + } + } } catch (RedisException $e) { if (! self::isEvalUnavailable($e->getMessage())) { throw $e; @@ -216,6 +229,23 @@ private static function isEvalUnavailable(string $message): bool || preg_match("/no permissions to run the [`']eval[`'] command/i", $message) === 1; } + /** + * Checks whether the message means that a data command executed inside the + * save script was denied by an ACL. + * + * EVAL availability was already checked, so the denied command can only be + * HMSET or EXPIREAT. Redis reports it either as a command level denial or as + * an ACL failure while running the script. + * + * Predis throws for every error reply, so this mapping only exists for the + * phpredis false plus getLastError() path. + */ + private static function isDataCommandPermissionError(string $message): bool + { + return preg_match("/no permissions to run the [`']?[a-z]+[`'] command/i", $message) === 1 + || preg_match('/ACL failure in script/i', $message) === 1; + } + public function delete(string $key): bool { $key = static::validateKey($key, $this->prefix); diff --git a/tests/system/Cache/Handlers/PredisHandlerTest.php b/tests/system/Cache/Handlers/PredisHandlerTest.php index 855ea9e5ad68..a4974df37454 100644 --- a/tests/system/Cache/Handlers/PredisHandlerTest.php +++ b/tests/system/Cache/Handlers/PredisHandlerTest.php @@ -385,7 +385,57 @@ public function __call($commandID, $arguments) $this->handler->save(self::$key1, 'denied_value', 120); $this->fail('Predis\Response\ServerException was not thrown when HMSET is denied inside the script.'); } catch (ServerException $e) { - $this->assertStringContainsString('NOPERM', $e->getMessage()); + $this->assertStringContainsString("no permissions to run the 'hmset' command", $e->getMessage()); + } + + // Only the script ran: no sequential fallback was attempted. + $this->assertSame(['eval'], $failingClient->commands); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalClient); + } + } + + public function testSaveRethrowsWhenExpireatIsDeniedInsideScript(): void + { + /** @var Client $originalClient */ + $originalClient = $this->getPrivateProperty($this->handler, 'redis'); + + $prefix = $this->config->prefix; + + $failingClient = new class ($originalClient->getConnection()->getParameters(), ['prefix' => $prefix]) extends Client { + /** + * @var list + */ + public array $commands = []; + + public ?Throwable $evalException = null; + + /** + * @param string $commandID + * @param array $arguments + */ + public function __call($commandID, $arguments) + { + $this->commands[] = strtolower($commandID); + + if (strtolower($commandID) === 'eval' && $this->evalException instanceof Throwable) { + throw $this->evalException; + } + + return parent::__call($commandID, $arguments); + } + }; + + $failingClient->evalException = new ServerException("ERR ACL failure in script: User foo has no permissions to run the 'expireat' command"); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingClient); + + try { + $this->handler->save(self::$key1, 'denied_value', 120); + $this->fail('Predis\\Response\\ServerException was not thrown when EXPIREAT is denied inside the script.'); + } catch (ServerException $e) { + $this->assertStringContainsString("no permissions to run the 'expireat' command", $e->getMessage()); } // Only the script ran: no sequential fallback was attempted. @@ -412,4 +462,16 @@ public function testSaveUsesConfiguredPrefixInScript(): void $handler->clean(); } } + + + public function testSaveScriptUsesPcallForDataCommands(): void + { + $reflection = new \ReflectionClass(\CodeIgniter\Cache\Handlers\PredisHandler::class); + $script = $reflection->getConstant('SAVE_SCRIPT'); + $this->assertStringContainsString("redis.pcall('HMSET'", $script); + $this->assertStringContainsString("redis.pcall('EXPIREAT'", $script); + $this->assertStringNotContainsString("redis.call('HMSET'", $script); + $this->assertStringNotContainsString("redis.call('EXPIREAT'", $script); + } + } diff --git a/tests/system/Cache/Handlers/RedisHandlerTest.php b/tests/system/Cache/Handlers/RedisHandlerTest.php index 16f369aa7952..bdbae8d25f57 100644 --- a/tests/system/Cache/Handlers/RedisHandlerTest.php +++ b/tests/system/Cache/Handlers/RedisHandlerTest.php @@ -409,7 +409,7 @@ public function testSaveReturnsFalseWithoutFallbackWhenEvalFailsWithoutError(): } } - public function testSaveReturnsFalseWithoutFallbackWhenHmsetIsDeniedInsideScript(): void + public function testSaveThrowsWithoutFallbackWhenHmsetIsDeniedInsideScript(): void { /** @var Redis $originalRedis */ $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); @@ -429,10 +429,45 @@ public function testSaveReturnsFalseWithoutFallbackWhenHmsetIsDeniedInsideScript $failingRedis->expects($this->never()) ->method('expireAt'); + $this->expectException(RedisException::class); + $this->expectExceptionMessage("no permissions to run the 'hmset' command"); + try { $this->setPrivateProperty($this->handler, 'redis', $failingRedis); - $this->assertFalse($this->handler->save(self::$key1, 'new_value', 60)); + $this->handler->save(self::$key1, 'new_value', 60); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } + + public function testSaveThrowsWithoutFallbackWhenExpireatIsDeniedInsideScript(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('eval') + ->willReturn(false); + $failingRedis->expects($this->once()) + ->method('getLastError') + ->willReturn("NOPERM this user has no permissions to run the 'expireat' command"); + $failingRedis->expects($this->never()) + ->method('hMset'); + $failingRedis->expects($this->never()) + ->method('expireAt'); + + $this->expectException(RedisException::class); + $this->expectExceptionMessage("no permissions to run the 'expireat' command"); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->handler->save(self::$key1, 'new_value', 60); } finally { $this->setPrivateProperty($this->handler, 'redis', $originalRedis); } @@ -523,4 +558,78 @@ public function testSaveFallsBackWhenEvalIsDeniedByAcl(): void $this->setPrivateProperty($this->handler, 'redis', $originalRedis); } } + + public function testSaveThrowsWhenAclFailureInScriptReturnedAsFalse(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('eval') + ->willReturn(false); + $failingRedis->expects($this->once()) + ->method('getLastError') + ->willReturn("ERR ACL failure in script: No permissions to access a key"); + $failingRedis->expects($this->never()) + ->method('hMset'); + $failingRedis->expects($this->never()) + ->method('expireAt'); + + $this->expectException(RedisException::class); + $this->expectExceptionMessage('ACL failure in script'); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->handler->save(self::$key1, 'new_value', 60); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } + + public function testSaveFallsBackWhenEvalDeniedByAclReturnedAsFalse(): void + { + /** @var Redis $originalRedis */ + $originalRedis = $this->getPrivateProperty($this->handler, 'redis'); + + $failingRedis = $this->createMock(Redis::class); + $failingRedis->expects($this->once()) + ->method('clearLastError') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('eval') + ->willReturn(false); + $failingRedis->expects($this->once()) + ->method('getLastError') + ->willReturn("NOPERM this user has no permissions to run the 'eval' command"); + $failingRedis->expects($this->once()) + ->method('hMset') + ->willReturn(true); + $failingRedis->expects($this->once()) + ->method('expireAt') + ->willReturn(true); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $this->assertTrue($this->handler->save(self::$key1, 'fallback_value', 120)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalRedis); + } + } + + public function testSaveScriptUsesPcallForDataCommands(): void + { + $reflection = new \ReflectionClass(\CodeIgniter\Cache\Handlers\RedisHandler::class); + $script = $reflection->getConstant('SAVE_SCRIPT'); + $this->assertStringContainsString("redis.pcall('HMSET'", $script); + $this->assertStringContainsString("redis.pcall('EXPIREAT'", $script); + $this->assertStringNotContainsString("redis.call('HMSET'", $script); + $this->assertStringNotContainsString("redis.call('EXPIREAT'", $script); + } + } From 2ced984dd802e1e668107ad420d3e9008116043e Mon Sep 17 00:00:00 2001 From: Bogdan Date: Tue, 17 Nov 2026 22:27:57 +0100 Subject: [PATCH 6/6] cs(Cache): apply CS Fixer and Rector to cache handler regression tests Adds (string) casts in assertString*ContainsString calls per StringCastAssertStringContainsStringRector and aligns formatting with PHP CS Fixer; no behavioral changes. --- .../system/Cache/Handlers/PredisHandlerTest.php | 15 +++++++-------- tests/system/Cache/Handlers/RedisHandlerTest.php | 16 ++++++++-------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/tests/system/Cache/Handlers/PredisHandlerTest.php b/tests/system/Cache/Handlers/PredisHandlerTest.php index a4974df37454..22b45fa5555d 100644 --- a/tests/system/Cache/Handlers/PredisHandlerTest.php +++ b/tests/system/Cache/Handlers/PredisHandlerTest.php @@ -20,6 +20,7 @@ use PHPUnit\Framework\Attributes\Group; use Predis\Client; use Predis\Response\ServerException; +use ReflectionClass; use Throwable; /** @@ -463,15 +464,13 @@ public function testSaveUsesConfiguredPrefixInScript(): void } } - public function testSaveScriptUsesPcallForDataCommands(): void { - $reflection = new \ReflectionClass(\CodeIgniter\Cache\Handlers\PredisHandler::class); - $script = $reflection->getConstant('SAVE_SCRIPT'); - $this->assertStringContainsString("redis.pcall('HMSET'", $script); - $this->assertStringContainsString("redis.pcall('EXPIREAT'", $script); - $this->assertStringNotContainsString("redis.call('HMSET'", $script); - $this->assertStringNotContainsString("redis.call('EXPIREAT'", $script); + $reflection = new ReflectionClass(PredisHandler::class); + $script = $reflection->getConstant('SAVE_SCRIPT'); + $this->assertStringContainsString("redis.pcall('HMSET'", (string) $script); + $this->assertStringContainsString("redis.pcall('EXPIREAT'", (string) $script); + $this->assertStringNotContainsString("redis.call('HMSET'", (string) $script); + $this->assertStringNotContainsString("redis.call('EXPIREAT'", (string) $script); } - } diff --git a/tests/system/Cache/Handlers/RedisHandlerTest.php b/tests/system/Cache/Handlers/RedisHandlerTest.php index bdbae8d25f57..f3d24aafe12c 100644 --- a/tests/system/Cache/Handlers/RedisHandlerTest.php +++ b/tests/system/Cache/Handlers/RedisHandlerTest.php @@ -21,6 +21,7 @@ use PHPUnit\Framework\Attributes\Group; use Redis; use RedisException; +use ReflectionClass; /** * @internal @@ -573,7 +574,7 @@ public function testSaveThrowsWhenAclFailureInScriptReturnedAsFalse(): void ->willReturn(false); $failingRedis->expects($this->once()) ->method('getLastError') - ->willReturn("ERR ACL failure in script: No permissions to access a key"); + ->willReturn('ERR ACL failure in script: No permissions to access a key'); $failingRedis->expects($this->never()) ->method('hMset'); $failingRedis->expects($this->never()) @@ -624,12 +625,11 @@ public function testSaveFallsBackWhenEvalDeniedByAclReturnedAsFalse(): void public function testSaveScriptUsesPcallForDataCommands(): void { - $reflection = new \ReflectionClass(\CodeIgniter\Cache\Handlers\RedisHandler::class); - $script = $reflection->getConstant('SAVE_SCRIPT'); - $this->assertStringContainsString("redis.pcall('HMSET'", $script); - $this->assertStringContainsString("redis.pcall('EXPIREAT'", $script); - $this->assertStringNotContainsString("redis.call('HMSET'", $script); - $this->assertStringNotContainsString("redis.call('EXPIREAT'", $script); + $reflection = new ReflectionClass(RedisHandler::class); + $script = $reflection->getConstant('SAVE_SCRIPT'); + $this->assertStringContainsString("redis.pcall('HMSET'", (string) $script); + $this->assertStringContainsString("redis.pcall('EXPIREAT'", (string) $script); + $this->assertStringNotContainsString("redis.call('HMSET'", (string) $script); + $this->assertStringNotContainsString("redis.call('EXPIREAT'", (string) $script); } - }