diff --git a/system/Cache/Handlers/PredisHandler.php b/system/Cache/Handlers/PredisHandler.php index 79e7ae98f916..f7408c8dc284 100644 --- a/system/Cache/Handlers/PredisHandler.php +++ b/system/Cache/Handlers/PredisHandler.php @@ -19,6 +19,7 @@ use Exception; use Predis\Client; use Predis\Collection\Iterator\Keyspace; +use Predis\Response\ServerException; use Predis\Response\Status; /** @@ -26,6 +27,31 @@ */ class PredisHandler extends BaseHandler { + /** + * Lua script to execute HMSET and EXPIREAT in a single round trip. + * + * 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 + * 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 res + end + local exp = redis.pcall('EXPIREAT', KEYS[1], ARGV[1]) + if type(exp) == 'table' and exp.err then + return exp + end + return 1 + LUA; + /** * Default config * @@ -118,17 +144,51 @@ 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) { + 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; + } } - if ($ttl !== 0) { - $this->redis->expireat($key, Time::now()->getTimestamp() + $ttl); + // 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 { $key = static::validateKey($key); diff --git a/system/Cache/Handlers/RedisHandler.php b/system/Cache/Handlers/RedisHandler.php index ccbb29bcd032..faf992d19abd 100644 --- a/system/Cache/Handlers/RedisHandler.php +++ b/system/Cache/Handlers/RedisHandler.php @@ -24,6 +24,32 @@ */ class RedisHandler extends BaseHandler { + /** + * Lua script to execute HMSET and EXPIREAT in a single round trip. + * + * 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 + * 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 res + end + local exp = redis.pcall('EXPIREAT', KEYS[1], ARGV[1]) + if type(exp) == 'table' and exp.err then + return exp + end + return 1 + LUA; + /** * Default config * @@ -134,17 +160,92 @@ public function save(string $key, mixed $value, int $ttl = 60): bool return false; } - if (! $this->redis->hMset($key, ['__ci_type' => $dataType, '__ci_value' => $value])) { + $fields = ['__ci_type' => $dataType, '__ci_value' => $value]; + + if ($ttl === 0) { + return (bool) $this->redis->hMset($key, $fields); + } + + $expiresAt = Time::now()->getTimestamp() + $ttl; + + $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; + } + + // phpredis reports server errors as false and keeps the message in getLastError(). + $error = $this->redis->getLastError(); + + 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; + } + + $shouldFallback = true; + } + + if (! $shouldFallback) { return false; } - if ($ttl !== 0) { - $this->redis->expireAt($key, Time::now()->getTimestamp() + $ttl); + // EVAL is unavailable (renamed command or ACL denial): run both commands sequentially. + if (! $this->redis->hMset($key, $fields)) { + return false; } + $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; + } + + /** + * 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 91949f53238f..22b45fa5555d 100644 --- a/tests/system/Cache/Handlers/PredisHandlerTest.php +++ b/tests/system/Cache/Handlers/PredisHandlerTest.php @@ -18,6 +18,10 @@ use CodeIgniter\I18n\Time; use Config\Cache; use PHPUnit\Framework\Attributes\Group; +use Predis\Client; +use Predis\Response\ServerException; +use ReflectionClass; +use Throwable; /** * @internal @@ -196,4 +200,277 @@ public function testReconnect(): void $this->assertSame('value', $this->handler->get(self::$key1)); } + + public function testSaveThrowsServerExceptionOnNonHashKeyPreservingValueAndTtl(): void + { + /** @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->setPrivateProperty($this->handler, 'redis', $spy); + + 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); + + $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)); + } finally { + $this->setPrivateProperty($this->handler, 'redis', $originalClient); + $redis->del([$prefixedKey]); + } + } + + public function testSaveFallbackWhenEvalThrowsException(): 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 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("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. + $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(); + } + } + + public function testSaveScriptUsesPcallForDataCommands(): void + { + $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 1f85ecc28349..f3d24aafe12c 100644 --- a/tests/system/Cache/Handlers/RedisHandlerTest.php +++ b/tests/system/Cache/Handlers/RedisHandlerTest.php @@ -19,6 +19,9 @@ use Config\Cache; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; +use Redis; +use RedisException; +use ReflectionClass; /** * @internal @@ -238,4 +241,395 @@ 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 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', with args beginning with: 'local res = redis.pcall(...)")); + $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 testSaveFallbackWhenEvalReturnsFalse(): 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 unknown command 'EVAL', with args beginning with: 'local res = redis.pcall(...)"); + $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 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(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()) + ->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 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 testSaveThrowsWithoutFallbackWhenHmsetIsDeniedInsideScript(): 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'); + + $this->expectException(RedisException::class); + $this->expectExceptionMessage("no permissions to run the 'hmset' command"); + + try { + $this->setPrivateProperty($this->handler, 'redis', $failingRedis); + + $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); + } + } + + 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); + } + } + + 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(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); + } }