Skip to content

Commit 5b4f615

Browse files
committed
set a default and max ttl for redis keys
having infinite TTL can lead to leaked keys as the prefix changes with version upgrades Signed-off-by: Robin Appelman <robin@icewind.nl>
1 parent 09c5f99 commit 5b4f615

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

lib/private/Memcache/Redis.php

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ class Redis extends Cache implements IMemcacheTTL {
4848
],
4949
];
5050

51+
private const DEFAULT_TTL = 24 * 60 * 60; // 1 month
52+
private const MAX_TTL = 30 * 24 * 60 * 60; // 1 month
53+
5154
/**
5255
* @var \Redis|\RedisCluster $cache
5356
*/
@@ -79,11 +82,12 @@ public function get($key) {
7982

8083
public function set($key, $value, $ttl = 0) {
8184
$value = self::encodeValue($value);
82-
if ($ttl > 0) {
83-
return $this->getCache()->setex($this->getPrefix() . $key, $ttl, $value);
84-
} else {
85-
return $this->getCache()->set($this->getPrefix() . $key, $value);
85+
if ($ttl === 0) {
86+
// having infinite TTL can lead to leaked keys as the prefix changes with version upgrades
87+
$ttl = self::DEFAULT_TTL;
8688
}
89+
$ttl = min($ttl, self::MAX_TTL);
90+
return $this->getCache()->setex($this->getPrefix() . $key, $ttl, $value);
8791
}
8892

8993
public function hasKey($key) {
@@ -117,11 +121,14 @@ public function clear($prefix = '') {
117121
*/
118122
public function add($key, $value, $ttl = 0) {
119123
$value = self::encodeValue($value);
124+
if ($ttl === 0) {
125+
// having infinite TTL can lead to leaked keys as the prefix changes with version upgrades
126+
$ttl = self::DEFAULT_TTL;
127+
}
128+
$ttl = min($ttl, self::MAX_TTL);
120129

121130
$args = ['nx'];
122-
if ($ttl !== 0 && is_int($ttl)) {
123-
$args['ex'] = $ttl;
124-
}
131+
$args['ex'] = $ttl;
125132

126133
return $this->getCache()->set($this->getPrefix() . $key, $value, $args);
127134
}
@@ -178,6 +185,11 @@ public function cad($key, $old) {
178185
}
179186

180187
public function setTTL($key, $ttl) {
188+
if ($ttl === 0) {
189+
// having infinite TTL can lead to leaked keys as the prefix changes with version upgrades
190+
$ttl = self::DEFAULT_TTL;
191+
}
192+
$ttl = min($ttl, self::MAX_TTL);
181193
$this->getCache()->expire($this->getPrefix() . $key, $ttl);
182194
}
183195

0 commit comments

Comments
 (0)