Skip to content

Commit 1eef866

Browse files
committed
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.
1 parent 81bef53 commit 1eef866

4 files changed

Lines changed: 219 additions & 13 deletions

File tree

‎system/Cache/Handlers/PredisHandler.php‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,11 @@ class PredisHandler extends BaseHandler
3030
/**
3131
* Lua script to execute HMSET and EXPIREAT in a single round trip.
3232
*
33-
* The pcall error reply is returned to the client, so an HMSET error (e.g.
34-
* WRONGTYPE) never runs EXPIREAT, keeps its original error type, and is not
35-
* retried by the sequential fallback in save().
33+
* Both commands run through pcall and their error reply is returned as-is,
34+
* so an HMSET error (e.g. WRONGTYPE) stops the script before EXPIREAT and
35+
* every error keeps its original type and message. Predis raises
36+
* ServerException for such a reply, which save() only swallows when it is
37+
* about EVAL itself, so an ACL denial is never retried sequentially.
3638
*
3739
* If HMSET succeeds and EXPIREAT is rejected, the hash is stored without a
3840
* TTL, exactly as with the previous sequential implementation (Redis does
@@ -43,7 +45,10 @@ class PredisHandler extends BaseHandler
4345
if type(res) == 'table' and res.err then
4446
return res
4547
end
46-
redis.call('EXPIREAT', KEYS[1], ARGV[1])
48+
local exp = redis.pcall('EXPIREAT', KEYS[1], ARGV[1])
49+
if type(exp) == 'table' and exp.err then
50+
return exp
51+
end
4752
return 1
4853
LUA;
4954

‎system/Cache/Handlers/RedisHandler.php‎

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,12 @@ class RedisHandler extends BaseHandler
2727
/**
2828
* Lua script to execute HMSET and EXPIREAT in a single round trip.
2929
*
30-
* The pcall error reply is returned to the client, so a failing HMSET never
31-
* runs EXPIREAT and the original error message and type are preserved:
32-
* clients that throw on error replies raise RedisException, phpredis exposes
33-
* the message through Redis::getLastError().
30+
* Both commands run through pcall and their error reply is returned as-is,
31+
* so a failing HMSET never runs EXPIREAT and the original error message and
32+
* type are preserved. phpredis exposes the message through
33+
* Redis::getLastError(); save() rethrows a permission error as
34+
* RedisException, as the sequential implementation did, and keeps reporting
35+
* any other error (e.g. WRONGTYPE) as false.
3436
*
3537
* If HMSET succeeds and EXPIREAT is rejected, the hash is stored without a
3638
* TTL, exactly as with the previous sequential implementation (Redis does
@@ -41,7 +43,10 @@ class RedisHandler extends BaseHandler
4143
if type(res) == 'table' and res.err then
4244
return res
4345
end
44-
redis.call('EXPIREAT', KEYS[1], ARGV[1])
46+
local exp = redis.pcall('EXPIREAT', KEYS[1], ARGV[1])
47+
if type(exp) == 'table' and exp.err then
48+
return exp
49+
end
4550
return 1
4651
LUA;
4752

@@ -181,7 +186,15 @@ public function save(string $key, mixed $value, int $ttl = 60): bool
181186
// phpredis reports server errors as false and keeps the message in getLastError().
182187
$error = $this->redis->getLastError();
183188

184-
$shouldFallback = is_string($error) && self::isEvalUnavailable($error);
189+
if (is_string($error)) {
190+
if (self::isEvalUnavailable($error)) {
191+
$shouldFallback = true;
192+
} elseif (self::isDataCommandPermissionError($error)) {
193+
// HMSET or EXPIREAT was denied by an ACL: the script itself ran,
194+
// so keep throwing exactly like the sequential implementation did.
195+
throw new RedisException($error);
196+
}
197+
}
185198
} catch (RedisException $e) {
186199
if (! self::isEvalUnavailable($e->getMessage())) {
187200
throw $e;
@@ -216,6 +229,23 @@ private static function isEvalUnavailable(string $message): bool
216229
|| preg_match("/no permissions to run the [`']eval[`'] command/i", $message) === 1;
217230
}
218231

232+
/**
233+
* Checks whether the message means that a data command executed inside the
234+
* save script was denied by an ACL.
235+
*
236+
* EVAL availability was already checked, so the denied command can only be
237+
* HMSET or EXPIREAT. Redis reports it either as a command level denial or as
238+
* an ACL failure while running the script.
239+
*
240+
* Predis throws for every error reply, so this mapping only exists for the
241+
* phpredis false plus getLastError() path.
242+
*/
243+
private static function isDataCommandPermissionError(string $message): bool
244+
{
245+
return preg_match("/no permissions to run the [`']?[a-z]+[`'] command/i", $message) === 1
246+
|| preg_match('/ACL failure in script/i', $message) === 1;
247+
}
248+
219249
public function delete(string $key): bool
220250
{
221251
$key = static::validateKey($key, $this->prefix);

‎tests/system/Cache/Handlers/PredisHandlerTest.php‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,57 @@ public function __call($commandID, $arguments)
385385
$this->handler->save(self::$key1, 'denied_value', 120);
386386
$this->fail('Predis\Response\ServerException was not thrown when HMSET is denied inside the script.');
387387
} catch (ServerException $e) {
388-
$this->assertStringContainsString('NOPERM', $e->getMessage());
388+
$this->assertStringContainsString("no permissions to run the 'hmset' command", $e->getMessage());
389+
}
390+
391+
// Only the script ran: no sequential fallback was attempted.
392+
$this->assertSame(['eval'], $failingClient->commands);
393+
} finally {
394+
$this->setPrivateProperty($this->handler, 'redis', $originalClient);
395+
}
396+
}
397+
398+
public function testSaveRethrowsWhenExpireatIsDeniedInsideScript(): void
399+
{
400+
/** @var Client $originalClient */
401+
$originalClient = $this->getPrivateProperty($this->handler, 'redis');
402+
403+
$prefix = $this->config->prefix;
404+
405+
$failingClient = new class ($originalClient->getConnection()->getParameters(), ['prefix' => $prefix]) extends Client {
406+
/**
407+
* @var list<string>
408+
*/
409+
public array $commands = [];
410+
411+
public ?Throwable $evalException = null;
412+
413+
/**
414+
* @param string $commandID
415+
* @param array<int|string, mixed> $arguments
416+
*/
417+
public function __call($commandID, $arguments)
418+
{
419+
$this->commands[] = strtolower($commandID);
420+
421+
if (strtolower($commandID) === 'eval' && $this->evalException instanceof Throwable) {
422+
throw $this->evalException;
423+
}
424+
425+
return parent::__call($commandID, $arguments);
426+
}
427+
};
428+
429+
$failingClient->evalException = new ServerException("ERR ACL failure in script: User foo has no permissions to run the 'expireat' command");
430+
431+
try {
432+
$this->setPrivateProperty($this->handler, 'redis', $failingClient);
433+
434+
try {
435+
$this->handler->save(self::$key1, 'denied_value', 120);
436+
$this->fail('Predis\\Response\\ServerException was not thrown when EXPIREAT is denied inside the script.');
437+
} catch (ServerException $e) {
438+
$this->assertStringContainsString("no permissions to run the 'expireat' command", $e->getMessage());
389439
}
390440

391441
// Only the script ran: no sequential fallback was attempted.
@@ -412,4 +462,16 @@ public function testSaveUsesConfiguredPrefixInScript(): void
412462
$handler->clean();
413463
}
414464
}
465+
466+
467+
public function testSaveScriptUsesPcallForDataCommands(): void
468+
{
469+
$reflection = new \ReflectionClass(\CodeIgniter\Cache\Handlers\PredisHandler::class);
470+
$script = $reflection->getConstant('SAVE_SCRIPT');
471+
$this->assertStringContainsString("redis.pcall('HMSET'", $script);
472+
$this->assertStringContainsString("redis.pcall('EXPIREAT'", $script);
473+
$this->assertStringNotContainsString("redis.call('HMSET'", $script);
474+
$this->assertStringNotContainsString("redis.call('EXPIREAT'", $script);
475+
}
476+
415477
}

