diff --git a/Backend/Controllers/RedisSettingsAdmin.php b/Backend/Controllers/RedisSettingsAdmin.php index 739bfff..013b426 100644 --- a/Backend/Controllers/RedisSettingsAdmin.php +++ b/Backend/Controllers/RedisSettingsAdmin.php @@ -3,25 +3,61 @@ namespace Okay\Modules\Sviat\Redis\Backend\Controllers; use Okay\Admin\Controllers\IndexAdmin; +use Okay\Modules\Sviat\Redis\Security\RequestOrigin; use Okay\Modules\Sviat\Redis\Services\RedisCacheService; +use Okay\Modules\Sviat\Redis\Services\RedisConnectionForm; class RedisSettingsAdmin extends IndexAdmin { + /** Інші POST сторінки (вихід з адмінки) приходять сюди порожніми й не мають зачепити налаштування. */ + private const array ACTIONS = ['save', 'test', 'flush_helpers']; + public function fetch(RedisCacheService $redisCache) { $testResult = null; $error = null; $flushError = null; + $formErrors = []; + $passwordDropped = false; + + $locked = $redisCache->lockedConnectionFields(); + + if ($this->request->method('post') && in_array($this->request->post('action'), self::ACTIONS, true)) { + if (!$this->isFromThisSite()) { + $this->response->setStatusCode(403); + $this->response->setContent(json_encode(['message' => 'Forbidden']), RESPONSE_JSON); + + return; + } + + if (!isset($locked['enabled'])) { + $this->settings->set('sviat__redis__enabled', (int) $this->request->post('enabled')); + } + + $connection = RedisConnectionForm::apply( + [ + 'host' => $this->request->post('host'), + 'port' => $this->request->post('port'), + 'db' => $this->request->post('db'), + 'username' => $this->request->post('username'), + 'password' => $this->request->post('password'), + 'clear_password' => $this->request->post('clear_password'), + 'prefix' => $this->request->post('prefix'), + ], + [ + 'host' => (string) ($this->settings->get('sviat__redis__host') ?: '127.0.0.1'), + 'port' => (string) ($this->settings->get('sviat__redis__port') ?: 6379), + 'username' => (string) ($this->settings->get('sviat__redis__username') ?? ''), + 'password' => (string) ($this->settings->get('sviat__redis__password') ?? ''), + ], + $locked + ); + foreach ($connection['values'] as $field => $value) { + $this->settings->set('sviat__redis__' . $field, $value); + } + $formErrors = $connection['errors']; + $passwordDropped = $connection['passwordDropped']; - if ($this->request->method('post')) { - $this->settings->set('sviat__redis__enabled', (int)$this->request->post('enabled')); - $this->settings->set('sviat__redis__host', $this->request->post('host')); - $this->settings->set('sviat__redis__port', (int)$this->request->post('port')); - $this->settings->set('sviat__redis__db', (int)$this->request->post('db')); - $this->settings->set('sviat__redis__username', trim((string) $this->request->post('username'))); - // Save password as-is; empty value means no auth. - $this->settings->set('sviat__redis__password', (string) ($this->request->post('password') ?? '')); - $this->settings->set('sviat__redis__prefix', $this->request->post('prefix')); $this->settings->set('sviat__redis__default_ttl', (int)$this->request->post('default_ttl')); $this->settings->set('sviat__redis__ttl__products_get_list', (int)$this->request->post('ttl_products_get_list')); @@ -31,7 +67,6 @@ public function fetch(RedisCacheService $redisCache) $this->settings->set('sviat__redis__ttl__product_attach_variants', (int)$this->request->post('ttl_product_attach_variants')); $this->settings->set('sviat__redis__ttl__product_attach_images', (int)$this->request->post('ttl_product_attach_images')); $this->settings->set('sviat__redis__ttl__product_attach_features', (int)$this->request->post('ttl_product_attach_features')); - $this->settings->set('sviat__redis__ttl__money_currencies_list', (int)$this->request->post('ttl_money_currencies_list')); $this->settings->set('sviat__redis__ttl__brands_get_list', (int)$this->request->post('ttl_brands_get_list')); $this->settings->set('sviat__redis__ttl__filter_get_brands', (int)$this->request->post('ttl_filter_get_brands')); $this->settings->set('sviat__redis__ttl__authors_get_list', (int)$this->request->post('ttl_authors_get_list')); @@ -58,13 +93,17 @@ public function fetch(RedisCacheService $redisCache) $stats = $redisCache->getStats(); - $this->design->assign('redis_enabled', (int)$this->settings->get('sviat__redis__enabled')); - $this->design->assign('redis_host', $this->settings->get('sviat__redis__host') ?: '127.0.0.1'); - $this->design->assign('redis_port', (int)($this->settings->get('sviat__redis__port') ?: 6379)); - $this->design->assign('redis_db', (int)($this->settings->get('sviat__redis__db') ?: 0)); - $this->design->assign('redis_username', (string) ($this->settings->get('sviat__redis__username') ?? '')); - $this->design->assign('redis_password', $this->settings->get('sviat__redis__password')); - $this->design->assign('redis_prefix', $this->settings->get('sviat__redis__prefix') ?: 'okay:'); + $view = $redisCache->connectionView(); + $this->design->assign('redis_locked', $locked); + $this->design->assign('redis_form_errors', $formErrors); + $this->design->assign('redis_password_dropped', $passwordDropped); + $this->design->assign('redis_enabled', (int) $view['enabled']); + $this->design->assign('redis_host', $view['host']); + $this->design->assign('redis_port', $view['port']); + $this->design->assign('redis_db', $view['db']); + $this->design->assign('redis_username', $view['username']); + $this->design->assign('redis_password_is_set', (string) ($this->settings->get('sviat__redis__password') ?? '') !== ''); + $this->design->assign('redis_prefix', $view['prefix']); $this->design->assign('redis_default_ttl', (int)($this->settings->get('sviat__redis__default_ttl') ?: 600)); $this->design->assign('ttl_products_get_list', (int)($this->settings->get('sviat__redis__ttl__products_get_list') ?: 300)); @@ -74,7 +113,6 @@ public function fetch(RedisCacheService $redisCache) $this->design->assign('ttl_product_attach_variants', (int)($this->settings->get('sviat__redis__ttl__product_attach_variants') ?: 300)); $this->design->assign('ttl_product_attach_images', (int)($this->settings->get('sviat__redis__ttl__product_attach_images') ?: 3600)); $this->design->assign('ttl_product_attach_features', (int)($this->settings->get('sviat__redis__ttl__product_attach_features') ?: 3600)); - $this->design->assign('ttl_money_currencies_list', (int)($this->settings->get('sviat__redis__ttl__money_currencies_list') ?: 3600)); $this->design->assign('ttl_brands_get_list', (int)($this->settings->get('sviat__redis__ttl__brands_get_list') ?: 600)); $this->design->assign('ttl_filter_get_brands', (int)($this->settings->get('sviat__redis__ttl__filter_get_brands') ?: 600)); $this->design->assign('ttl_authors_get_list', (int)($this->settings->get('sviat__redis__ttl__authors_get_list') ?: 600)); @@ -88,5 +126,10 @@ public function fetch(RedisCacheService $redisCache) $this->response->setContent($this->design->fetch('redis_settings.tpl')); } -} + /** На стоку CSRF-перевірка ядра стоїть після контролера, тому модуль перевіряє сам. */ + protected function isFromThisSite(): bool + { + return RequestOrigin::isFromThisSite(); + } +} diff --git a/Backend/design/html/redis_settings.tpl b/Backend/design/html/redis_settings.tpl index f7f4f71..c96fbb4 100644 --- a/Backend/design/html/redis_settings.tpl +++ b/Backend/design/html/redis_settings.tpl @@ -9,7 +9,7 @@ {* Алерти: збережено / результат тесту підключення *} -{if $message_success || $test_result === true || $test_result === false || $flush_error !== null} +{if $message_success || $test_result === true || $test_result === false || $flush_error !== null || $redis_form_errors || $redis_password_dropped}
{if $message_success} @@ -19,6 +19,20 @@
{/if} + {if $redis_form_errors} +
+
+
{$btr->sviat_redis_form_invalid|escape}
+
+
+ {/if} + {if $redis_password_dropped} +
+
+
{$btr->sviat_redis_password_dropped|escape}
+
+
+ {/if} {if $test_result === true}
@@ -53,13 +67,21 @@
{$btr->sviat_redis_connection_box|escape}
+ {if $redis_locked} +
+
+
{$btr->sviat_redis_locked_hint|escape}
+
+
+ {/if} +
@@ -70,32 +92,40 @@
- +
- +
- +
- +
+ {if !$redis_locked.password}
- + + {if $redis_password_is_set} + + {/if}
+ {/if}
- +
@@ -191,12 +221,6 @@
-
-
- - -
-
diff --git a/Backend/lang/en.php b/Backend/lang/en.php index 7c90318..e2015b1 100644 --- a/Backend/lang/en.php +++ b/Backend/lang/en.php @@ -12,13 +12,18 @@ $lang['sviat_redis_username'] = 'Username'; $lang['sviat_redis_username_placeholder'] = 'ACL (Redis 6+), empty = password only'; $lang['sviat_redis_password'] = 'Password'; -$lang['sviat_redis_password_placeholder'] = 'Empty = no authentication'; +$lang['sviat_redis_clear_password'] = 'Remove stored password'; +$lang['sviat_redis_locked_hint'] = 'Part of the connection is set outside the admin panel (env or config.local.php), those fields cannot be changed here.'; +$lang['sviat_redis_form_invalid'] = 'Some fields are invalid and were not saved.'; +$lang['sviat_redis_password_dropped'] = 'The host changed, so the stored password was removed. Enter the password for the new server.'; +$lang['sviat_redis_password_placeholder'] = 'Leave blank to keep the current password'; +$lang['sviat_redis_password_placeholder_empty'] = 'Empty = no authentication'; $lang['sviat_redis_key_prefix'] = 'Key prefix'; $lang['sviat_redis_default_ttl'] = 'Default TTL (sec)'; $lang['sviat_redis_test_connection'] = 'Test connection'; $lang['sviat_redis_cache_status'] = 'Cache status'; $lang['sviat_redis_db_keys_count'] = 'Number of keys in DB'; $lang['sviat_redis_used_memory'] = 'Used memory'; -$lang['sviat_redis_flush_current_db'] = 'Clear all Redis cache (current DB)'; +$lang['sviat_redis_flush_current_db'] = 'Clear this module cache'; $lang['sviat_redis_unavailable'] = 'Redis is unavailable'; $lang['sviat_redis_helpers_ttl'] = 'TTL for helpers'; diff --git a/Backend/lang/ru.php b/Backend/lang/ru.php index 4e16f50..dc12e6f 100644 --- a/Backend/lang/ru.php +++ b/Backend/lang/ru.php @@ -12,13 +12,18 @@ $lang['sviat_redis_username'] = 'Username'; $lang['sviat_redis_username_placeholder'] = 'ACL (Redis 6+), пусто = только пароль'; $lang['sviat_redis_password'] = 'Password'; -$lang['sviat_redis_password_placeholder'] = 'Пусто = без авторизации'; +$lang['sviat_redis_clear_password'] = 'Удалить сохранённый пароль'; +$lang['sviat_redis_locked_hint'] = 'Часть подключения задана вне админки (env или config.local.php), эти поля здесь не меняются.'; +$lang['sviat_redis_form_invalid'] = 'Некоторые поля заполнены неверно и не сохранены.'; +$lang['sviat_redis_password_dropped'] = 'Хост изменился, поэтому сохранённый пароль удалён. Введите пароль нового сервера.'; +$lang['sviat_redis_password_placeholder'] = 'Оставьте пустым, чтобы сохранить текущий'; +$lang['sviat_redis_password_placeholder_empty'] = 'Пусто = без авторизации'; $lang['sviat_redis_key_prefix'] = 'Префикс ключей'; $lang['sviat_redis_default_ttl'] = 'TTL по умолчанию (сек)'; $lang['sviat_redis_test_connection'] = 'Проверить подключение'; $lang['sviat_redis_cache_status'] = 'Состояние кеша'; $lang['sviat_redis_db_keys_count'] = 'Количество ключей в БД'; $lang['sviat_redis_used_memory'] = 'Используемая память'; -$lang['sviat_redis_flush_current_db'] = 'Очистить весь кеш Redis (текущая DB)'; +$lang['sviat_redis_flush_current_db'] = 'Очистить кеш этого модуля'; $lang['sviat_redis_unavailable'] = 'Redis недоступен'; $lang['sviat_redis_helpers_ttl'] = 'TTL для хелперов'; diff --git a/Backend/lang/ua.php b/Backend/lang/ua.php index acef106..b049c7d 100644 --- a/Backend/lang/ua.php +++ b/Backend/lang/ua.php @@ -12,14 +12,19 @@ $lang['sviat_redis_username'] = 'Username'; $lang['sviat_redis_username_placeholder'] = 'ACL (Redis 6+), порожньо = лише пароль'; $lang['sviat_redis_password'] = 'Password'; -$lang['sviat_redis_password_placeholder'] = 'Порожньо = без авторизації'; +$lang['sviat_redis_clear_password'] = 'Видалити збережений пароль'; +$lang['sviat_redis_locked_hint'] = 'Частину підключення задано поза адмінкою (env або config.local.php), ці поля тут не змінюються.'; +$lang['sviat_redis_form_invalid'] = 'Деякі поля заповнено неправильно, їх не збережено.'; +$lang['sviat_redis_password_dropped'] = 'Хост змінився, тому збережений пароль видалено. Введіть пароль нового сервера.'; +$lang['sviat_redis_password_placeholder'] = 'Залиште порожнім, щоб зберегти поточний'; +$lang['sviat_redis_password_placeholder_empty'] = 'Порожньо = без авторизації'; $lang['sviat_redis_key_prefix'] = 'Префікс ключів'; $lang['sviat_redis_default_ttl'] = 'TTL за замовчуванням (сек)'; $lang['sviat_redis_test_connection'] = 'Протестувати підключення'; $lang['sviat_redis_cache_status'] = 'Стан кешу'; $lang['sviat_redis_db_keys_count'] = 'Кількість ключів у БД'; $lang['sviat_redis_used_memory'] = 'Використана пам\'ять'; -$lang['sviat_redis_flush_current_db'] = 'Очистити весь кеш Redis (поточна DB)'; +$lang['sviat_redis_flush_current_db'] = 'Очистити кеш цього модуля'; $lang['sviat_redis_unavailable'] = 'Redis недоступний'; $lang['sviat_redis_helpers_ttl'] = 'TTL для хелперів'; diff --git a/Extenders/CurrencyCacheInvalidator.php b/Extenders/CurrencyCacheInvalidator.php index b2a7260..3364aa9 100644 --- a/Extenders/CurrencyCacheInvalidator.php +++ b/Extenders/CurrencyCacheInvalidator.php @@ -18,21 +18,18 @@ public function __construct(RedisCacheService $redis) public function onCurrencyUpdate($output, $ids, $object): void { if (!$output) { return; } - $this->redis->bumpOnce(CacheTags::MONEY); $this->redis->bumpOnce(CacheTags::PRODUCTS_ALL); } public function onCurrencyAdd($output, $object): void { if ((int) $output <= 0) { return; } - $this->redis->bumpOnce(CacheTags::MONEY); $this->redis->bumpOnce(CacheTags::PRODUCTS_ALL); } public function onCurrencyDelete($output, $ids): void { if (!$output) { return; } - $this->redis->bumpOnce(CacheTags::MONEY); $this->redis->bumpOnce(CacheTags::PRODUCTS_ALL); } } diff --git a/Extenders/ProductRouteWarmer.php b/Extenders/ProductRouteWarmer.php new file mode 100644 index 0000000..4a88d73 --- /dev/null +++ b/Extenders/ProductRouteWarmer.php @@ -0,0 +1,51 @@ +router = $router; + $this->entityFactory = $entityFactory; + } + + public function warmCurrentProduct(): void + { + if ($this->routeName() !== self::PRODUCT_ROUTE) { + return; + } + + $url = (string) ($this->router->getCurrentRouteRequiredParams()['url'] ?? ''); + if ($url === '' || ProductRoute::getUrlSlugAlias($url)) { + return; + } + + $route = $this->entityFactory->get(RouterCacheEntity::class)->findOne(['url' => $url, 'type' => 'product']); + if (!empty($route->slug_url)) { + ProductRoute::setUrlSlugAlias($url, $route->slug_url); + } + } + + protected function routeName(): ?string + { + return Router::getCurrentRouteName(); + } +} diff --git a/Helpers/MoneyHelper.php b/Helpers/MoneyHelper.php deleted file mode 100644 index c41d9a0..0000000 --- a/Helpers/MoneyHelper.php +++ /dev/null @@ -1,71 +0,0 @@ -entityFactory = $entityFactory; - $this->settings = $settings; - $this->redis = $redis; - } - - private function getCurrenciesList(): array - { - if (!$this->redis->isEnabled()) { - return $this->loadCurrenciesFromDb(); - } - $key = $this->redis->makeVersionedKey('money_currencies_list', [CacheTags::MONEY], []); - $cached = $this->redis->get($key); - if (is_array($cached) && !empty($cached)) { - return $cached; - } - $currencies = $this->loadCurrenciesFromDb(); - if (!empty($currencies)) { - $this->redis->set($key, $currencies, $this->redis->getHelperTtl('money_currencies_list') ?? 3600); - } - return $currencies; - } - - private function loadCurrenciesFromDb(): array - { - /** @var CurrenciesEntity $currenciesEntity */ - $currenciesEntity = $this->entityFactory->get(CurrenciesEntity::class); - return $currenciesEntity->mappedBy('id')->find(); - } - - public function convertVariantPriceToMainCurrency($variant) - { - if (empty($variant)) { - return ExtenderFacade::execute(__METHOD__, $variant, func_get_args()); - } - if ($this->settings->get('hide_equal_compare_price') && $variant->compare_price <= $variant->price) { - $variant->compare_price = null; - } - $currencies = $this->getCurrenciesList(); - if (!isset($currencies[$variant->currency_id])) { - return ExtenderFacade::execute(__METHOD__, $variant, func_get_args()); - } - $variantCurrency = $currencies[$variant->currency_id]; - if (!empty($variant->currency_id) && $variantCurrency->rate_from != $variantCurrency->rate_to) { - $variant->price = round($variant->price * $variantCurrency->rate_to / $variantCurrency->rate_from, 2); - if (!empty($variant->compare_price)) { - $variant->compare_price = round($variant->compare_price * $variantCurrency->rate_to / $variantCurrency->rate_from, 2); - } - } - return ExtenderFacade::execute(__METHOD__, $variant, func_get_args()); - } -} diff --git a/Init/Init.php b/Init/Init.php index ebe8ec4..cd91640 100644 --- a/Init/Init.php +++ b/Init/Init.php @@ -4,6 +4,7 @@ use Okay\Core\Modules\AbstractInit; use Okay\Helpers\MainHelper; +use Okay\Helpers\UserHelper; use Okay\Entities\AuthorsEntity; use Okay\Entities\BlogEntity; use Okay\Entities\BrandsEntity; @@ -25,6 +26,7 @@ use Okay\Modules\Sviat\Redis\Extenders\FeaturesValuesCacheInvalidator; use Okay\Modules\Sviat\Redis\Extenders\ImagesCacheInvalidator; use Okay\Modules\Sviat\Redis\Extenders\ProductCacheInvalidator; +use Okay\Modules\Sviat\Redis\Extenders\ProductRouteWarmer; use Okay\Modules\Sviat\Redis\Extenders\SpecialImagesCacheInvalidator; use Okay\Modules\Sviat\Redis\Extenders\VariantsCacheInvalidator; @@ -46,6 +48,12 @@ public function init() [CacheStatsReporter::class, 'reportStats'] ); + // Останній розширюваний метод перед setDesignDataProcedure(): там будується мовний перемикач. + $this->registerQueueExtension( + [UserHelper::class, 'mergeBrowsedProducts'], + [ProductRouteWarmer::class, 'warmCurrentProduct'] + ); + // Products $this->registerQueueExtension( ['class' => ProductsEntity::class, 'method' => 'update'], diff --git a/Init/module.json b/Init/module.json index e816142..fdac12c 100644 --- a/Init/module.json +++ b/Init/module.json @@ -1,6 +1,6 @@ { "Okay": "4.5.3", - "version": "1.0.11", + "version": "1.0.12", "name": "Redis cache", "description": "Кешування Redis", "vendor": { diff --git a/Init/services.php b/Init/services.php index a2eb573..6267ac3 100644 --- a/Init/services.php +++ b/Init/services.php @@ -2,6 +2,7 @@ namespace Okay\Modules\Sviat\Redis\Init; +use Okay\Core\Config; use Okay\Core\Design; use Okay\Core\EntityFactory; use Okay\Core\FrontTranslations; @@ -32,6 +33,7 @@ use Okay\Modules\Sviat\Redis\Extenders\FeaturesValuesCacheInvalidator; use Okay\Modules\Sviat\Redis\Extenders\ImagesCacheInvalidator; use Okay\Modules\Sviat\Redis\Extenders\ProductCacheInvalidator; +use Okay\Modules\Sviat\Redis\Extenders\ProductRouteWarmer; use Okay\Modules\Sviat\Redis\Extenders\SpecialImagesCacheInvalidator; use Okay\Modules\Sviat\Redis\Extenders\VariantsCacheInvalidator; use Okay\Modules\Sviat\Redis\Helpers\AuthorsHelper; @@ -40,7 +42,6 @@ use Okay\Modules\Sviat\Redis\Helpers\CatalogHelper; use Okay\Modules\Sviat\Redis\Helpers\CategoriesHelper; use Okay\Modules\Sviat\Redis\Helpers\FilterHelper; -use Okay\Modules\Sviat\Redis\Helpers\MoneyHelper as RedisMoneyHelper; use Okay\Modules\Sviat\Redis\Helpers\ProductsHelper; use Okay\Modules\Sviat\Redis\Helpers\RelatedProductsHelper; use Okay\Modules\Sviat\Redis\Services\RedisCacheService; @@ -48,7 +49,12 @@ return [ RedisCacheService::class => [ 'class' => RedisCacheService::class, - 'arguments' => [new SR(Settings::class)], + 'arguments' => [new SR(Settings::class), new SR(Config::class)], + ], + + ProductRouteWarmer::class => [ + 'class' => ProductRouteWarmer::class, + 'arguments' => [new SR(Router::class), new SR(EntityFactory::class)], ], CoreProductsHelper::class => [ @@ -141,15 +147,6 @@ ], ], - MoneyHelper::class => [ - 'class' => RedisMoneyHelper::class, - 'arguments' => [ - new SR(EntityFactory::class), - new SR(Settings::class), - new SR(RedisCacheService::class), - ], - ], - // ----- Invalidators ----- VariantsCacheInvalidator::class => [ 'class' => VariantsCacheInvalidator::class, diff --git a/README.md b/README.md index dc44f1a..848ed80 100644 --- a/README.md +++ b/README.md @@ -24,21 +24,26 @@ - Увімкнення/вимкнення Redis-кешу. - Перевірка підключення до Redis кнопкою «Протестувати підключення». - Перегляд базової статистики (кількість ключів, використана пам’ять). -- Очищення кешу поточної Redis DB кнопкою «Очистити весь кеш Redis». - -### Безпека кешу (опційно) - -- Є поле «Секрет підпису кешу (HMAC)». -- Якщо задати секрет, модуль перевіряє цілісність кеш-даних перед читанням. +- Очищення кешу модуля кнопкою «Очистити кеш цього модуля»: чужі ключі в тій самій Redis DB (сесії, черги) лишаються. ## Вимоги -- PHP 8.5+ +- Перевірено на PHP 8.5 - OkayCMS 4.5.3 (чиста або [форк](https://github.com/devSviat/OkayCMS-Fork)) -- Перевірено на PHP 8.5 — на чистій OkayCMS 4.5.3 і на форку - Встановлений PHP-розширення `redis` (phpredis) - Запущений Redis сервер (локально або на окремому сервері) +### Сумісність + +Модуль 1.0.12: + +| OkayCMS | PHP | Що перевірено | +|---|---|---| +| 4.5.3, чиста | 8.5 | Тести, кешування, інвалідація цін, налаштування в адмінці | +| [Форк](https://github.com/devSviat/OkayCMS-Fork) 1.5.4 | 8.5 | Тести, кешування, інвалідація цін, налаштування в адмінці | + +Перевірено з phpredis 6.3.0 і Redis 7. + ## Встановлення ### Варіант 1: Скачування з GitHub @@ -62,11 +67,41 @@ Після встановлення перейдіть в адмін-панель → Модулі → Знайдіть «Redis cache» → Натисніть «Встановити». +## Де зберігати підключення + +Модуль шукає параметри в такому порядку, перше знайдене значення перемагає: + +1. Змінні оточення `REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, `REDIS_USERNAME`, `REDIS_PASSWORD`, `REDIS_PREFIX`, `REDIS_ENABLED`. Зручно для Docker. +2. Файл `config/config.local.php`. Рекомендовано для звичайного хостингу. +3. Форма в адмін-панелі. Найпростіший варіант, але пароль лежить у таблиці налаштувань. + +Для `config/config.local.php` додайте в кінець файлу: + +```ini +[redis] +redis_enabled = 1 +redis_host = 127.0.0.1 +redis_port = 6379 +redis_db = 0 +redis_password = 'ваш-пароль' +redis_prefix = shop1: +``` + +Потрібні лише ті рядки, які ви хочете закріпити. Пароль беріть в одинарні лапки, щоб спецсимволи читались буквально. Для `redis_enabled` використовуйте `1` або `0`. Файла може не бути: тоді скопіюйте `config/config.local-example.php`, якщо він є, або створіть файл із першим рядком `;`. Цей файл не потрапляє в оновлення магазину. + +**Що це дає:** + +- Пароль не потрапляє в базу, а отже, і в її дампи та резервні копії. +- Менеджер із правом `settings` не може змінити хост і забрати пароль: поля, задані поза адмінкою, у формі лише для читання. Якщо пароль заданий поза адмінкою, хост, порт і користувач теж блокуються. +- Налаштування бази й Redis лежать в одному місці, і перенесення сайту не вимагає правок в адмінці. + +**Швидкість від цього не зміниться.** Магазин і так читає налаштування на кожному запиті, тож різниця між джерелами менша за мікросекунду. Прискорення дає сам Redis. Вибір джерела стосується безпеки й зручності. + ## Налаштування 1. Перейдіть в адмін-панель → Модулі → Redis cache. 2. Увімкніть перемикач «Увімкнути Redis кеш». -3. Заповніть підключення: +3. Заповніть підключення, якщо воно не задане в `config.local.php` чи env: - Host - Port - DB @@ -74,8 +109,7 @@ - Password (якщо потрібна авторизація) 4. За потреби вкажіть: - префікс ключів; - - TTL за замовчуванням; - - HMAC-секрет (необов’язково). + - TTL за замовчуванням. 5. Натисніть «Протестувати підключення». 6. Якщо все добре — натисніть «Зберегти». 7. За потреби налаштуйте TTL для окремих хелперів у нижньому блоці. @@ -83,9 +117,16 @@ ## Важливо - Кеш працює тільки на фронтенді; адмін-запити не кешуються. -- Очищення кешу в модулі очищає **всю поточну Redis DB** (а не лише ключі одного блоку). -- Якщо змінюєте HMAC-секрет, старі ключі краще оновити/очистити. +- Очищення кешу видаляє лише ключі цього модуля (`<префікс>helpers:*`). Магазини зі спільним Redis мають використовувати різні префікси. +- Очищення йде проходами `SCAN`, тож на дуже великій базі воно не миттєве. +- Redis має дозволяти `EVAL`. Якщо його заборонено, кеш працює, але замок перерахунку знімається лише через 60 с. +- Порожнє поле пароля зберігає поточний пароль, а галочка «Видалити збережений пароль» його видаляє. Введений новий пароль має пріоритет над галочкою. - Якщо Redis недоступний, сайт продовжить працювати без кешу. +- На сторінці товару модуль заздалегідь бере маршрут цього товару одним запитом. Без цього ядро читає всю таблицю маршрутів заради мовного перемикача. +- Якщо змінити хост, порт або користувача й лишити поле пароля порожнім, збережений пароль видаляється: він не піде на новий сервер. +- Курси валют модуль не кешує: вони впливають на ціну в кошику, а ядро й так читає їх один раз за запит. +- Значення в кеші підписані HMAC. Ключа в Redis немає: він виводиться з доступу до БД або задається як `REDIS_SIGNING_KEY` чи `redis_signing_key`. Підпис охоплює і ключ кешу, тому значення не можна перенести під інший ключ. Запис у Redis без ключа сприймається як промах. Після оновлення модуля старі записи просто перераховуються. +- Задайте Redis пароль і `maxmemory`: підпис не захищає від читання кешу й від переповнення пам'яті. ## Тести diff --git a/Security/PlainSettingValue.php b/Security/PlainSettingValue.php new file mode 100644 index 0000000..5a023fd --- /dev/null +++ b/Security/PlainSettingValue.php @@ -0,0 +1,28 @@ + true); + $decoded = unserialize($value, ['allowed_classes' => false]); + restore_error_handler(); + + return $decoded === false && $value !== serialize(false); + } +} diff --git a/Security/RequestOrigin.php b/Security/RequestOrigin.php new file mode 100644 index 0000000..0ea8cba --- /dev/null +++ b/Security/RequestOrigin.php @@ -0,0 +1,88 @@ + 80, 'https' => 443]; + + public static function isFromThisSite(): bool + { + $expected = self::normalize(Request::getDomainWithProtocol()); + if ($expected === null) { + return false; + } + + $origin = $_SERVER['HTTP_ORIGIN'] ?? null; + $referer = $_SERVER['HTTP_REFERER'] ?? null; + + // Origin виграє: браузер ставить його сам, а Referer ріжуть проксі + // й розширення приватності. Другий кандидат — лише коли першого немає. + foreach ([$origin, $referer] as $candidate) { + if (!is_string($candidate) || $candidate === '') { + continue; + } + + // Пісочниця в iframe і частина редиректів шлють рядок "null". + // Це не наш origin, і запасний варіант тут уже не рятує. + if (strtolower($candidate) === 'null') { + return false; + } + + return self::normalize($candidate) === $expected; + } + + // Жодного доказу походження — жодного проходу. + return false; + } + + /** + * @return string|null scheme://host[:port], або null, якщо розібрати не вдалось + */ + private static function normalize(string $url): ?string + { + if ($url === '') { + return null; + } + + $parsed = @parse_url($url); + if ($parsed === false || empty($parsed['scheme']) || empty($parsed['host'])) { + return null; + } + + $scheme = strtolower($parsed['scheme']); + if (!isset(self::DEFAULT_PORTS[$scheme])) { + return null; + } + + // Браузер серіалізує Origin як scheme://host[:port] і облікових даних + // туди не кладе. Раз їх не буває в чесному заголовку — не приймаємо. + if (isset($parsed['user']) || isset($parsed['pass'])) { + return null; + } + + $normalized = $scheme . '://' . strtolower($parsed['host']); + + if (isset($parsed['port']) && (int) $parsed['port'] !== self::DEFAULT_PORTS[$scheme]) { + $normalized .= ':' . (int) $parsed['port']; + } + + return $normalized; + } +} diff --git a/Services/CacheTags.php b/Services/CacheTags.php index 6f35c8b..0cfcf84 100644 --- a/Services/CacheTags.php +++ b/Services/CacheTags.php @@ -10,7 +10,6 @@ final class CacheTags public const string CATEGORIES = 'cver:global'; public const string BRANDS = 'bver:global'; public const string AUTHORS_BLOG = 'aver:global'; - public const string MONEY = 'mver:global'; public static function product(int $productId): string { diff --git a/Services/RedisCacheService.php b/Services/RedisCacheService.php index 04e0242..7db510e 100644 --- a/Services/RedisCacheService.php +++ b/Services/RedisCacheService.php @@ -2,13 +2,22 @@ namespace Okay\Modules\Sviat\Redis\Services; +use Okay\Core\Config; use Okay\Core\Settings; class RedisCacheService { private const string VERSION_KEY_PREFIX = 'helpers:ver:'; + /** + * Позначка підписаного значення. Значення йдуть у ціну й HTML вітрини, тож + * доступ на запис до Redis не має ставати можливістю їх підмінити. + */ + private const string SIGNATURE_MARK = 'sig2:'; + private const int SIGNATURE_LENGTH = 64; + private Settings $settings; + private ?Config $config; private $client = null; private bool $initialized = false; private ?string $lastError = null; @@ -40,6 +49,9 @@ class RedisCacheService /** @var array ключі, перерахунок яких уже заплановано в цьому запиті */ private array $refreshing = []; + /** @var array токени власника замків: протухлий замок не знімає старий власник */ + private array $refreshLockTokens = []; + /** Вікно схлопування повторних bump одного тега, секунди. */ private const float BUMP_COLLAPSE_WINDOW = 1.0; @@ -74,6 +86,8 @@ class RedisCacheService private bool $breakerSuppressed = false; private bool $replayingBumps = false; private bool $stateDirResolved = false; + private bool $signingKeyResolved = false; + private ?string $signingKeyMemo = null; private ?string $stateDirMemo = null; private int $statHits = 0; @@ -84,34 +98,47 @@ class RedisCacheService private static ?bool $authSupportsTwoArgs = null; - public function __construct(Settings $settings) + /** Поля підключення і суфікси REDIS_*: у config.local.php це redis_host тощо. */ + private const array CONNECTION_FIELDS = [ + 'enabled' => 'ENABLED', + 'host' => 'HOST', + 'port' => 'PORT', + 'db' => 'DB', + 'username' => 'USERNAME', + 'password' => 'PASSWORD', + 'prefix' => 'PREFIX', + ]; + + public function __construct(Settings $settings, ?Config $config = null) { $this->settings = $settings; + $this->config = $config; } /** - * Env має пріоритет над налаштуваннями в БД: інакше зміна REDIS_PASSWORD - * у .env лишає сайт мовчки без кешу, поки хтось не відкриє адмінку. + * Пріоритет: env, потім config.local.php, потім налаштування в БД. Інакше + * зміна REDIS_PASSWORD у .env лишає сайт мовчки без кешу, поки хтось не + * відкриє адмінку. */ private function loadConfig(): array { - $password = self::env('REDIS_PASSWORD') + $password = $this->fixedValue('PASSWORD') ?? trim((string) ($this->settings->get('sviat__redis__password') ?? '')); - $username = self::env('REDIS_USERNAME') + $username = $this->fixedValue('USERNAME') ?? trim((string) ($this->settings->get('sviat__redis__username') ?? '')); - $enabledEnv = self::env('REDIS_ENABLED'); + $enabledEnv = $this->fixedValue('ENABLED'); return [ 'enabled' => $enabledEnv !== null ? filter_var($enabledEnv, FILTER_VALIDATE_BOOLEAN) : (bool) $this->settings->get('sviat__redis__enabled'), - 'host' => self::env('REDIS_HOST') ?: ($this->settings->get('sviat__redis__host') ?: '127.0.0.1'), - 'port' => (int) (self::env('REDIS_PORT') ?: ($this->settings->get('sviat__redis__port') ?: 6379)), - 'db' => (int) (self::env('REDIS_DB') ?? ($this->settings->get('sviat__redis__db') ?: 0)), + 'host' => $this->fixedValue('HOST') ?: ($this->settings->get('sviat__redis__host') ?: '127.0.0.1'), + 'port' => (int) ($this->fixedValue('PORT') ?: ($this->settings->get('sviat__redis__port') ?: 6379)), + 'db' => (int) ($this->fixedValue('DB') ?? ($this->settings->get('sviat__redis__db') ?: 0)), 'username' => $username !== '' ? $username : null, 'auth' => $password !== '' ? $password : null, - 'prefix' => self::env('REDIS_PREFIX') ?: ($this->settings->get('sviat__redis__prefix') ?: 'okay:'), + 'prefix' => $this->fixedValue('PREFIX') ?: ($this->settings->get('sviat__redis__prefix') ?: 'okay:'), 'ttl' => (int) ($this->settings->get('sviat__redis__default_ttl') ?: 600), ]; } @@ -129,6 +156,68 @@ private static function env(string $name): ?string return $value !== '' ? $value : null; } + /** Значення поза адмінкою: env або config.local.php. */ + private function fixedValue(string $name): ?string + { + return self::env('REDIS_' . $name) ?? $this->configValue($name); + } + + private function configValue(string $name): ?string + { + if ($this->config === null) { + return null; + } + $value = $this->config->get('redis_' . strtolower($name)); + if ($value === null) { + return null; + } + $value = trim((string) $value); + + return $value !== '' ? $value : null; + } + + /** + * Поля, які адмінка не може змінити. + * + * Пароль поза адмінкою закриває і хост, порт та користувача: інакше менеджер + * скерував би цей пароль на свій сервер. + * + * @return array поле => 'env' або 'config' + */ + public function lockedConnectionFields(): array + { + $locked = []; + foreach (self::CONNECTION_FIELDS as $field => $name) { + if (self::env('REDIS_' . $name) !== null) { + $locked[$field] = 'env'; + } elseif ($this->configValue($name) !== null) { + $locked[$field] = 'config'; + } + } + if (isset($locked['password'])) { + foreach (['host', 'port', 'username'] as $field) { + $locked[$field] ??= $locked['password']; + } + } + + return $locked; + } + + /** @return array{enabled: bool, host: string, port: int, db: int, username: string, prefix: string} */ + public function connectionView(): array + { + $config = $this->loadConfig(); + + return [ + 'enabled' => (bool) $config['enabled'], + 'host' => (string) $config['host'], + 'port' => (int) $config['port'], + 'db' => (int) $config['db'], + 'username' => (string) ($config['username'] ?? ''), + 'prefix' => (string) $config['prefix'], + ]; + } + public function isEnabled(): bool { return $this->loadConfig()['enabled'] && class_exists('\\Redis'); @@ -383,24 +472,39 @@ public function testConnection(bool $allowWhenDisabled = false): bool } } + /** + * Видаляє лише ключі модуля: FLUSHDB знищив би сесії й черги інших сервісів + * у тій самій логічній DB. Значення й версії тегів лежать під helpers:. + */ public function flushAll(): bool { if (!$this->isEnabled()) { return false; } + // Без OPT_PREFIX: SCAN порівнює фізичні імена, а DEL інакше додав би префікс удруге. $client = $this->connectBare(false); if (!$client) { return false; } try { - $client->flushDB(); + // Екранування: «*» у префіксі зачепив би ключі сусіднього магазину. + $pattern = addcslashes((string) $this->loadConfig()['prefix'], '\\*?[]') . 'helpers:*'; + /** @var int|string|null $cursor */ + $cursor = null; + do { + $keys = $client->scan($cursor, $pattern, 500); + if (is_array($keys) && $keys !== []) { + $client->del(...$keys); + } + } while ((int) $cursor !== 0); + $this->versionMemo = []; $this->getMemo = []; - + $this->refreshLockTokens = []; + $this->refreshing = []; return true; } catch (\Throwable $e) { $this->lastError = $e->getMessage(); - return false; } finally { try { $client->close(); } catch (\Throwable) {} @@ -922,13 +1026,22 @@ private function refreshLockKey(string $key): string private function releaseRefreshLock(string $key): void { + $token = $this->refreshLockTokens[$key] ?? null; + unset($this->refreshLockTokens[$key]); + if ($token === null) { + return; + } $client = $this->initClient(); if (!$client) { return; } try { - $client->del($this->refreshLockKey($key)); + // Атомарно: воркер, чий замок протух, не зніме замок наступника. + // OPT_PREFIX phpredis додає і до KEYS в eval(). + $lua = 'if redis.call("GET", KEYS[1]) == ARGV[1] then ' + . 'return redis.call("DEL", KEYS[1]) else return 0 end'; + $client->eval($lua, [$this->refreshLockKey($key), $token], 1); } catch (\Throwable $e) { // Замок і сам протухне через SWR_LOCK_TTL. $this->lastError = $e->getMessage(); @@ -944,7 +1057,12 @@ private function acquireRefreshLock(string $key): bool } try { - return (bool) $client->set($this->refreshLockKey($key), '1', ['nx', 'ex' => self::SWR_LOCK_TTL]); + $token = bin2hex(random_bytes(16)); + if (!(bool) $client->set($this->refreshLockKey($key), $token, ['nx', 'ex' => self::SWR_LOCK_TTL])) { + return false; + } + $this->refreshLockTokens[$key] = $token; + return true; } catch (\Throwable $e) { $this->lastError = $e->getMessage(); $this->dropClient(); @@ -974,7 +1092,7 @@ public function get(string $key) $this->statMisses++; return null; } - $value = $this->safeUnserialize((string) $data); + $value = $this->decode($key, (string) $data); if ($value === null) { $this->getMemo[$key] = [false, null]; $this->statMisses++; @@ -1035,7 +1153,7 @@ public function mGet(array $keys): array $this->statMisses++; continue; } - $value = $this->safeUnserialize((string) $data); + $value = $this->decode($k, (string) $data); if ($value === null) { $this->getMemo[$k] = [false, null]; $result[$k] = null; @@ -1058,6 +1176,65 @@ public function mGet(array $keys): array return $result; } + /** Ключ ніколи не лежить у Redis: env, конфіг або похідний від доступу до БД. */ + private function signingKey(): ?string + { + if ($this->signingKeyResolved) { + return $this->signingKeyMemo; + } + $this->signingKeyResolved = true; + + $explicit = self::env('REDIS_SIGNING_KEY') ?? $this->configValue('SIGNING_KEY'); + if ($explicit !== null) { + return $this->signingKeyMemo = $explicit; + } + if ($this->config === null) { + return null; + } + + // Спільне для php-fpm і планувальника, на відміну від salt, що залежить від stat() файлу. + return $this->signingKeyMemo = hash('sha256', implode('|', [ + 'sviat-redis-cache', + (string) $this->config->get('db_server'), + (string) $this->config->get('db_user'), + (string) $this->config->get('db_password'), + (string) $this->config->get('db_name'), + ])); + } + + /** Ключ кешу входить у підпис: інакше чинне значення можна було б скопіювати під чужий ключ. */ + private function seal(string $cacheKey, string $data): string + { + $key = $this->signingKey(); + + return $key === null + ? $data + : self::SIGNATURE_MARK . hash_hmac('sha256', $cacheKey . "\0" . $data, $key) . $data; + } + + /** @return mixed значення або null, якщо підпису немає чи він не збігся */ + private function decode(string $cacheKey, string $raw) + { + $key = $this->signingKey(); + if ($key === null) { + return $this->safeUnserialize($raw); + } + + $markLength = strlen(self::SIGNATURE_MARK); + if (strncmp($raw, self::SIGNATURE_MARK, $markLength) !== 0) { + return null; + } + $signature = substr($raw, $markLength, self::SIGNATURE_LENGTH); + $data = substr($raw, $markLength + self::SIGNATURE_LENGTH); + if (!hash_equals(hash_hmac('sha256', $cacheKey . "\0" . $data, $key), $signature)) { + $this->lastError = 'Cache signature mismatch'; + + return null; + } + + return $this->safeUnserialize($data); + } + private function safeUnserialize(string $data) { set_error_handler(function ($severity, $message) { @@ -1087,7 +1264,7 @@ public function set(string $key, $value, ?int $ttl = null): void $ttl = max(self::MIN_TTL, (int) $config['ttl']); } try { - $data = serialize($value); + $data = $this->seal($key, serialize($value)); $started = microtime(true); $client->setex($key, $ttl, $data); $this->statSeconds += microtime(true) - $started; diff --git a/Services/RedisConnectionForm.php b/Services/RedisConnectionForm.php new file mode 100644 index 0000000..aa4675e --- /dev/null +++ b/Services/RedisConnectionForm.php @@ -0,0 +1,119 @@ + $post host, port, db, username, password, clear_password, prefix + * @param array $stored збережені значення тих самих полів + * @param array $locked поле => джерело + * @return array{values: array, errors: list, passwordDropped: bool} + */ + public static function apply(array $post, array $stored, array $locked = []): array + { + $values = []; + $errors = []; + + $host = trim((string) ($post['host'] ?? '')); + if (!isset($locked['host'])) { + if (self::isValidHost($host)) { + $values['host'] = $host; + } else { + $errors[] = 'host'; + } + } + + $port = (int) ($post['port'] ?? 0); + if (!isset($locked['port'])) { + if ($port >= 1 && $port <= 65535) { + $values['port'] = $port; + } else { + $errors[] = 'port'; + } + } + + if (!isset($locked['db'])) { + $values['db'] = max(0, (int) ($post['db'] ?? 0)); + } + + $username = trim((string) ($post['username'] ?? '')); + if (!isset($locked['username'])) { + if (PlainSettingValue::isPlain($username)) { + $values['username'] = $username; + } else { + $errors[] = 'username'; + } + } + + $prefix = (string) ($post['prefix'] ?? ''); + if (!isset($locked['prefix'])) { + if (self::isValidPrefix($prefix)) { + $values['prefix'] = $prefix; + } else { + $errors[] = 'prefix'; + } + } + + $passwordDropped = false; + if (!isset($locked['password'])) { + $password = (string) ($post['password'] ?? ''); + $hasStored = (string) ($stored['password'] ?? '') !== ''; + + if ($password !== '') { + if (PlainSettingValue::isPlain($password)) { + $values['password'] = $password; + } else { + $errors[] = 'password'; + } + } elseif ((int) ($post['clear_password'] ?? 0) === 1) { + $values['password'] = ''; + } elseif ($hasStored && self::targetChanged($values, $stored)) { + // Збережений пароль належить старому серверу: на новий він пішов би відкритим AUTH. + $values['password'] = ''; + $passwordDropped = true; + } + } + + return ['values' => $values, 'errors' => $errors, 'passwordDropped' => $passwordDropped]; + } + + /** Ім'я, IPv4, IPv6 у дужках, tls://ім'я або абсолютний шлях unix-сокета. */ + public static function isValidHost(string $host): bool + { + if ($host === '' || strlen($host) > 255) { + return false; + } + + return preg_match('#^(?:(?:tls://)?[A-Za-z0-9][A-Za-z0-9.\-]*|\[[0-9A-Fa-f:]+\]|/[A-Za-z0-9._/\-]+)$#', $host) === 1; + } + + public static function isValidPrefix(string $prefix): bool + { + return $prefix !== '' + && strlen($prefix) <= self::MAX_PREFIX_LENGTH + && preg_match('/\s/', $prefix) !== 1 + && PlainSettingValue::isPlain($prefix); + } + + private static function targetChanged(array $values, array $stored): bool + { + foreach (['host', 'port', 'username'] as $field) { + if (array_key_exists($field, $values) && (string) $values[$field] !== (string) ($stored[$field] ?? '')) { + return true; + } + } + + return false; + } +} diff --git a/tests/BreakerAndPendingBumpsTest.php b/tests/BreakerAndPendingBumpsTest.php index 76db8d1..1f19391 100644 --- a/tests/BreakerAndPendingBumpsTest.php +++ b/tests/BreakerAndPendingBumpsTest.php @@ -270,7 +270,7 @@ public function testFailedWipeKeepsTheOverflowMark(): void if (!class_exists('\\Redis')) { $this->markTestSkipped('phpredis not installed'); } file_put_contents($this->bumpsFile(), "*\n"); $client = new FakeRedisClient(); - $client->failFlush = true; + $client->failScanTimes = 1; $service = $this->makeService($client); $service->get('anything'); diff --git a/tests/CacheInvalidatorsContractTest.php b/tests/CacheInvalidatorsContractTest.php new file mode 100644 index 0000000..5b91083 --- /dev/null +++ b/tests/CacheInvalidatorsContractTest.php @@ -0,0 +1,135 @@ +}> */ + public static function events(): array + { + $rows = [ + [CategoryCacheInvalidator::class, 'onCategory', [CacheTags::CATEGORIES, CacheTags::PRODUCTS_LIST]], + [BrandCacheInvalidator::class, 'onBrand', [CacheTags::BRANDS, CacheTags::PRODUCTS_LIST]], + [BlogCacheInvalidator::class, 'onBlog', [CacheTags::AUTHORS_BLOG]], + [AuthorCacheInvalidator::class, 'onAuthor', [CacheTags::AUTHORS_BLOG]], + [CurrencyCacheInvalidator::class, 'onCurrency', [CacheTags::PRODUCTS_ALL]], + [FeaturesCacheInvalidator::class, 'onFeature', self::ALL_AND_LIST], + [FeaturesValuesCacheInvalidator::class, 'onFeatureValue', self::ALL_AND_LIST], + [SpecialImagesCacheInvalidator::class, 'onSpecialImage', [CacheTags::PRODUCTS_ALL]], + ]; + + $cases = []; + foreach ($rows as [$class, $prefix, $tags]) { + foreach (['Add', 'Update', 'Delete'] as $event) { + $cases[$prefix . $event] = [$class, $prefix . $event, $event, $tags]; + } + } + + return $cases; + } + + /** @param list $expected */ + #[DataProvider('events')] + public function testSuccessfulEventBumpsExactTags(string $class, string $method, string $event, array $expected): void + { + $stub = new StubRedisCacheService(); + + new $class($stub)->$method(...self::successArgs($event)); + + self::assertSame($expected, $stub->bumps); + } + + /** @param list $tags */ + #[DataProvider('events')] + public function testFailedEventBumpsNothing(string $class, string $method, string $event, array $tags): void + { + $stub = new StubRedisCacheService(); + + new $class($stub)->$method(...self::failureArgs($event)); + + self::assertSame([], $stub->bumps, 'запис не відбувся — кеш лишається дійсним'); + } + + public function testProductUpdateBumpsEachProductAndList(): void + { + $stub = new StubRedisCacheService(); + + new ProductCacheInvalidator($stub)->onProductUpdate(true, [7, '9'], (object) []); + + self::assertSame([CacheTags::product(7), CacheTags::product(9), CacheTags::PRODUCTS_LIST], $stub->bumps); + } + + public function testProductUpdateAcceptsSingleIdAndIgnoresInvalid(): void + { + $stub = new StubRedisCacheService(); + + new ProductCacheInvalidator($stub)->onProductUpdate(true, 7, (object) []); + self::assertSame([CacheTags::product(7), CacheTags::PRODUCTS_LIST], $stub->bumps); + + $stub = new StubRedisCacheService(); + new ProductCacheInvalidator($stub)->onProductUpdate(true, [0, -1], (object) []); + self::assertSame([CacheTags::PRODUCTS_LIST], $stub->bumps); + } + + public function testProductAddTouchesOnlyLists(): void + { + $stub = new StubRedisCacheService(); + + new ProductCacheInvalidator($stub)->onProductAdd(5, (object) []); + + self::assertSame([CacheTags::PRODUCTS_LIST], $stub->bumps); + } + + /** Після видалення id товарів уже невідомі кешу, тож скидається все. */ + public function testProductDeleteBumpsAllAndList(): void + { + $stub = new StubRedisCacheService(); + + new ProductCacheInvalidator($stub)->onProductDelete(true, [7]); + + self::assertSame(self::ALL_AND_LIST, $stub->bumps); + } + + public function testFailedProductEventsBumpNothing(): void + { + $stub = new StubRedisCacheService(); + $invalidator = new ProductCacheInvalidator($stub); + + $invalidator->onProductUpdate(false, [7], (object) []); + $invalidator->onProductAdd(0, (object) []); + $invalidator->onProductDelete(false, [7]); + + self::assertSame([], $stub->bumps); + } + + private static function successArgs(string $event): array + { + return $event === 'Add' ? [5, (object) []] : ($event === 'Update' ? [true, [1], (object) []] : [true, [1]]); + } + + private static function failureArgs(string $event): array + { + return $event === 'Add' ? [0, (object) []] : ($event === 'Update' ? [false, [1], (object) []] : [false, [1]]); + } +} diff --git a/tests/CacheSigningTest.php b/tests/CacheSigningTest.php new file mode 100644 index 0000000..66de592 --- /dev/null +++ b/tests/CacheSigningTest.php @@ -0,0 +1,134 @@ +markTestSkipped('phpredis not installed'); + } + foreach (['REDIS_SIGNING_KEY', 'REDIS_ENABLED'] as $name) { + $this->envBackup[$name] = getenv($name); + putenv($name); + } + } + + protected function tearDown(): void + { + foreach ($this->envBackup as $name => $value) { + putenv($value === false ? $name : "$name=$value"); + } + } + + private function service(FakeRedisClient $client, array $config = ['db_password' => 'secret', 'db_name' => 'shop']): RedisCacheService + { + $settings = $this->createStub(Settings::class); + $settings->method('get')->willReturnCallback(fn (string $k) => ['sviat__redis__enabled' => true, 'sviat__redis__default_ttl' => 600][$k] ?? null); + $configStub = $this->createStub(Config::class); + $configStub->method('get')->willReturnCallback(fn (string $k) => $config[$k] ?? null); + + $service = new RedisCacheService($settings, $configStub); + $r = new \ReflectionClass(RedisCacheService::class); + self::accessible($r->getProperty('client'))->setValue($service, $client); + self::accessible($r->getProperty('initialized'))->setValue($service, true); + + return $service; + } + + public function testValueSurvivesRoundTrip(): void + { + $client = new FakeRedisClient(); + $this->service($client)->set('helpers:k', ['price' => 100]); + + self::assertSame(['price' => 100], $this->service($client)->get('helpers:k')); + self::assertStringStartsWith('sig2:', $client->store['helpers:k']); + } + + public function testTamperedValueIsAMiss(): void + { + $client = new FakeRedisClient(); + $this->service($client)->set('helpers:k', ['price' => 100]); + $client->store['helpers:k'] = str_replace('i:100', 'i:001', $client->store['helpers:k']); + + self::assertNull($this->service($client)->get('helpers:k')); + } + + public function testUnsignedValueWrittenDirectlyIsAMiss(): void + { + $client = new FakeRedisClient(); + $client->store['helpers:k'] = serialize(['price' => 1]); + + $service = $this->service($client); + + self::assertNull($service->get('helpers:k')); + self::assertSame(['helpers:k' => null], $service->mGet(['helpers:k'])); + } + + public function testValueSignedWithAnotherKeyIsAMiss(): void + { + $client = new FakeRedisClient(); + $this->service($client, ['db_password' => 'other'])->set('helpers:k', ['price' => 1]); + + self::assertNull($this->service($client)->get('helpers:k')); + } + + public function testSignedValueCannotBeMovedToAnotherKey(): void + { + $client = new FakeRedisClient(); + $this->service($client)->set('helpers:cheap', ['price' => 1]); + $client->store['helpers:expensive'] = $client->store['helpers:cheap']; + + self::assertNull($this->service($client)->get('helpers:expensive')); + self::assertSame(['helpers:expensive' => null], $this->service($client)->mGet(['helpers:expensive'])); + } + + public function testEnvKeyWins(): void + { + $client = new FakeRedisClient(); + putenv('REDIS_SIGNING_KEY=explicit'); + $this->service($client, ['db_password' => 'a'])->set('helpers:k', 1); + + self::assertSame(1, $this->service($client, ['db_password' => 'b'])->get('helpers:k')); + } + + public function testMGetVerifiesEachValue(): void + { + $client = new FakeRedisClient(); + $this->service($client)->set('helpers:good', 'ok'); + $client->store['helpers:bad'] = 'sig2:' . str_repeat('0', 64) . serialize('evil'); + + $result = $this->service($client)->mGet(['helpers:good', 'helpers:bad']); + + self::assertSame(['helpers:good' => 'ok', 'helpers:bad' => null], $result); + } + + public function testKeyIsNeverStoredInRedis(): void + { + $client = new FakeRedisClient(); + $this->service($client)->set('helpers:k', 'x'); + + self::assertStringNotContainsString('secret', implode('', array_map('strval', $client->store))); + } + + public function testServiceReceivesConfigInProduction(): void + { + $services = (string) file_get_contents(__DIR__ . '/../../../../Okay/Modules/Sviat/Redis/Init/services.php'); + + self::assertStringContainsString('[new SR(Settings::class), new SR(Config::class)]', $services); + } +} diff --git a/tests/CacheStatsReporterTest.php b/tests/CacheStatsReporterTest.php new file mode 100644 index 0000000..3f7af29 --- /dev/null +++ b/tests/CacheStatsReporterTest.php @@ -0,0 +1,61 @@ +requestStats; } + }; + + $headers = []; + $response = $this->createStub(Response::class); + $response->method('addHeader')->willReturnCallback(function ($header) use (&$headers, $response) { + $headers[] = $header; + return $response; + }); + $config = $this->createStub(Config::class); + $config->method('__get')->willReturn(null); + $config->method('get')->willReturn($debug); + + new CacheStatsReporter($redis, $response, $config, $this->createStub(LoggerInterface::class))->reportStats(); + + return $headers; + } + + private function stats(?string $error = null): array + { + return ['hits' => 3, 'misses' => 1, 'bumps' => 0, 'round_trips' => 2, 'ms' => '1.5', 'error' => $error, 'suppressed' => false]; + } + + public function testNoHeaderOutsideDebug(): void + { + self::assertSame([], $this->report(false, $this->stats())); + } + + public function testHeaderInDebugCarriesCounters(): void + { + self::assertSame(['X-Redis-Prerender: h=3 m=1 bumps=0 rt=2 ms=1.5'], $this->report(true, $this->stats())); + } + + /** Текст помилки йде від сервера Redis, а перенос рядка зробив би з нього новий заголовок. */ + public function testErrorTextCannotInjectHeader(): void + { + $headers = $this->report(true, $this->stats("boom\r\nSet-Cookie: x=1")); + + self::assertStringNotContainsString("\r", $headers[0]); + self::assertStringNotContainsString("\n", $headers[0]); + self::assertStringEndsWith('err=boom Set-Cookie: x=1', $headers[0]); + } +} diff --git a/tests/ConnectionSourcesTest.php b/tests/ConnectionSourcesTest.php new file mode 100644 index 0000000..eb8e1af --- /dev/null +++ b/tests/ConnectionSourcesTest.php @@ -0,0 +1,227 @@ +envBackup[$name] = getenv($name); + putenv($name); + unset($_ENV[$name], $_SERVER[$name]); + } + } + + protected function tearDown(): void + { + foreach ($this->envBackup as $name => $value) { + putenv($value === false ? $name : "$name=$value"); + } + } + + private function service(array $config = [], array $settings = []): RedisCacheService + { + $settingsStub = $this->createStub(Settings::class); + $settingsStub->method('get')->willReturnCallback(fn (string $k) => $settings[$k] ?? null); + $configStub = $this->createStub(Config::class); + $configStub->method('get')->willReturnCallback(fn (string $k) => $config[$k] ?? null); + + return new RedisCacheService($settingsStub, $configStub); + } + + public function testAdminSettingsAreUsedWhenNothingElseIsSet(): void + { + $service = $this->service([], ['sviat__redis__host' => 'admin.host', 'sviat__redis__port' => 6390]); + + self::assertSame('admin.host', $service->connectionView()['host']); + self::assertSame(6390, $service->connectionView()['port']); + self::assertSame([], $service->lockedConnectionFields()); + } + + public function testConfigFileBeatsAdminSettings(): void + { + $service = $this->service( + ['redis_host' => 'config.host', 'redis_port' => '6381', 'redis_db' => '0', 'redis_prefix' => 'shop:'], + ['sviat__redis__host' => 'admin.host', 'sviat__redis__port' => 6390, 'sviat__redis__db' => 3] + ); + + $view = $service->connectionView(); + + self::assertSame('config.host', $view['host']); + self::assertSame(6381, $view['port']); + self::assertSame(0, $view['db'], 'нуль у конфігу не губиться на користь адмінки'); + self::assertSame('shop:', $view['prefix']); + } + + public function testEnvBeatsConfigFile(): void + { + putenv('REDIS_HOST=env.host'); + + $service = $this->service(['redis_host' => 'config.host']); + + self::assertSame('env.host', $service->connectionView()['host']); + self::assertSame(['host' => 'env'], $service->lockedConnectionFields()); + } + + public function testEmptyConfigValueDoesNotLock(): void + { + self::assertSame([], $this->service(['redis_host' => ' '])->lockedConnectionFields()); + } + + public function testEnabledZeroInConfigDisablesCache(): void + { + $service = $this->service(['redis_enabled' => '0'], ['sviat__redis__enabled' => 1]); + + self::assertFalse($service->connectionView()['enabled']); + } + + /** Пароль, заданий поза адмінкою, не має піти на хост, який обрав менеджер. */ + public function testFixedPasswordLocksItsTarget(): void + { + $locked = $this->service(['redis_password' => 'секрет'])->lockedConnectionFields(); + + ksort($locked); + self::assertSame(['host' => 'config', 'password' => 'config', 'port' => 'config', 'username' => 'config'], $locked); + } + + public function testViewNeverCarriesThePassword(): void + { + $view = $this->service(['redis_password' => 'секрет'])->connectionView(); + + self::assertArrayNotHasKey('auth', $view); + self::assertNotContains('секрет', $view); + } + + private function post(array $overrides = []): array + { + return $overrides + ['host' => 'redis.local', 'port' => '6379', 'db' => '0', 'username' => '', 'password' => '', 'prefix' => 'okay:']; + } + + private function stored(): array + { + return ['host' => 'redis.local', 'port' => '6379', 'username' => '', 'password' => 'секрет']; + } + + public function testChangingHostDropsStoredPassword(): void + { + $result = RedisConnectionForm::apply($this->post(['host' => 'attacker.example']), $this->stored()); + + self::assertSame('', $result['values']['password']); + self::assertTrue($result['passwordDropped']); + } + + #[DataProvider('targetChanges')] + public function testAnyTargetChangeDropsPassword(array $change): void + { + self::assertTrue(RedisConnectionForm::apply($this->post($change), $this->stored())['passwordDropped']); + } + + public static function targetChanges(): array + { + return [ + 'port' => [['port' => '6380']], + 'username' => [['username' => 'other']], + ]; + } + + public function testUnchangedTargetKeepsPassword(): void + { + $result = RedisConnectionForm::apply($this->post(), $this->stored()); + + self::assertArrayNotHasKey('password', $result['values']); + self::assertFalse($result['passwordDropped']); + } + + public function testNewPasswordOnNewHostIsAccepted(): void + { + $result = RedisConnectionForm::apply($this->post(['host' => 'new.host', 'password' => 'новий']), $this->stored()); + + self::assertSame('новий', $result['values']['password']); + self::assertFalse($result['passwordDropped']); + } + + public function testLockedFieldsAreNotChanged(): void + { + $result = RedisConnectionForm::apply( + $this->post(['host' => 'attacker.example', 'password' => 'x']), + $this->stored(), + ['host' => 'config', 'password' => 'config'] + ); + + self::assertArrayNotHasKey('host', $result['values']); + self::assertArrayNotHasKey('password', $result['values']); + } + + #[DataProvider('hosts')] + public function testHostValidation(string $host, bool $valid): void + { + self::assertSame($valid, RedisConnectionForm::isValidHost($host)); + } + + public static function hosts(): array + { + return [ + 'name' => ['redis.internal', true], + 'ipv4' => ['127.0.0.1', true], + 'ipv6' => ['[::1]', true], + 'tls' => ['tls://redis.example', true], + 'socket' => ['/var/run/redis/redis.sock', true], + 'empty' => ['', false], + 'http' => ['http://internal/', false], + 'gopher' => ['gopher://x', false], + 'space' => ['a b', false], + 'newline' => ["a\nb", false], + 'serialized' => ['O:8:"stdClass":0:{}', false], + 'traversal' => ['user@host', false], + ]; + } + + #[DataProvider('badPorts')] + public function testPortOutOfRangeIsRefusedAndNotSaved(string $port): void + { + $result = RedisConnectionForm::apply($this->post(['port' => $port]), $this->stored()); + + self::assertContains('port', $result['errors']); + self::assertArrayNotHasKey('port', $result['values']); + } + + public static function badPorts(): array + { + return [['0'], ['-1'], ['65536'], ['abc']]; + } + + public function testSerialisedValuesAreNotSaved(): void + { + $result = RedisConnectionForm::apply( + $this->post(['prefix' => 'O:8:"stdClass":0:{}', 'password' => 'a:0:{}', 'username' => 'b:0;']), + $this->stored() + ); + + self::assertSame(['username', 'prefix', 'password'], $result['errors']); + self::assertArrayNotHasKey('prefix', $result['values']); + self::assertArrayNotHasKey('password', $result['values']); + } + + public function testMoneyHelperIsNotOverridden(): void + { + $services = (string) file_get_contents(__DIR__ . '/../../../../Okay/Modules/Sviat/Redis/Init/services.php'); + + self::assertStringNotContainsString('RedisMoneyHelper', $services, 'курси валют ідуть у ціну кошика, у кеші їм не місце'); + } +} diff --git a/tests/FakeRedisClient.php b/tests/FakeRedisClient.php index 51b4226..d9ae75a 100644 --- a/tests/FakeRedisClient.php +++ b/tests/FakeRedisClient.php @@ -67,20 +67,61 @@ public function incr($key) return $this->store[$key]; } - public function del($key): int + public function del(...$keys): int { - $this->calls[] = ['del', $key]; - if (!array_key_exists($key, $this->store)) { - return 0; + $deleted = 0; + foreach ($keys as $key) { + $this->calls[] = ['del', $key]; + if (array_key_exists($key, $this->foreign)) { + unset($this->foreign[$key]); + $deleted++; + continue; + } + $logical = str_starts_with($key, $this->physicalPrefix) + ? substr($key, strlen($this->physicalPrefix)) + : $key; + if (array_key_exists($logical, $this->store)) { + unset($this->store[$logical], $this->ttls[$logical]); + $deleted++; + } } - unset($this->store[$key], $this->ttls[$key]); - return 1; + return $deleted; + } + + /** store тримає ключі без префікса: так їх бачить клієнт з OPT_PREFIX. SCAN віддає фізичні імена. */ + public string $physicalPrefix = 'okay:'; + + /** Ключі інших сервісів у тій самій DB, із повними іменами. */ + public array $foreign = []; + + public int $scanPageSize = 1000; + public int $failScanTimes = 0; + + public function scan(&$cursor, $pattern = null, $count = 0) + { + $this->calls[] = ['scan', $pattern]; + if ($this->failScanTimes > 0) { + $this->failScanTimes--; + throw new \RuntimeException('scan failed'); + } + $physical = array_merge( + array_map(fn ($k) => $this->physicalPrefix . $k, array_keys($this->store)), + array_keys($this->foreign) + ); + $matched = array_values(array_filter($physical, fn ($k) => fnmatch((string) $pattern, $k))); + $page = array_slice($matched, 0, $this->scanPageSize); + $cursor = count($matched) > count($page) ? 1 : 0; + return $page; } - public bool $failFlush = false; - public function flushDB(): bool + public function eval($script, $args = [], $numKeys = 0) { - if ($this->failFlush) { throw new \RuntimeException('flush failed'); } - $this->store = []; $this->ttls = []; return true; + $this->calls[] = ['eval', $args]; + [$key, $token] = $args; + if (($this->store[$key] ?? null) !== $token) { + return 0; + } + unset($this->store[$key]); + return 1; } } diff --git a/tests/FlushScopeAndLockOwnershipTest.php b/tests/FlushScopeAndLockOwnershipTest.php new file mode 100644 index 0000000..da8f52b --- /dev/null +++ b/tests/FlushScopeAndLockOwnershipTest.php @@ -0,0 +1,207 @@ +createStub(Settings::class); + $settings->method('get')->willReturnCallback(fn (string $k) => [ + 'sviat__redis__enabled' => true, + 'sviat__redis__host' => '127.0.0.1', + 'sviat__redis__port' => 6379, + 'sviat__redis__db' => 0, + 'sviat__redis__prefix' => $prefix, + 'sviat__redis__default_ttl' => 600, + ][$k] ?? null); + + $service = new class ($settings, $client) extends RedisCacheService { + public array $deferred = []; + + public function __construct(Settings $settings, private FakeRedisClient $bare) + { + parent::__construct($settings); + } + + protected function connectBare(bool $applyKeyPrefix = true, bool $persistent = false) + { + return $this->bare; + } + + protected function defer(callable $task): void + { + $this->deferred[] = $task; + } + }; + + $r = new \ReflectionClass(RedisCacheService::class); + self::accessible($r->getProperty('client'))->setValue($service, $client); + self::accessible($r->getProperty('initialized'))->setValue($service, true); + + return $service; + } + + private function lockKey(FakeRedisClient $client): string + { + $locks = array_values(array_filter(array_keys($client->store), fn ($k) => str_ends_with((string) $k, ':lock'))); + self::assertCount(1, $locks, 'замок узято'); + + return $locks[0]; + } + + private function staleService(FakeRedisClient $client): RedisCacheService + { + // Перший виклик кладе конверт, другий після протухання бере замок. + $service = $this->makeService($client); + $service->remember('t', [], [], fn () => 'старе', 60); + foreach ($client->store as $key => $value) { + $envelope = unserialize($value); + $envelope['f'] = 1.0; + $client->store[$key] = serialize($envelope); + } + + return $this->makeService($client); + } + + public function testFlushDeletesOnlyModuleKeys(): void + { + $this->requirePhpRedis(); + $client = new FakeRedisClient(); + $client->store['helpers:products:abc'] = 'значення'; + $client->store['helpers:ver:pver:1'] = 3; + $client->foreign['PHPREDIS_SESSION:abc'] = 'сесія'; + $client->foreign['other-app:helpers:x'] = 'чужий кеш'; + $client->foreign['okay:queue:jobs'] = 'черга під тим самим префіксом'; + + self::assertTrue($this->makeService($client)->flushAll()); + + self::assertSame([], $client->store); + self::assertCount(3, $client->foreign); + } + + public function testFlushWalksAllScanPages(): void + { + $this->requirePhpRedis(); + $client = new FakeRedisClient(); + $client->scanPageSize = 2; + for ($i = 0; $i < 7; $i++) { + $client->store["helpers:k$i"] = 'v'; + } + + self::assertTrue($this->makeService($client)->flushAll()); + + self::assertSame([], $client->store); + } + + /** Символи glob у префіксі інакше розширили б очищення на чужі ключі. */ + public function testGlobCharactersInPrefixAreLiteral(): void + { + $this->requirePhpRedis(); + $client = new FakeRedisClient(); + $client->physicalPrefix = 'shop*:'; + $client->store['helpers:own'] = 'своє'; + $client->foreign['shop2:helpers:neighbour'] = 'сусідній магазин'; + + self::assertTrue($this->makeService($client, 'shop*:')->flushAll()); + + self::assertSame([], $client->store); + self::assertArrayHasKey('shop2:helpers:neighbour', $client->foreign); + } + + public function testFailedScanIsReportedNotSilent(): void + { + $this->requirePhpRedis(); + $client = new FakeRedisClient(); + $client->failScanTimes = 1; + $service = $this->makeService($client); + + self::assertFalse($service->flushAll()); + self::assertSame('scan failed', $service->getLastError()); + } + + public function testRefreshReleasesItsOwnLockThroughCompareAndDelete(): void + { + $this->requirePhpRedis(); + $client = new FakeRedisClient(); + $service = $this->staleService($client); + $service->remember('t', [], [], fn () => 'нове', 60); + $lock = $this->lockKey($client); + + ($service->deferred[0])(); + + self::assertArrayNotHasKey($lock, $client->store); + self::assertSame(['eval', [$lock, $this->tokenFrom($client)]], $this->lastCall($client, 'eval')); + } + + public function testExpiredOwnerDoesNotReleaseReplacementLock(): void + { + $this->requirePhpRedis(); + $client = new FakeRedisClient(); + $service = $this->staleService($client); + $service->remember('t', [], [], fn () => 'нове', 60); + $lock = $this->lockKey($client); + + // Замок протух, поки перерахунок тривав, і його взяв інший воркер. + $client->store[$lock] = 'токен-іншого-воркера'; + ($service->deferred[0])(); + + self::assertSame('токен-іншого-воркера', $client->store[$lock]); + } + + public function testLockTokensDifferBetweenAcquisitions(): void + { + $this->requirePhpRedis(); + $tokens = []; + foreach ([1, 2] as $ignored) { + $client = new FakeRedisClient(); + $service = $this->staleService($client); + $service->remember('t', [], [], fn () => 'нове', 60); + $tokens[] = $client->store[$this->lockKey($client)]; + } + + self::assertNotSame($tokens[0], $tokens[1]); + self::assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $tokens[0]); + } + + private function requirePhpRedis(): void + { + if (!class_exists('\\Redis')) { + $this->markTestSkipped('phpredis not installed'); + } + } + + private function lastCall(FakeRedisClient $client, string $name): ?array + { + foreach (array_reverse($client->calls) as $call) { + if ($call[0] === $name) { + return $call; + } + } + + return null; + } + + private function tokenFrom(FakeRedisClient $client): string + { + foreach ($client->calls as $call) { + if ($call[0] === 'set' && str_ends_with((string) $call[1], ':lock')) { + return $call[2]; + } + } + self::fail('замок не встановлювали'); + } +} diff --git a/tests/HelpersCacheTest.php b/tests/HelpersCacheTest.php new file mode 100644 index 0000000..ced6e94 --- /dev/null +++ b/tests/HelpersCacheTest.php @@ -0,0 +1,167 @@ +newInstanceWithoutConstructor(); + self::accessible(new \ReflectionProperty($class, 'redis'))->setValue($helper, $redis); + foreach ($parentProps as $name => [$owner, $value]) { + self::accessible(new \ReflectionProperty($owner, $name))->setValue($helper, $value); + } + + return $helper; + } + + private function factoryReturning(array $rows): EntityFactory + { + $entity = new class ($rows) { + public function __construct(private array $rows) {} + public function __call($name, $args) { return $name === 'find' ? $this->rows : $this; } + }; + $factory = $this->createStub(EntityFactory::class); + $factory->method('get')->willReturn($entity); + + return $factory; + } + + /** @return list}> */ + private function listHelpers(): array + { + return [ + [BrandsHelper::class, 'getList', 'brands_get_list', [CacheTags::BRANDS]], + [AuthorsHelper::class, 'getList', 'authors_get_list', [CacheTags::AUTHORS_BLOG]], + [BlogHelper::class, 'getList', 'blog_get_list', [CacheTags::AUTHORS_BLOG]], + ]; + } + + public function testListHelpersServeHitWithRightKeyAndTags(): void + { + foreach ($this->listHelpers() as [$class, $method, $name, $tags]) { + $redis = new StubRedisCacheService(); + $redis->cachedValue = [3 => (object) ['id' => 3]]; + + $result = $this->build($class, $redis)->$method(['visible' => 1], 'position', []); + + self::assertSame($redis->cachedValue, $result, $class); + self::assertStringStartsWith($name . '|' . implode(',', $tags) . '|', (string) $redis->lastKey, $class); + } + } + + public function testListHelpersSeparateKeysByFilterSortAndFields(): void + { + foreach ($this->listHelpers() as [$class, $method]) { + $keys = []; + foreach ([[['a' => 1], 's', []], [['a' => 2], 's', []], [['a' => 1], 'z', []], [['a' => 1], 's', ['x']]] as $args) { + $redis = new StubRedisCacheService(); + $redis->cachedValue = []; + $this->build($class, $redis)->$method(...$args); + $keys[] = $redis->lastKey; + } + + self::assertCount(4, array_unique($keys), $class); + } + } + + public function testAuthorsMissStoresResultWithConfiguredTtl(): void + { + $redis = new StubRedisCacheService(); + $redis->helperTtls['authors_get_list'] = 120; + $rows = [3 => (object) ['id' => 3]]; + $helper = $this->build(AuthorsHelper::class, $redis, [ + 'entityFactory' => [\Okay\Helpers\AuthorsHelper::class, $this->factoryReturning($rows)], + ]); + + self::assertSame($rows, $helper->getList([], null, [])); + + self::assertCount(1, $redis->stored); + self::assertSame([$rows, 120], array_values($redis->stored)[0]); + } + + public function testDisabledCacheNeverTouchesRedis(): void + { + $redis = new StubRedisCacheService(); + $redis->enabled = false; + $rows = [3 => (object) ['id' => 3]]; + $helper = $this->build(AuthorsHelper::class, $redis, [ + 'entityFactory' => [\Okay\Helpers\AuthorsHelper::class, $this->factoryReturning($rows)], + ]); + + self::assertSame($rows, $helper->getList([], null, [])); + self::assertNull($redis->lastKey); + self::assertSame([], $redis->stored); + } + + public function testAttachPostDataHitIsKeyedByPostId(): void + { + $keys = []; + foreach ([1, 2] as $id) { + $redis = new StubRedisCacheService(); + $redis->cachedValue = (object) ['id' => $id, 'author' => 'закешований']; + + $result = $this->build(BlogHelper::class, $redis)->attachPostData((object) ['id' => $id]); + + self::assertSame($redis->cachedValue, $result); + self::assertStringStartsWith('blog_attach_post_data|' . CacheTags::AUTHORS_BLOG . '|', (string) $redis->lastKey); + $keys[] = $redis->lastKey; + } + + self::assertNotSame($keys[0], $keys[1]); + } + + public function testAttachPostDataWithoutIdSkipsCache(): void + { + $redis = new StubRedisCacheService(); + + self::assertFalse($this->build(BlogHelper::class, $redis)->attachPostData((object) [])); + self::assertNull($redis->lastKey); + } + + public function testRelatedProductsKeyDependsOnEntityAndFilter(): void + { + $first = new class implements RelatedProductsInterface { + public function getRelatedProducts(array $filter = []) { return []; } + public function addRelatedProduct($objectId, $relatedId, $position = 0) {} + public function deleteRelatedProduct($objectId, $relatedId = null) {} + }; + $second = new class implements RelatedProductsInterface { + public function getRelatedProducts(array $filter = []) { return []; } + public function addRelatedProduct($objectId, $relatedId, $position = 0) {} + public function deleteRelatedProduct($objectId, $relatedId = null) {} + }; + + $keys = []; + foreach ([[$first, ['p' => 1]], [$first, ['p' => 2]], [$second, ['p' => 1]]] as [$entity, $filter]) { + $redis = new StubRedisCacheService(); + $redis->cachedValue = []; + $this->build(RelatedProductsHelper::class, $redis)->getRelatedProductsList($entity, $filter); + self::assertStringStartsWith( + 'related_products_list|' . CacheTags::PRODUCTS_ALL . ',' . CacheTags::PRODUCTS_LIST . '|', + (string) $redis->lastKey + ); + $keys[] = $redis->lastKey; + } + + self::assertCount(3, array_unique($keys)); + } +} diff --git a/tests/InitRegistrationTest.php b/tests/InitRegistrationTest.php new file mode 100644 index 0000000..32092fa --- /dev/null +++ b/tests/InitRegistrationTest.php @@ -0,0 +1,102 @@ + ціль і екстендер кожної реєстрації */ + private function registrations(): array + { + $source = (string) file_get_contents(self::MODULE . '/Init/Init.php'); + preg_match_all('/^use ([\\\\\w]+);/m', $source, $uses); + $imports = []; + foreach ($uses[1] as $fqcn) { + $imports[substr((string) strrchr('\\' . $fqcn, '\\'), 1)] = $fqcn; + } + + $pair = "\\[\\s*(?:'class'\\s*=>\\s*)?(\\w+)::class,\\s*(?:'method'\\s*=>\\s*)?'(\\w+)'\\s*\\]"; + preg_match_all("/register(?:Queue|Chain)Extension\\(\\s*{$pair},\\s*{$pair}\\s*\\)/", $source, $matches, PREG_SET_ORDER); + + return array_map( + fn ($m) => [$imports[$m[1]], $m[2], $imports[$m[3]], $m[4]], + $matches + ); + } + + public function testRegistrationsAreFound(): void + { + $source = (string) file_get_contents(self::MODULE . '/Init/Init.php'); + + self::assertSame(substr_count($source, 'Extension('), count($this->registrations()), 'регулярка мусить бачити кожну реєстрацію'); + } + + public function testEveryHookPointsAtExistingMethods(): void + { + foreach ($this->registrations() as [$target, $targetMethod, $extender, $extenderMethod]) { + self::assertTrue(method_exists($target, $targetMethod), "$target::$targetMethod"); + self::assertTrue(method_exists($extender, $extenderMethod), "$extender::$extenderMethod"); + } + } + + /** method_exists тут замало: хук на метод без ExtenderFacade просто ніколи не викликається. */ + public function testEveryHookedMethodIsActuallyExtendable(): void + { + foreach ($this->registrations() as [$target, $targetMethod]) { + self::assertTrue($this->reachesExtender(new \ReflectionMethod($target, $targetMethod)), "$target::$targetMethod"); + } + } + + /** Сутності перевизначають update() і кличуть parent::, а ExtenderFacade лежить у базовому CRUD. */ + private function reachesExtender(\ReflectionMethod $method): bool + { + $source = implode('', array_slice( + file((string) $method->getFileName()), + (int) $method->getStartLine() - 1, + (int) $method->getEndLine() - (int) $method->getStartLine() + 1 + )); + if (str_contains($source, 'ExtenderFacade::execute')) { + return true; + } + + $parent = $method->getDeclaringClass()->getParentClass(); + + return $parent !== false + && str_contains($source, 'parent::' . $method->getName()) + && $this->reachesExtender($parent->getMethod($method->getName())); + } + + public function testEveryInvalidatorHandlerIsRegistered(): void + { + $registered = []; + foreach ($this->registrations() as [, , $extender, $method]) { + $registered["$extender::$method"] = true; + } + + foreach (glob(self::MODULE . '/Extenders/*Invalidator.php') as $file) { + $class = self::EXTENDERS . basename($file, '.php'); + foreach (get_class_methods($class) as $method) { + if (str_starts_with($method, 'on')) { + self::assertArrayHasKey("$class::$method", $registered); + } + } + } + } + + public function testEveryExtenderIsADeclaredService(): void + { + $services = (string) file_get_contents(self::MODULE . '/Init/services.php'); + + foreach (glob(self::MODULE . '/Extenders/*.php') as $file) { + self::assertStringContainsString(basename($file, '.php') . '::class', $services, basename($file)); + } + } +} diff --git a/tests/ProductRouteWarmerTest.php b/tests/ProductRouteWarmerTest.php new file mode 100644 index 0000000..37392ba --- /dev/null +++ b/tests/ProductRouteWarmerTest.php @@ -0,0 +1,83 @@ +setValue(null, []); + $this->lookups = []; + } + + private function warmer(string $routeName, array $params, ?object $row): ProductRouteWarmer + { + $router = $this->createStub(Router::class); + $router->method('getCurrentRouteRequiredParams')->willReturn($params); + + $entity = $this->createStub(RouterCacheEntity::class); + $entity->method('findOne')->willReturnCallback(function (array $filter) use ($row) { + $this->lookups[] = $filter; + return $row; + }); + $factory = $this->createStub(EntityFactory::class); + $factory->method('get')->willReturn($entity); + + return new class ($router, $factory, $routeName) extends ProductRouteWarmer { + public function __construct(Router $router, EntityFactory $factory, private string $name) + { + parent::__construct($router, $factory); + } + + protected function routeName(): ?string + { + return $this->name; + } + }; + } + + public function testProductPageGetsAliasByPointLookup(): void + { + $this->warmer('product', ['url' => 'kettle'], (object) ['slug_url' => 'kitchen/kettle'])->warmCurrentProduct(); + + self::assertSame('kitchen/kettle', ProductRoute::getUrlSlugAlias('kettle')); + self::assertSame([['url' => 'kettle', 'type' => 'product']], $this->lookups); + } + + public function testOtherRoutesDoNoWork(): void + { + $this->warmer('category', ['url' => 'kitchen'], (object) ['slug_url' => 'x'])->warmCurrentProduct(); + + self::assertSame([], $this->lookups); + } + + public function testKnownAliasIsNotQueriedAgain(): void + { + ProductRoute::setUrlSlugAlias('kettle', 'kitchen/kettle'); + + $this->warmer('product', ['url' => 'kettle'], null)->warmCurrentProduct(); + + self::assertSame([], $this->lookups); + } + + public function testMissingRouteLeavesCoreFallback(): void + { + $this->warmer('product', ['url' => 'new-product'], null)->warmCurrentProduct(); + + self::assertEmpty(ProductRoute::getUrlSlugAlias('new-product')); + } +} diff --git a/tests/RealServerContractTest.php b/tests/RealServerContractTest.php new file mode 100644 index 0000000..fd50226 --- /dev/null +++ b/tests/RealServerContractTest.php @@ -0,0 +1,172 @@ +markTestSkipped('потрібні phpredis і REDIS_HOST'); + } + + $password = getenv('REDIS_PASSWORD'); + $this->raw = new \Redis(); + try { + $this->raw->connect($host, (int) (getenv('REDIS_PORT') ?: 6379), 1.0); + if ($password !== false && $password !== '') { + $this->raw->auth($password); + } + $this->raw->select(self::TEST_DB); + } catch (\Throwable $e) { + unset($this->raw); + $this->markTestSkipped('Redis недоступний: ' . $e->getMessage()); + } + $this->raw->flushDB(); + + foreach (['REDIS_DB', 'REDIS_PREFIX', 'REDIS_ENABLED'] as $name) { + $this->envBackup[$name] = getenv($name); + } + putenv('REDIS_DB=' . self::TEST_DB); + putenv('REDIS_ENABLED=1'); + } + + protected function tearDown(): void + { + if (!isset($this->raw)) { + return; + } + $this->raw->flushDB(); + $this->raw->close(); + foreach ($this->envBackup as $name => $value) { + putenv($value === false ? $name : "$name=$value"); + } + } + + private function service(string $prefix): RedisCacheService + { + putenv('REDIS_PREFIX=' . $prefix); + $settings = $this->createStub(Settings::class); + $settings->method('get')->willReturnCallback( + fn (string $k) => $k === 'sviat__redis__default_ttl' ? 600 : null + ); + + return new class ($settings) extends RedisCacheService { + public array $deferred = []; + + protected function defer(callable $task): void + { + $this->deferred[] = $task; + } + }; + } + + public function testFlushRemovesEveryModuleKeyAndNothingElse(): void + { + for ($i = 0; $i < 1300; $i++) { + $this->raw->set("okay:helpers:k$i", 'v'); + } + $this->raw->set('okay:helpers:ver:pver:1', '5'); + $this->raw->set('PHPREDIS_SESSION:abc', 'сесія'); + $this->raw->set('okay:queue:jobs', 'черга під тим самим префіксом'); + $this->raw->set('other:helpers:x', 'сусід'); + + self::assertTrue($this->service('okay:')->flushAll()); + + self::assertSame(3, $this->raw->dbSize()); + self::assertSame('сесія', $this->raw->get('PHPREDIS_SESSION:abc')); + } + + public function testFlushWithGlobPrefixKeepsNeighbour(): void + { + $this->raw->set('shop*:helpers:own', 'своє'); + $this->raw->set('shop2:helpers:neighbour', 'сусід'); + + self::assertTrue($this->service('shop*:')->flushAll()); + + self::assertSame(0, $this->raw->exists('shop*:helpers:own')); + self::assertSame(1, $this->raw->exists('shop2:helpers:neighbour')); + } + + public function testFlushOnEmptyDbSucceeds(): void + { + self::assertTrue($this->service('okay:')->flushAll()); + } + + public function testLockReleaseSeesPrefixedKey(): void + { + $service = $this->service('okay:'); + $service->remember('t', [], [], fn () => 'старе', 60); + $this->expireAllEnvelopes(); + + $service = $this->service('okay:'); + self::assertSame('старе', $service->remember('t', [], [], fn () => 'нове', 60)); + $locks = $this->raw->keys('okay:*:lock'); + self::assertCount(1, $locks, 'замок лежить під префіксом'); + self::assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $this->raw->get($locks[0])); + + ($service->deferred[0])(); + + self::assertSame([], $this->raw->keys('okay:*:lock'), 'якби eval не додав префікс, замок лишився б'); + } + + public function testExpiredOwnerLeavesReplacementLockOnServer(): void + { + $service = $this->service('okay:'); + $service->remember('t', [], [], fn () => 'старе', 60); + $this->expireAllEnvelopes(); + + $service = $this->service('okay:'); + $service->remember('t', [], [], fn () => 'нове', 60); + [$lock] = $this->raw->keys('okay:*:lock'); + $this->raw->set($lock, 'токен-іншого-воркера'); + + ($service->deferred[0])(); + + self::assertSame('токен-іншого-воркера', $this->raw->get($lock)); + } + + public function testWriterWithoutTheKeyCannotChangeCachedValue(): void + { + $settings = $this->createStub(Settings::class); + $settings->method('get')->willReturnCallback(fn (string $k) => $k === 'sviat__redis__default_ttl' ? 600 : null); + $config = $this->createStub(Config::class); + $config->method('get')->willReturnCallback(fn (string $k) => $k === 'db_password' ? 'secret' : null); + putenv('REDIS_PREFIX=okay:'); + + new RedisCacheService($settings, $config)->set('helpers:price', ['rate' => 40]); + self::assertSame(['rate' => 40], new RedisCacheService($settings, $config)->get('helpers:price')); + + $this->raw->set('okay:helpers:price', serialize(['rate' => 1])); + + self::assertNull(new RedisCacheService($settings, $config)->get('helpers:price')); + } + + private function expireAllEnvelopes(): void + { + foreach ($this->raw->keys('okay:helpers:*') as $key) { + $envelope = unserialize($this->raw->get($key)); + if (is_array($envelope) && isset($envelope['f'])) { + $envelope['f'] = 1.0; + $this->raw->set($key, serialize($envelope)); + } + } + } +} diff --git a/tests/RedisCacheServiceTest.php b/tests/RedisCacheServiceTest.php index 5f1c966..0425e29 100644 --- a/tests/RedisCacheServiceTest.php +++ b/tests/RedisCacheServiceTest.php @@ -355,4 +355,101 @@ public function testRequestStatsDoNotDoubleCountMemoizedReads(): void $this->assertSame(1, $service->getRequestStats()['hits']); } + + private function serviceWithBareClient(?object $client, bool $enabled = true): RedisCacheService + { + $settings = $this->createStub(Settings::class); + $settings->method('get')->willReturnCallback(fn (string $k) => $k === 'sviat__redis__enabled' ? $enabled : null); + + return new class ($settings, $client) extends RedisCacheService { + public function __construct(Settings $settings, private ?object $bare) + { + parent::__construct($settings); + } + + protected function connectBare(bool $applyKeyPrefix = true, bool $persistent = false) + { + return $this->bare; + } + }; + } + + public function testConnectionSucceedsOnPong(): void + { + if (!class_exists('\\Redis')) { $this->markTestSkipped('phpredis not installed'); } + $service = $this->serviceWithBareClient(new FakeRedisClient()); + + self::assertTrue($service->testConnection()); + self::assertNull($service->getLastError()); + } + + public function testConnectionReportsUnexpectedAnswer(): void + { + if (!class_exists('\\Redis')) { $this->markTestSkipped('phpredis not installed'); } + $client = new class extends FakeRedisClient { + public function ping() { return 'LOADING'; } + }; + $service = $this->serviceWithBareClient($client); + + self::assertFalse($service->testConnection()); + self::assertSame('Unexpected PING response from Redis', $service->getLastError()); + } + + public function testConnectionReportsServerFailure(): void + { + if (!class_exists('\\Redis')) { $this->markTestSkipped('phpredis not installed'); } + $client = new class extends FakeRedisClient { + public function ping() { throw new \RuntimeException('NOAUTH'); } + }; + $service = $this->serviceWithBareClient($client); + + self::assertFalse($service->testConnection()); + self::assertSame('NOAUTH', $service->getLastError()); + } + + public function testDisabledModuleIsCheckedOnlyWhenAdminAsks(): void + { + if (!class_exists('\\Redis')) { $this->markTestSkipped('phpredis not installed'); } + $service = $this->serviceWithBareClient(new FakeRedisClient(), false); + + self::assertFalse($service->testConnection()); + self::assertTrue($service->testConnection(true)); + } + + public function testStatsReportServerState(): void + { + if (!class_exists('\\Redis')) { $this->markTestSkipped('phpredis not installed'); } + $client = new FakeRedisClient(); + $client->store['k'] = 'v'; + + $stats = $this->makeService($client)->getStats(); + + self::assertTrue($stats['connected']); + self::assertSame(1, $stats['db_size']); + self::assertSame('1M', $stats['used_memory']); + } + + public function testStatsSurviveServerFailure(): void + { + if (!class_exists('\\Redis')) { $this->markTestSkipped('phpredis not installed'); } + $client = new class extends FakeRedisClient { + public function info(): array { throw new \RuntimeException('down'); } + }; + + $stats = $this->makeService($client)->getStats(); + + self::assertFalse($stats['connected']); + self::assertSame('down', $stats['error']); + } + + public function testInvalidateProductDataBumpsBothProductScopes(): void + { + if (!class_exists('\\Redis')) { $this->markTestSkipped('phpredis not installed'); } + $client = new FakeRedisClient(); + + $this->makeService($client)->invalidateProductData(); + + self::assertSame(1, $client->store['helpers:ver:pall:global']); + self::assertSame(1, $client->store['helpers:ver:plist:global']); + } } diff --git a/tests/SettingsPasswordTest.php b/tests/SettingsPasswordTest.php new file mode 100644 index 0000000..c8faa77 --- /dev/null +++ b/tests/SettingsPasswordTest.php @@ -0,0 +1,193 @@ +, 1: array} збережене й передане в шаблон */ + private function submit(array $post, ?string $stored): array + { + $saved = ['sviat__redis__password' => $stored, 'sviat__redis__host' => 'redis.local', 'sviat__redis__port' => 6379]; + $post += ['host' => 'redis.local', 'port' => '6379', 'prefix' => 'okay:']; + + $settings = $this->createStub(Settings::class); + $settings->method('get')->willReturnCallback(function (string $k) use (&$saved) { + return $saved[$k] ?? null; + }); + $settings->method('set')->willReturnCallback(function (string $k, $v) use (&$saved) { + $saved[$k] = $v; + }); + + $request = new class ($post) extends Request { + public function __construct(private array $form) + { + } + + public function method($method = null) + { + return $method === null ? 'POST' : strtolower((string) $method) === 'post'; + } + + public function post($name = null, $type = null, $default = null) + { + return $this->form[$name] ?? null; + } + }; + + $assigned = []; + $design = $this->createStub(Design::class); + $design->method('assign')->willReturnCallback(function ($k, $v) use (&$assigned) { + $assigned[$k] = $v; + }); + $design->method('fetch')->willReturn(''); + + $controller = new \ReflectionClass(new class extends RedisSettingsAdmin { + public function __construct() {} + protected function isFromThisSite(): bool { return true; } + })->newInstanceWithoutConstructor(); + $parent = new \ReflectionClass(\Okay\Admin\Controllers\IndexAdmin::class); + foreach (['settings' => $settings, 'request' => $request, 'design' => $design, 'response' => $this->createStub(Response::class)] as $prop => $value) { + self::accessible($parent->getProperty($prop))->setValue($controller, $value); + } + + $redis = $this->createStub(RedisCacheService::class); + $redis->method('connectionView')->willReturn(['enabled' => false, 'host' => 'redis.local', 'port' => 6379, 'db' => 0, 'username' => '', 'prefix' => 'okay:']); + $controller->fetch($redis); + + return [$saved, $assigned]; + } + + public function testBlankFieldKeepsStoredPassword(): void + { + [$saved] = $this->submit(['action' => 'save', 'password' => ''], 'секрет'); + + self::assertSame('секрет', $saved['sviat__redis__password']); + } + + public function testTypedPasswordReplacesStoredOne(): void + { + [$saved] = $this->submit(['action' => 'save', 'password' => 'новий'], 'секрет'); + + self::assertSame('новий', $saved['sviat__redis__password']); + } + + public function testClearCheckboxRemovesStoredPassword(): void + { + [$saved] = $this->submit(['action' => 'save', 'password' => '', 'clear_password' => '1'], 'секрет'); + + self::assertSame('', $saved['sviat__redis__password']); + } + + public function testTypedPasswordWinsOverClearCheckbox(): void + { + [$saved] = $this->submit(['action' => 'save', 'password' => 'новий', 'clear_password' => '1'], 'секрет'); + + self::assertSame('новий', $saved['sviat__redis__password'], 'введений пароль не сміє мовчки зникнути'); + } + + public function testPlaceholderDependsOnWhetherPasswordIsStored(): void + { + $template = (string) file_get_contents(self::TEMPLATE); + + self::assertMatchesRegularExpression( + '/placeholder="\\{if \\$redis_password_is_set\\}\\{\\$btr->sviat_redis_password_placeholder\\|escape\\}\\{else\\}\\{\\$btr->sviat_redis_password_placeholder_empty\\|escape\\}\\{\\/if\\}"/', + $template + ); + } + + public function testPasswordKeysExistInEveryLanguage(): void + { + foreach (['ua', 'en', 'ru'] as $language) { + $lang = []; + require __DIR__ . "/../../../../Okay/Modules/Sviat/Redis/Backend/lang/$language.php"; + + foreach (['sviat_redis_password_placeholder', 'sviat_redis_password_placeholder_empty', 'sviat_redis_clear_password'] as $key) { + self::assertNotEmpty($lang[$key] ?? null, "$language: $key"); + } + } + } + + public function testForeignOriginWritesNothing(): void + { + $saved = []; + $settings = $this->createStub(Settings::class); + $settings->method('set')->willReturnCallback(function (string $k, $v) use (&$saved) { + $saved[$k] = $v; + }); + $request = new class extends Request { + public function __construct() {} + public function method($method = null) { return true; } + public function post($name = null, $type = null, $default = null) { return $name === 'action' ? 'save' : 'x'; } + }; + $statuses = []; + $response = $this->createStub(Response::class); + $response->method('setStatusCode')->willReturnCallback(function ($code) use (&$statuses, $response) { + $statuses[] = $code; + return $response; + }); + + $controller = new \ReflectionClass(new class extends RedisSettingsAdmin { + public function __construct() {} + protected function isFromThisSite(): bool { return false; } + })->newInstanceWithoutConstructor(); + $parent = new \ReflectionClass(\Okay\Admin\Controllers\IndexAdmin::class); + foreach (['settings' => $settings, 'request' => $request, 'design' => $this->createStub(Design::class), 'response' => $response] as $prop => $value) { + self::accessible($parent->getProperty($prop))->setValue($controller, $value); + } + + $controller->fetch($this->createStub(RedisCacheService::class)); + + self::assertSame([], $saved); + self::assertSame([403], $statuses); + } + + public function testPostWithoutKnownActionWritesNothing(): void + { + [$saved] = $this->submit(['password' => 'новий'], 'секрет'); + + self::assertSame('секрет', $saved['sviat__redis__password']); + self::assertArrayNotHasKey('sviat__redis__default_ttl', $saved); + } + + public function testStoredPasswordNeverReachesTemplate(): void + { + [, $assigned] = $this->submit(['action' => 'save', 'password' => ''], 'секрет'); + + self::assertArrayNotHasKey('redis_password', $assigned); + self::assertNotContains('секрет', $assigned); + self::assertTrue($assigned['redis_password_is_set']); + } + + public function testClearCheckboxOnlyOfferedWhenThereIsSomethingToClear(): void + { + [, $assigned] = $this->submit(['action' => 'save', 'password' => ''], ''); + + self::assertFalse($assigned['redis_password_is_set']); + } + + public function testTemplateRendersPasswordInputEmpty(): void + { + $template = (string) file_get_contents(self::TEMPLATE); + + self::assertStringContainsString('name="password" value=""', $template); + self::assertStringNotContainsString('$redis_password|', $template); + } +} diff --git a/tests/StubRedisCacheService.php b/tests/StubRedisCacheService.php index 7a5857b..430868b 100644 --- a/tests/StubRedisCacheService.php +++ b/tests/StubRedisCacheService.php @@ -22,7 +22,9 @@ public function __construct() // Skip parent constructor — we only record bumps. } - public function isEnabled(): bool { return true; } + public bool $enabled = true; + + public function isEnabled(): bool { return $this->enabled; } public function bump(string $tag): void { @@ -44,6 +46,7 @@ public function makeVersionedKey(string $name, array $tags, array $args = []): s public function get(string $key) { + $this->lastKey = $key; return $this->cachedValue; } @@ -52,9 +55,15 @@ public function set(string $key, $value, ?int $ttl = null): void $this->stored[$key] = [$value, $ttl]; } + /** @var array helperKey => TTL з налаштувань */ + public array $helperTtls = []; + + /** Ключ, за яким востаннє читали кеш. */ + public ?string $lastKey = null; + public function getHelperTtl(string $helperKey): ?int { - return null; + return $this->helperTtls[$helperKey] ?? null; } /**