Skip to content

Commit 4da6c1e

Browse files
committed
Improve Manager user-input validation
- New check is done on the JSON cache integrity before saving in the cache and on retrieving from the backend cache
1 parent 24b65e1 commit 4da6c1e

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

src/Manager.php

+17-9
Original file line numberDiff line numberDiff line change
@@ -53,20 +53,26 @@ public function __construct(CacheInterface $cache, HttpClient $http)
5353
*
5454
* @param string $source_url the Public Suffix List URL
5555
*
56+
* @throws Exception If the PSL can not be fetch from the source URL and its cache backend
57+
* @throws Exception If the PSL cache copy is corrupted
58+
*
5659
* @return Rules
5760
*/
5861
public function getRules(string $source_url = self::PSL_URL): Rules
5962
{
6063
$cacheKey = $this->getCacheKey($source_url);
61-
if (null !== ($rules = $this->cache->get($cacheKey))) {
62-
return new Rules(json_decode($rules, true));
63-
}
64+
$rules = $this->cache->get($cacheKey);
6465

65-
if (!$this->refreshRules($source_url)) {
66+
if (null === $rules && !$this->refreshRules($source_url)) {
6667
throw new Exception(sprintf('Unable to load the public suffix list rules for %s', $source_url));
6768
}
6869

69-
return new Rules(json_decode($this->cache->get($cacheKey), true));
70+
$rules = json_decode($rules ?? $this->cache->get($cacheKey), true);
71+
if (JSON_ERROR_NONE === json_last_error()) {
72+
return new Rules($rules);
73+
}
74+
75+
throw new Exception('The public suffix list cache is corrupted: '.json_last_error_msg(), json_last_error());
7076
}
7177

7278
/**
@@ -92,16 +98,18 @@ private function getCacheKey(string $str): string
9298
*
9399
* @param string $source_url the Public Suffix List URL
94100
*
101+
* @throws If the PSL can not be converted to JSON format
102+
*
95103
* @return bool
96104
*/
97105
public function refreshRules(string $source_url = self::PSL_URL): bool
98106
{
99107
$content = $this->http->getContent($source_url);
100-
$rules = (new Converter())->convert($content);
101-
if (empty($rules[Rules::ICANN_DOMAINS]) || empty($rules[Rules::PRIVATE_DOMAINS])) {
102-
return false;
108+
$rules = json_encode((new Converter())->convert($content));
109+
if (JSON_ERROR_NONE === json_last_error()) {
110+
return $this->cache->set($this->getCacheKey($source_url), $rules);
103111
}
104112

105-
return $this->cache->set($this->getCacheKey($source_url), json_encode($rules));
113+
throw new Exception('The public suffix list JSON conversion failed: '.json_last_error_msg(), json_last_error());
106114
}
107115
}

0 commit comments

Comments
 (0)