‎tests/system/Cache/Handlers/RedisHandlerTest.php‎

Lines changed: 111 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ public function testSaveReturnsFalseWithoutFallbackWhenEvalFailsWithoutError():
409409
}
410410
}
411411

412-
public function testSaveReturnsFalseWithoutFallbackWhenHmsetIsDeniedInsideScript(): void
412+
public function testSaveThrowsWithoutFallbackWhenHmsetIsDeniedInsideScript(): void
413413
{
414414
/** @var Redis $originalRedis */
415415
$originalRedis = $this->getPrivateProperty($this->handler, 'redis');
@@ -429,10 +429,45 @@ public function testSaveReturnsFalseWithoutFallbackWhenHmsetIsDeniedInsideScript
429429
$failingRedis->expects($this->never())
430430
->method('expireAt');
431431

432+
$this->expectException(RedisException::class);
433+
$this->expectExceptionMessage("no permissions to run the 'hmset' command");
434+
432435
try {
433436
$this->setPrivateProperty($this->handler, 'redis', $failingRedis);
434437

435-
$this->assertFalse($this->handler->save(self::$key1, 'new_value', 60));
438+
$this->handler->save(self::$key1, 'new_value', 60);
439+
} finally {
440+
$this->setPrivateProperty($this->handler, 'redis', $originalRedis);
441+
}
442+
}
443+
444+
public function testSaveThrowsWithoutFallbackWhenExpireatIsDeniedInsideScript(): void
445+
{
446+
/** @var Redis $originalRedis */
447+
$originalRedis = $this->getPrivateProperty($this->handler, 'redis');
448+
449+
$failingRedis = $this->createMock(Redis::class);
450+
$failingRedis->expects($this->once())
451+
->method('clearLastError')
452+
->willReturn(true);
453+
$failingRedis->expects($this->once())
454+
->method('eval')
455+
->willReturn(false);
456+
$failingRedis->expects($this->once())
457+
->method('getLastError')
458+
->willReturn("NOPERM this user has no permissions to run the 'expireat' command");
459+
$failingRedis->expects($this->never())
460+
->method('hMset');
461+
$failingRedis->expects($this->never())
462+
->method('expireAt');
463+
464+
$this->expectException(RedisException::class);
465+
$this->expectExceptionMessage("no permissions to run the 'expireat' command");
466+
467+
try {
468+
$this->setPrivateProperty($this->handler, 'redis', $failingRedis);
469+
470+
$this->handler->save(self::$key1, 'new_value', 60);
436471
} finally {
437472
$this->setPrivateProperty($this->handler, 'redis', $originalRedis);
438473
}
@@ -523,4 +558,78 @@ public function testSaveFallsBackWhenEvalIsDeniedByAcl(): void
523558
$this->setPrivateProperty($this->handler, 'redis', $originalRedis);
524559
}
525560
}
561+
562+
public function testSaveThrowsWhenAclFailureInScriptReturnedAsFalse(): void
563+
{
564+
/** @var Redis $originalRedis */
565+
$originalRedis = $this->getPrivateProperty($this->handler, 'redis');
566+
567+
$failingRedis = $this->createMock(Redis::class);
568+
$failingRedis->expects($this->once())
569+
->method('clearLastError')
570+
->willReturn(true);
571+
$failingRedis->expects($this->once())
572+
->method('eval')
573+
->willReturn(false);
574+
$failingRedis->expects($this->once())
575+
->method('getLastError')
576+
->willReturn("ERR ACL failure in script: No permissions to access a key");
577+
$failingRedis->expects($this->never())
578+
->method('hMset');
579+
$failingRedis->expects($this->never())
580+
->method('expireAt');
581+
582+
$this->expectException(RedisException::class);
583+
$this->expectExceptionMessage('ACL failure in script');
584+
585+
try {
586+
$this->setPrivateProperty($this->handler, 'redis', $failingRedis);
587+
588+
$this->handler->save(self::$key1, 'new_value', 60);
589+
} finally {
590+
$this->setPrivateProperty($this->handler, 'redis', $originalRedis);
591+
}
592+
}
593+
594+
public function testSaveFallsBackWhenEvalDeniedByAclReturnedAsFalse(): void
595+
{
596+
/** @var Redis $originalRedis */
597+
$originalRedis = $this->getPrivateProperty($this->handler, 'redis');
598+
599+
$failingRedis = $this->createMock(Redis::class);
600+
$failingRedis->expects($this->once())
601+
->method('clearLastError')
602+
->willReturn(true);
603+
$failingRedis->expects($this->once())
604+
->method('eval')
605+
->willReturn(false);
606+
$failingRedis->expects($this->once())
607+
->method('getLastError')
608+
->willReturn("NOPERM this user has no permissions to run the 'eval' command");
609+
$failingRedis->expects($this->once())
610+
->method('hMset')
611+
->willReturn(true);
612+
$failingRedis->expects($this->once())
613+
->method('expireAt')
614+
->willReturn(true);
615+
616+
try {
617+
$this->setPrivateProperty($this->handler, 'redis', $failingRedis);
618+
619+
$this->assertTrue($this->handler->save(self::$key1, 'fallback_value', 120));
620+
} finally {
621+
$this->setPrivateProperty($this->handler, 'redis', $originalRedis);
622+
}
623+
}
624+
625+
public function testSaveScriptUsesPcallForDataCommands(): void
626+
{
627+
$reflection = new \ReflectionClass(\CodeIgniter\Cache\Handlers\RedisHandler::class);
628+
$script = $reflection->getConstant('SAVE_SCRIPT');
629+
$this->assertStringContainsString("redis.pcall('HMSET'", $script);
630+
$this->assertStringContainsString("redis.pcall('EXPIREAT'", $script);
631+
$this->assertStringNotContainsString("redis.call('HMSET'", $script);
632+
$this->assertStringNotContainsString("redis.call('EXPIREAT'", $script);
633+
}
634+
526635
}

0 commit comments

Comments
 (0)