From b2f4cb8ffa9d5cd101ab23b558ab01338bf88ca0 Mon Sep 17 00:00:00 2001 From: Adam Daley Date: Tue, 28 Apr 2026 22:11:39 +0100 Subject: [PATCH] Enhance API rate limiting, validation, and subscription features (#3459) * Validate redirect paths and targets * Sanitize guest client data and misc cleanups * Implement API rate limiting and pruning * Bump `last_patch` setting to 54 * Add tests for `shouldUseTokenLogin` logic Add tests to cover logic added in #3451. * Add order/renewal line config for domain pricing Resolves #2793. * Add PayPalEmail adapter subscription test * Add width/height styling for textarea fields Resolves #2448. * Send invoice-created email on approve Resolves #3012. * Enforce cumulative cart stock and stockSale Resolves #3130. * Centralize subscription period retrieval Resolves #1035. * Support wildcard staff permissions (default.all) Resolves #2376. * Enable quantity selection and enforce stock max Resolves #2573. * Extend order expiry on first paid invoice Resolves #2864. * Rate-limit request prefix; invoice & promo fixes * Update src/modules/Redirect/templates/admin/mod_redirect_settings.html.twig Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update src/modules/Api/Service.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update src/modules/Client/Controller/Client.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update src/modules/Cron/Service.php Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Fix quantity not passed to getOrderLineConfig in createOrder Agent-Logs-Url: https://github.com/FOSSBilling/FOSSBilling/sessions/669f845c-50c4-4f7e-95cd-f44de162ad72 Co-authored-by: admdly <2807620+admdly@users.noreply.github.com> * Simplify quantity injection into getOrderLineConfig call Agent-Logs-Url: https://github.com/FOSSBilling/FOSSBilling/sessions/669f845c-50c4-4f7e-95cd-f44de162ad72 Co-authored-by: admdly <2807620+admdly@users.noreply.github.com> * Fix rate limit prefix isolation, whitelist headers, and staff controller prefix Agent-Logs-Url: https://github.com/FOSSBilling/FOSSBilling/sessions/11f3fd58-bb44-46a5-a6cf-0992b038f4a7 Co-authored-by: admdly <2807620+admdly@users.noreply.github.com> * Enforce promo usage limit and add test --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: admdly <2807620+admdly@users.noreply.github.com> --- src/config-sample.php | 8 +- src/install/sql/content.sql | 2 +- src/install/sql/structure.sql | 3 +- src/library/Box/App.php | 74 ++++++ src/library/FOSSBilling/UpdatePatcher.php | 18 ++ src/library/Model/ApiRequest.php | 14 -- src/library/Model/ApiRequestTable.php | 50 ---- src/library/Model/ProductDomainTable.php | 116 +++++++-- src/library/Model/ProductTable.php | 16 ++ src/modules/Api/Controller/Client.php | 54 ++-- src/modules/Api/Service.php | 66 +++-- src/modules/Cart/Service.php | 68 ++++- src/modules/Client/Api/Guest.php | 2 - src/modules/Client/Controller/Client.php | 25 +- src/modules/Client/Service.php | 25 +- .../admin/mod_formbuilder_manage.html.twig | 7 +- .../admin/mod_formbuilder_preview.html.twig | 8 +- .../client/mod_formbuilder_build.html.twig | 7 +- src/modules/Invoice/Service.php | 55 +++- src/modules/Invoice/ServiceInvoiceItem.php | 31 ++- src/modules/Invoice/ServiceSubscription.php | 78 +++--- src/modules/Order/Service.php | 24 +- ...rderbutton_product_configuration.html.twig | 12 +- src/modules/Product/Service.php | 44 +++- src/modules/Redirect/Api/Admin.php | 4 +- src/modules/Redirect/Controller/Client.php | 23 +- src/modules/Redirect/Service.php | 51 +++- .../admin/mod_redirect_settings.html.twig | 2 +- src/modules/Servicedomain/Service.php | 1 - src/modules/Staff/Controller/Admin.php | 24 +- src/modules/Staff/Service.php | 21 +- .../admin/mod_staff_manage.html.twig | 20 +- .../library/Model/ProductDomainTableTest.php | 110 ++++++++ .../modules/Api/Controller/ClientTest.php | 20 +- .../modules/Api/ControllerClientTest.php | 23 ++ tests-legacy/modules/Api/ServiceTest.php | 28 +++ .../modules/Cart/DomainPricingTest.php | 78 ++++++ tests-legacy/modules/Cart/ServiceTest.php | 92 ++++++- tests-legacy/modules/Client/ServiceTest.php | 73 ++++++ .../Invoice/PaymentAdapterPayPalEmailTest.php | 150 +++++++++++ .../Invoice/ServiceInvoiceItemTest.php | 121 +++++++++ .../Invoice/ServiceSubscriptionTest.php | 78 ++++-- tests-legacy/modules/Invoice/ServiceTest.php | 235 ++++++++++++++++-- tests-legacy/modules/Order/ServiceTest.php | 83 ++++++- .../modules/Redirect/Api/AdminTest.php | 4 +- tests-legacy/modules/Redirect/ServiceTest.php | 152 +++++++++++ tests-legacy/modules/Staff/ServiceTest.php | 31 +++ 47 files changed, 1940 insertions(+), 291 deletions(-) delete mode 100644 src/library/Model/ApiRequest.php delete mode 100644 src/library/Model/ApiRequestTable.php create mode 100644 tests-legacy/library/Model/ProductDomainTableTest.php create mode 100644 tests-legacy/modules/Cart/DomainPricingTest.php create mode 100644 tests-legacy/modules/Invoice/PaymentAdapterPayPalEmailTest.php create mode 100644 tests-legacy/modules/Redirect/ServiceTest.php diff --git a/src/config-sample.php b/src/config-sample.php index e3b658345..747eac1dc 100644 --- a/src/config-sample.php +++ b/src/config-sample.php @@ -172,10 +172,10 @@ return [ 'rate_limit' => 1000, /** - * Note about rate-limiting login attempts: - * When the limit is reached, a default delay of 2 seconds is added to the request. - * This makes brute-forcing a password useless while not outright blocking legitimate traffic. - * When calculating, ensure the rate-limited traffic can still make enough requests to stay rate limited + * Note about rate-limiting: + * Rate limiting applies to all requests (API routes and page routes). + * When the limit is reached, the request is rejected with HTTP 429 (Too Many Requests). + * Auth-sensitive endpoints (password reset, email confirmation) use the stricter login-tier limits. * Ex: One request every 2 seconds is more than 20 times in 1 minute, so the IP will remain throttled. */ 'throttle_delay' => 2, diff --git a/src/install/sql/content.sql b/src/install/sql/content.sql index aaa332cf3..af7f4812f 100644 --- a/src/install/sql/content.sql +++ b/src/install/sql/content.sql @@ -310,7 +310,7 @@ LOCK TABLES `setting` WRITE; INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`) VALUES - (1,'last_patch','53',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), + (1,'last_patch','54',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'), (2,'company_name','Company Name',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (3,'company_email','support@yourcompany.com',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), (4,'company_signature','FOSSBilling.org - Client Management, Invoicing and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'), diff --git a/src/install/sql/structure.sql b/src/install/sql/structure.sql index 03cc9da87..daa199f08 100644 --- a/src/install/sql/structure.sql +++ b/src/install/sql/structure.sql @@ -159,7 +159,8 @@ CREATE TABLE `api_request` ( `ip` varchar(45) DEFAULT NULL, `request` text, `created_at` datetime DEFAULT NULL, - PRIMARY KEY (`id`) + PRIMARY KEY (`id`), + KEY `api_request_ip_created` (`ip`, `created_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; diff --git a/src/library/Box/App.php b/src/library/Box/App.php index 1d2f53e86..752e66b53 100644 --- a/src/library/Box/App.php +++ b/src/library/Box/App.php @@ -131,9 +131,83 @@ class Box_App $this->checkPermission(); $timeCollector->stopMeasure('checkperm'); + $timeCollector->startMeasure('rateLimit', 'Checking rate limit'); + $this->enforceRateLimit(); + $timeCollector->stopMeasure('rateLimit'); + return $this->processRequest(); } + protected function enforceRateLimit(): void + { + $apiConfig = Config::getProperty('api', []); + $whitelist = $apiConfig['rate_limit_whitelist'] ?? []; + $ip = $this->di['request']->getClientIp(); + + if (in_array($ip, $whitelist, true)) { + return; + } + + $logPrefix = $this->mod === 'api' ? 'api:' : 'page:'; + + $authPattern = $this->getAuthSensitivePattern(); + if ($authPattern !== null) { + $rateSpan = $apiConfig['rate_span_login'] ?? 60; + $rateLimit = $apiConfig['rate_limit_login'] ?? 20; + $checkPrefix = 'page:' . $authPattern; + } else { + $rateSpan = $apiConfig['rate_span'] ?? 3600; + $rateLimit = $apiConfig['rate_limit'] ?? 1000; + $checkPrefix = $logPrefix; + } + + $service = $this->di['mod_service']('api'); + $service->logRequest($logPrefix . $this->url); + + if ($service->isRateLimited($ip, $rateLimit, $rateSpan, $checkPrefix)) { + $throttleDelay = $apiConfig['throttle_delay'] ?? 2; + sleep((int) $throttleDelay); + + if ($this->mod === 'api') { + $exc = new FOSSBilling\InformationException('Rate limit exceeded. Please try again later.', null, 429); + $apiController = new Box\Mod\Api\Controller\Client(); + $apiController->setDi($this->di); + $apiController->renderJson(null, $exc); + } else { + http_response_code(429); + echo $this->render('error', [ + 'exception' => new FOSSBilling\InformationException('Rate limit exceeded. Please try again later.', null, 429), + ]); + } + exit; + } + } + + protected function getAuthSensitivePattern(): ?string + { + $uri = '/' . ltrim($this->uri, '/'); + + $authSensitivePatterns = [ + '/client/reset-password-confirm/', + '/reset-password-confirm/', + '/client/confirm-email/', + '/staff/email/', + ]; + + foreach ($authSensitivePatterns as $pattern) { + if (str_starts_with($uri, $pattern)) { + return $pattern; + } + } + + return null; + } + + protected function isAuthSensitivePath(): bool + { + return $this->getAuthSensitivePattern() !== null; + } + /** * @param string $path */ diff --git a/src/library/FOSSBilling/UpdatePatcher.php b/src/library/FOSSBilling/UpdatePatcher.php index 607ba09f9..87d92ec7c 100644 --- a/src/library/FOSSBilling/UpdatePatcher.php +++ b/src/library/FOSSBilling/UpdatePatcher.php @@ -296,6 +296,7 @@ class UpdatePatcher implements InjectionAwareInterface 51 => 'patch51', 52 => 'patch52', 53 => 'patch53', + 54 => 'patch54', ]; ksort($patches, SORT_NATURAL); @@ -899,6 +900,23 @@ class UpdatePatcher implements InjectionAwareInterface } } + private function patch54(): void + { + $schemaManager = $this->di['dbal']->createSchemaManager(); + $indexes = array_map(static fn ($index) => $index->getName(), $schemaManager->listTableIndexes('api_request')); + + if (!in_array('api_request_ip_created', $indexes, true)) { + $this->executeSql('ALTER TABLE `api_request` ADD INDEX `api_request_ip_created` (`ip`, `created_at`);'); + } + + $fileActions = [ + Path::join(PATH_LIBRARY, 'Model', 'ClientPasswordResetTable.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ApiRequestTable.php') => 'unlink', + Path::join(PATH_LIBRARY, 'Model', 'ApiRequest.php') => 'unlink', + ]; + $this->executeFileActions($fileActions); + } + /** * If we end up needing a newly introduced package during the update process, composer's autoloader won't have it until the next load. * As a workaround, we can register AntLoader and point it at the Vendor folder which will then act as fallback to find the needed classes. diff --git a/src/library/Model/ApiRequest.php b/src/library/Model/ApiRequest.php deleted file mode 100644 index 2802ef696..000000000 --- a/src/library/Model/ApiRequest.php +++ /dev/null @@ -1,14 +0,0 @@ -di = $di; - } - - public function getDi(): ?Pimple\Container - { - return $this->di; - } - - public function logRequest($request, $ip): void - { - $r = $this->di['db']->dispense('ApiRequest'); - $r->ip = $ip; - $r->request = $request; - $r->created_at = date('Y-m-d H:i:s'); - $this->di['db']->store($r); - } - - public function getRequestCount($since, $ip = null) - { - $sinceIso = date('Y-m-d H:i:s', $since); - - $params = [':since' => $sinceIso]; - - if ($ip !== null) { - $sql = 'SELECT count(id) as cc FROM api_request WHERE created_at > :since AND ip = :ip'; - $params[':ip'] = $ip; - } else { - $sql = 'SELECT count(id) as cc FROM api_request WHERE created_at > :since'; - } - - return $this->di['dbal']->executeQuery($sql, $params)->fetchOne(); - } -} diff --git a/src/library/Model/ProductDomainTable.php b/src/library/Model/ProductDomainTable.php index 3a718cd2a..67009ac91 100644 --- a/src/library/Model/ProductDomainTable.php +++ b/src/library/Model/ProductDomainTable.php @@ -17,6 +17,55 @@ class Model_ProductDomainTable extends Model_ProductTable return 'year'; } + private function getRegistrationYears(array $config): int + { + if (isset($config['period']) && is_string($config['period']) && $config['period'] !== '') { + $period = $this->di['period']($config['period']); + + return max(1, $period->getQty()); + } + + return max(1, (int) ($config['register_years'] ?? $config['quantity'] ?? 1)); + } + + private function getTldModel(array $config): Model_Tld + { + $rtable = $this->di['mod_service']('servicedomain', 'Tld'); + $tld = ''; + + if (!isset($config['action'])) { + throw new FOSSBilling\Exception('Could not determine domain price. Domain action is missing', null, 498); + } + + if ($config['action'] == 'register') { + $tld = $config['register_tld']; + } + + if ($config['action'] == 'transfer') { + $tld = $config['transfer_tld']; + } + + $tld = $rtable->findOneByTld($tld); + if (!$tld instanceof Model_Tld) { + throw new FOSSBilling\Exception('Unknown TLD. Could not determine registration price'); + } + + return $tld; + } + + private function getRegistrationTotal(Model_Tld $tld, int $years): float + { + if ($years <= 0) { + return 0.0; + } + + if ($years <= 1) { + return (float) $tld->price_registration; + } + + return (float) $tld->price_registration + (($years - 1) * (float) $tld->price_renew); + } + protected function getStartingFromPrice(Model_Product $model) { $p = []; @@ -56,8 +105,9 @@ class Model_ProductDomainTable extends Model_ProductTable ) { if ($this->_hasFreePeriod($addon)) { $factor = $this->discountFactor($addon, $config['period']); + $tld = $this->getTldModel($config); - return $factor * $this->getProductPrice($product, $config); + return $this->getRegistrationTotal($tld, $factor); } return 0; @@ -219,32 +269,64 @@ class Model_ProductDomainTable extends Model_ProductTable return $pricing; } + /** + * @return array{price: float, quantity: int, setup_price: float} + */ #[Override] - public function getProductPrice(Model_Product $product, ?array $config = null) + public function getOrderLineConfig(Model_Product $product, ?array $config = null): array { - $rtable = $this->di['mod_service']('servicedomain', 'Tld'); - $tld = ''; - if (!isset($config['action'])) { throw new FOSSBilling\Exception('Could not determine domain price. Domain action is missing', null, 498); } if ($config['action'] == 'owndomain') { + return [ + 'price' => 0.0, + 'quantity' => 1, + 'setup_price' => 0.0, + ]; + } + + $tld = $this->getTldModel($config); + + if ($config['action'] == 'register') { + return [ + 'price' => $this->getRegistrationTotal($tld, $this->getRegistrationYears($config)), + 'quantity' => 1, + 'setup_price' => 0.0, + ]; + } + + return [ + 'price' => (float) $tld->price_transfer, + 'quantity' => 1, + 'setup_price' => 0.0, + ]; + } + + /** + * Resolved pricing for renewal lines in default currency. + * + * @return array{price: float, quantity: int} + */ + public function getRenewalLineConfig(Model_Product $product, ?array $config = null): array + { + $tld = $this->getTldModel($config ?? []); + + return [ + 'price' => (float) $tld->price_renew, + 'quantity' => $this->getRegistrationYears($config ?? []), + ]; + } + + #[Override] + public function getProductPrice(Model_Product $product, ?array $config = null) + { + if (($config['action'] ?? null) == 'owndomain') { return 0; } - if ($config['action'] == 'register') { - $tld = $config['register_tld']; - } - - if ($config['action'] == 'transfer') { - $tld = $config['transfer_tld']; - } - - $tld = $rtable->findOneByTld($tld); - if (!$tld instanceof Model_Tld) { - throw new FOSSBilling\Exception('Unknown TLD. Could not determine registration price'); - } + $tld = $this->getTldModel($config ?? []); if ($config['action'] == 'register') { return $tld->price_registration; diff --git a/src/library/Model/ProductTable.php b/src/library/Model/ProductTable.php index 18c456b67..3289ec2ef 100644 --- a/src/library/Model/ProductTable.php +++ b/src/library/Model/ProductTable.php @@ -72,6 +72,22 @@ class Model_ProductTable implements FOSSBilling\InjectionAwareInterface throw new FOSSBilling\Exception('Product pricing could not be determined. ' . static::class); } + /** + * Resolved pricing for the initial order line in default currency. + * + * @return array{price: float, quantity: int, setup_price: float} + */ + public function getOrderLineConfig(Model_Product $product, ?array $config = null): array + { + $quantity = max(1, (int) ($config['quantity'] ?? 1)); + + return [ + 'price' => (float) $this->getProductPrice($product, $config), + 'quantity' => $quantity, + 'setup_price' => (float) $this->getProductSetupPrice($product, $config), + ]; + } + /** * Price for one unit. * diff --git a/src/modules/Api/Controller/Client.php b/src/modules/Api/Controller/Client.php index 798240315..ae6de5246 100644 --- a/src/modules/Api/Controller/Client.php +++ b/src/modules/Api/Controller/Client.php @@ -24,6 +24,8 @@ use Symfony\Component\Filesystem\Filesystem; class Client implements InjectionAwareInterface { private int|float|null $_requests_left = null; + private int $_rate_span = 3600; + private int $_rate_limit = 1000; private ?array $apiConfig = null; private readonly Filesystem $filesystem; protected ?\Pimple\Container $di = null; @@ -120,28 +122,37 @@ class Client implements InjectionAwareInterface { $rateLimitWhitelist = $this->apiConfig['rate_limit_whitelist'] ?? []; if (in_array($this->_getIp(), $rateLimitWhitelist)) { + $this->_requests_left = null; + return true; } - $isLoginMethod = false; - if ($method == 'staff_login' || $method == 'client_login') { - $isLoginMethod = true; - $rate_span = $this->apiConfig['rate_span_login']; - $rate_limit = $this->apiConfig['rate_limit_login']; - - // 25 to 250ms delay to help prevent email enumeration. usleep(random_int(25000, 250000)); - } else { - $rate_span = $this->apiConfig['rate_span']; - $rate_limit = $this->apiConfig['rate_limit']; } + $rate_span = ($method == 'staff_login' || $method == 'client_login') + ? ($this->apiConfig['rate_span_login'] ?? 60) + : ($this->apiConfig['rate_span'] ?? 3600); + $rate_limit = ($method == 'staff_login' || $method == 'client_login') + ? ($this->apiConfig['rate_limit_login'] ?? 20) + : ($this->apiConfig['rate_limit'] ?? 1000); + + $requestPrefix = match ($method) { + 'staff_login' => 'api:/api/guest/staff/login', + 'client_login' => 'api:/api/guest/client/login', + default => 'api:', + }; + $service = $this->di['mod_service']('api'); - $requests = $service->getRequestCount(time() - $rate_span, $this->_getIp(), $isLoginMethod); - $this->_requests_left = $rate_limit - $requests; + $this->_requests_left = $service->getRemainingRequests($this->_getIp(), $rate_limit, $rate_span, $requestPrefix); + $this->_rate_span = $rate_span; + $this->_rate_limit = $rate_limit; + if ($this->_requests_left <= 0) { - sleep($this->apiConfig['throttle_delay']); + sleep((int) ($this->apiConfig['throttle_delay'] ?? 2)); + + throw new \FOSSBilling\InformationException('Rate limit exceeded. Please try again later.', null, 429); } return true; @@ -188,9 +199,6 @@ class Client implements InjectionAwareInterface { $this->_loadConfig(); $this->checkAllowedIps(); - - $service = $this->di['mod_service']('api'); - $service->logRequest(); $this->checkRateLimit($method); $this->checkHttpReferer(); $this->isRoleAllowed($role); @@ -404,7 +412,6 @@ class Client implements InjectionAwareInterface public function renderJson($data = null, ?\Exception $e = null): void { - // do not emit response if headers already sent if (headers_sent()) { return; } @@ -417,16 +424,21 @@ class Client implements InjectionAwareInterface if ($this->di['mod_service']('system')->shouldExposeVersion()) { header('X-FOSSBilling-Version: ' . \FOSSBilling\Version::VERSION); } - header('X-RateLimit-Span: ' . $this->apiConfig['rate_span']); - header('X-RateLimit-Limit: ' . $this->apiConfig['rate_limit']); - header('X-RateLimit-Remaining: ' . $this->_requests_left); + if ($this->_requests_left !== null) { + header('X-RateLimit-Span: ' . $this->_rate_span); + header('X-RateLimit-Limit: ' . $this->_rate_limit); + header('X-RateLimit-Remaining: ' . max(0, $this->_requests_left)); + } if ($e instanceof \Exception) { error_log("{$e->getMessage()} {$e->getCode()}."); $code = $e->getCode() ?: 9999; $result = ['result' => null, 'error' => ['message' => $e->getMessage(), 'code' => $code]]; $authFailed = [201, 202, 206, 204, 205, 203, 1004, 1002]; - if (in_array($code, $authFailed)) { + if ($code == 429) { + header('HTTP/1.1 429 Too Many Requests'); + header('Retry-After: ' . $this->_rate_span); + } elseif (in_array($code, $authFailed)) { header('HTTP/1.1 401 Unauthorized'); } elseif ($code == 403) { header('HTTP/1.1 403 Forbidden'); diff --git a/src/modules/Api/Service.php b/src/modules/Api/Service.php index 14e76ae3b..142d484dd 100644 --- a/src/modules/Api/Service.php +++ b/src/modules/Api/Service.php @@ -33,10 +33,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface ]; } - /** - * @return int - 1 - */ - public function logRequest() + public function logRequest(?string $path = null): int { $request = $this->di['request']; $sql = ' @@ -45,17 +42,13 @@ class Service implements \FOSSBilling\InjectionAwareInterface '; $values = [ 'ip' => $request->getClientIp(), - 'request' => $_SERVER['REQUEST_URI'] ?? null, + 'request' => $path ?? $_SERVER['REQUEST_URI'] ?? null, ]; - return $this->di['db']->exec($sql, $values); + return (int) $this->di['db']->exec($sql, $values); } - /** - * @param int|string $since - timestamp or string date - * @param string|null $ip - */ - public function getRequestCount($since, $ip = null, $isLoginMethod = false): int + public function getRequestCount($since, $ip = null, ?string $requestPrefix = null): int { if (!is_numeric($since)) { $since = strtotime($since); @@ -64,25 +57,50 @@ class Service implements \FOSSBilling\InjectionAwareInterface $values = [ 'since' => $sinceIso, ]; - if ($isLoginMethod) { - $sql = ' - SELECT COUNT(id) as cclogin - FROM api_request - WHERE created_at > :since - '; - } else { - $sql = ' - SELECT COUNT(id) as cc - FROM api_request - WHERE created_at > :since - '; - } + $sql = 'SELECT COUNT(id) FROM api_request WHERE created_at > :since'; if ($ip != null) { $sql .= ' AND ip = :ip'; $values['ip'] = $ip; } + if ($requestPrefix !== null) { + $sql .= ' AND request LIKE :request_prefix'; + $values['request_prefix'] = $requestPrefix . '%'; + } + return (int) $this->di['db']->getCell($sql, $values); } + + public function isRateLimited(string $ip, int $maxAttempts, int $timeSpanSeconds, ?string $requestPrefix = null): bool + { + return $this->getRequestCount(time() - $timeSpanSeconds, $ip, $requestPrefix) >= $maxAttempts; + } + + public function getRemainingRequests(string $ip, int $maxAttempts, int $timeSpanSeconds, ?string $requestPrefix = null): int + { + $count = $this->getRequestCount(time() - $timeSpanSeconds, $ip, $requestPrefix); + + return max(0, $maxAttempts - $count); + } + + public function pruneRequests(int $maxAgeSeconds = 7200): int + { + $cutoff = date('Y-m-d H:i:s', time() - $maxAgeSeconds); + $sql = 'DELETE FROM api_request WHERE created_at < :cutoff'; + + return (int) $this->di['db']->exec($sql, ['cutoff' => $cutoff]); + } + + public static function onBeforeAdminCronRun(\Box_Event $event): void + { + $di = $event->getDi(); + + try { + $service = $di['mod_service']('api'); + $service->pruneRequests(); + } catch (\Exception $e) { + error_log($e->getMessage()); + } + } } diff --git a/src/modules/Cart/Service.php b/src/modules/Cart/Service.php index 3b5dc01b5..2558131e3 100644 --- a/src/modules/Cart/Service.php +++ b/src/modules/Cart/Service.php @@ -115,12 +115,6 @@ class Service implements InjectionAwareInterface } } - $qty = $data['quantity'] ?? 1; - // check stock - if (!$this->isStockAvailable($product, $qty)) { - throw new \FOSSBilling\InformationException('This item is currently out of stock'); - } - $addons = $data['addons'] ?? []; unset($data['id']); unset($data['addons']); @@ -166,6 +160,20 @@ class Service implements InjectionAwareInterface } } + $pendingQuantities = []; + foreach ($list as $cartItem) { + /** @var \Model_Product $cartProduct */ + $cartProduct = $cartItem['product']; + $requestedQty = $this->getRequestedQuantity($cartItem['config']); + $cartProductId = (int) $cartProduct->id; + $pendingQuantities[$cartProductId] = ($pendingQuantities[$cartProductId] ?? 0) + $requestedQty; + + $reservedQty = $this->getReservedQuantityInCart($cart, $cartProductId); + if (!$this->isStockAvailable($cartProduct, $reservedQty + $pendingQuantities[$cartProductId])) { + throw new \FOSSBilling\InformationException('This item is currently out of stock'); + } + } + foreach ($list as $c) { $productFromList = $c['product']; $productFromListConfig = $c['config']; @@ -236,6 +244,26 @@ class Service implements InjectionAwareInterface return true; } + protected function getReservedQuantityInCart(\Model_Cart $cart, int $productId): int + { + $reservedQty = 0; + foreach ($this->getCartProducts($cart) as $cartProduct) { + if ((int) $cartProduct->product_id !== $productId) { + continue; + } + + $config = $this->getItemConfig($cartProduct); + $reservedQty += $this->getRequestedQuantity($config); + } + + return $reservedQty; + } + + protected function getRequestedQuantity(array $config): int + { + return max(1, (int) ($config['quantity'] ?? 1)); + } + public function removeProduct(\Model_Cart $cart, $id, $removeAddons = true): bool { $bindings = [ @@ -556,6 +584,7 @@ class Service implements InjectionAwareInterface $orders = []; $invoice_items = []; $master_order = null; + $requestedProductQuantities = []; $i = 0; foreach ($this->getCartProducts($cart) as $p) { @@ -566,6 +595,12 @@ class Service implements InjectionAwareInterface throw new \FOSSBilling\InformationException('Unable to complete order. One or more of the selected products are invalid.'); } + $requestedQty = $this->getRequestedQuantity($item); + $requestedProductQuantities[$product->id] = ($requestedProductQuantities[$product->id] ?? 0) + $requestedQty; + if (!$this->isStockAvailable($product, $requestedProductQuantities[$product->id])) { + throw new \FOSSBilling\InformationException('Unable to complete order. One or more selected products are out of stock.'); + } + /* * Convert the domain name to lowercase letters. * Using a capital letter in a domain name still points to the same name, so this isn't going to break anything @@ -721,9 +756,13 @@ class Service implements InjectionAwareInterface public function usePromo(\Model_Promo $promo): void { - ++$promo->used; - $promo->updated_at = date('Y-m-d H:i:s'); - $this->di['db']->store($promo); + $affectedRows = $this->di['db']->exec( + 'UPDATE promo SET used = used + 1, updated_at = ? WHERE id = ? AND (maxuses = 0 OR maxuses IS NULL OR maxuses > used)', + [date('Y-m-d H:i:s'), $promo->id] + ); + if ($affectedRows === 0) { + throw new \FOSSBilling\InformationException('This promo code has reached its maximum number of uses.'); + } } public function findActivePromoByCode($code) @@ -740,6 +779,7 @@ class Service implements InjectionAwareInterface protected function getRelatedItemsDiscount(\Model_Cart $cart, \Model_CartProduct $model) { $product = $this->di['db']->load('Product', $model->product_id); + $product->setDi($this->di); $repo = $product->getTable(); $config = $this->getItemConfig($model); @@ -761,6 +801,7 @@ class Service implements InjectionAwareInterface private function getItemTitle(\Model_CartProduct $model) { $product = $this->di['db']->load('Product', $model->product_id); + $product->setDi($this->di); $config = $this->getItemConfig($model); $service = $product->getService(); if (method_exists($service, 'getCartProductTitle')) { @@ -773,6 +814,7 @@ class Service implements InjectionAwareInterface protected function getItemPromoDiscount(\Model_CartProduct $model, \Model_Promo $promo) { $product = $this->di['db']->load('Product', $model->product_id); + $product->setDi($this->di); $repo = $this->di['mod_service']('product'); $config = $this->getItemConfig($model); @@ -787,11 +829,13 @@ class Service implements InjectionAwareInterface public function cartProductToApiArray(\Model_CartProduct $model): array { $product = $this->di['db']->load('Product', $model->product_id); + $product->setDi($this->di); $repo = $product->getTable(); $config = $this->getItemConfig($model); - $setup = $repo->getProductSetupPrice($product, $config); - $price = $repo->getProductPrice($product, $config); - $qty = $config['quantity'] ?? 1; + $line = $repo->getOrderLineConfig($product, $config); + $setup = $line['setup_price']; + $price = $line['price']; + $qty = $line['quantity']; [$discount_price, $discount_setup] = $this->getProductDiscount($model, $setup); diff --git a/src/modules/Client/Api/Guest.php b/src/modules/Client/Api/Guest.php index 01d1347d0..274b8c59c 100644 --- a/src/modules/Client/Api/Guest.php +++ b/src/modules/Client/Api/Guest.php @@ -25,7 +25,6 @@ class Guest extends \Api_Abstract * * @optional bool $auto_login - Auto login client after signup * @optional string $last_name - last name - * @optional string $aid - Alternative id. Usually used by import tools. * @optional string $gender - Gender - values: male|female|nonbinary|other * @optional string $country - Country * @optional string $city - city @@ -42,7 +41,6 @@ class Guest extends \Api_Abstract * @optional string $phone_cc - Phone country code * @optional string $document_type - Related document type, ie: passport, driving license * @optional string $document_nr - Related document number, ie: passport number: LC45698122 - * @optional string $notes - Notes about client. Visible for admin only * @optional string $custom_1 - Custom field 1 * @optional string $custom_2 - Custom field 2 * @optional string $custom_3 - Custom field 3 diff --git a/src/modules/Client/Controller/Client.php b/src/modules/Client/Controller/Client.php index 64b02ccb7..bf6ddf96b 100644 --- a/src/modules/Client/Controller/Client.php +++ b/src/modules/Client/Controller/Client.php @@ -44,8 +44,13 @@ class Client implements \FOSSBilling\InjectionAwareInterface public function get_client_confirmation(\Box_App $app, $hash): never { + $startTime = hrtime(true); $service = $this->di['mod_service']('client'); $service->approveClientEmailByHash($hash); + $elapsed = (hrtime(true) - $startTime) / 1_000_000; + if ($elapsed < 50) { + usleep(random_int((int) (50_000 - $elapsed * 1000), 100_000)); + } $systemService = $this->di['mod_service']('System'); $systemService->setPendingMessage(__trans('Email address was confirmed')); $app->redirect('/'); @@ -75,11 +80,29 @@ class Client implements \FOSSBilling\InjectionAwareInterface ]; $template = 'mod_client_set_new_password'; - // Call password_reset_valid function and if true, then render the template, otherwise redirect to the index page + $apiService = $this->di['mod_service']('api'); + $ip = $this->di['request']->getClientIp(); + $apiConfig = \FOSSBilling\Config::getProperty('api', []); + $loginSpan = $apiConfig['rate_span_login'] ?? 60; + $loginLimit = $apiConfig['rate_limit_login'] ?? 20; + $requestPrefix = 'page:/client/reset-password-confirm'; + + if ($apiService->isRateLimited($ip, $loginLimit, $loginSpan, $requestPrefix)) { + usleep(random_int(50000, 100000)); + $app->redirect('/'); + } + + $startTime = hrtime(true); $result = $service->password_reset_valid($data); if ($result !== false) { return $app->render($template); } + + $elapsed = (hrtime(true) - $startTime) / 1_000_000; + if ($elapsed < 50) { + usleep(random_int((int) (50_000 - $elapsed * 1000), 100_000)); + } + $app->redirect('/'); } } diff --git a/src/modules/Client/Service.php b/src/modules/Client/Service.php index 1d647faa7..5f8ce8718 100644 --- a/src/modules/Client/Service.php +++ b/src/modules/Client/Service.php @@ -635,12 +635,29 @@ class Service implements InjectionAwareInterface $event_params['ip'] = $this->di['request']->getClientIp(); $this->di['events_manager']->fire(['event' => 'onBeforeClientSignUp', 'params' => $event_params]); - $data['ip'] = $this->di['request']->getClientIp(); - $data['status'] = \Model_Client::ACTIVE; - $client = $this->createClient($data); + $allowedFields = [ + 'email', 'first_name', 'last_name', 'password', + 'phone', 'phone_cc', 'gender', 'birthday', + 'company', 'company_vat', 'company_number', 'type', + 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', + 'document_type', 'document_nr', + 'custom_1', 'custom_2', 'custom_3', 'custom_4', 'custom_5', + 'custom_6', 'custom_7', 'custom_8', 'custom_9', 'custom_10', + ]; + + $safeData = [ + 'ip' => $this->di['request']->getClientIp(), + 'status' => \Model_Client::ACTIVE, + ]; + foreach ($allowedFields as $field) { + if (array_key_exists($field, $data)) { + $safeData[$field] = $data[$field]; + } + } + + $client = $this->createClient($safeData); $event_params['id'] = $client->id; - $this->di['events_manager']->fire(['event' => 'onAfterClientSignUp', 'params' => $event_params]); $this->di['logger']->info('Client #%s signed up', $client->id); diff --git a/src/modules/Formbuilder/templates/admin/mod_formbuilder_manage.html.twig b/src/modules/Formbuilder/templates/admin/mod_formbuilder_manage.html.twig index 7511844e6..3960c3bf8 100644 --- a/src/modules/Formbuilder/templates/admin/mod_formbuilder_manage.html.twig +++ b/src/modules/Formbuilder/templates/admin/mod_formbuilder_manage.html.twig @@ -77,9 +77,14 @@ {% endfor %} {% elseif field.type == "textarea" %} - {% endif %} diff --git a/src/modules/Formbuilder/templates/admin/mod_formbuilder_preview.html.twig b/src/modules/Formbuilder/templates/admin/mod_formbuilder_preview.html.twig index 71c1eee27..b581abde5 100644 --- a/src/modules/Formbuilder/templates/admin/mod_formbuilder_preview.html.twig +++ b/src/modules/Formbuilder/templates/admin/mod_formbuilder_preview.html.twig @@ -72,7 +72,13 @@ {% endif %} {% elseif field.type == "textarea" %} - + {% set textarea_width = field.options.width|default(null) %} + {% set textarea_height = field.options.height|default(null) %} + {% endif %}
diff --git a/src/modules/Formbuilder/templates/client/mod_formbuilder_build.html.twig b/src/modules/Formbuilder/templates/client/mod_formbuilder_build.html.twig index ab8024055..203067558 100644 --- a/src/modules/Formbuilder/templates/client/mod_formbuilder_build.html.twig +++ b/src/modules/Formbuilder/templates/client/mod_formbuilder_build.html.twig @@ -79,7 +79,12 @@ {% endfor %} {% elseif field.type == "textarea" %} - diff --git a/src/modules/Invoice/Service.php b/src/modules/Invoice/Service.php index e1ca18a86..d4fc0cf97 100644 --- a/src/modules/Invoice/Service.php +++ b/src/modules/Invoice/Service.php @@ -365,6 +365,22 @@ class Service implements InjectionAwareInterface $params = $event->getParameters(); $di = $event->getDi(); + try { + if (($params['total'] ?? 0) > 0 + && ($params['status'] ?? null) !== \Model_Invoice::STATUS_PAID + && isset($params['client']['id']) + ) { + $email = []; + $email['to_client'] = $params['client']['id']; + $email['code'] = 'mod_invoice_created'; + $email['invoice'] = $params; + $emailService = $di['mod_service']('email'); + $emailService->sendTemplate($email); + } + } catch (\Exception $exc) { + error_log($exc->getMessage()); + } + return true; } @@ -381,7 +397,7 @@ class Service implements InjectionAwareInterface $email['to_client'] = $invoiceModel->client_id; $email['code'] = 'mod_invoice_payment_reminder'; $email['invoice'] = $invoice; - $emailService = $di['mod_service']('Email'); + $emailService = $di['mod_service']('email'); $emailService->sendTemplate($email); } catch (\Exception $exc) { error_log($exc->getMessage()); @@ -644,12 +660,12 @@ class Service implements InjectionAwareInterface $invoice->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($invoice); - $this->di['events_manager']->fire(['event' => 'onAfterAdminInvoiceApprove', 'params' => $this->toApiArray($invoice)]); - if (isset($data['use_credits']) && $data['use_credits']) { $this->tryPayWithCredits($invoice); } + $this->di['events_manager']->fire(['event' => 'onAfterAdminInvoiceApprove', 'params' => $this->toApiArray($invoice)]); + $this->di['logger']->info("Approved invoice {$invoice->id}."); return true; @@ -1040,9 +1056,40 @@ class Service implements InjectionAwareInterface $this->setInvoiceDefaults($proforma); $price = $order->price; + $line = [ + 'price' => $order->price, + 'quantity' => $order->quantity, + ]; + + if (in_array($order->status, [ + \Model_ClientOrder::STATUS_ACTIVE, + \Model_ClientOrder::STATUS_FAILED_RENEW, + \Model_ClientOrder::STATUS_SUSPENDED, + ], true)) { + $product = $this->di['db']->getExistingModelById('Product', $order->product_id, 'Product not found'); + $product->setDi($this->di); + $repo = $product->getTable(); + $config = json_decode($order->config ?? '', true) ?? []; + + if (method_exists($repo, 'getRenewalLineConfig')) { + $currencyService = $this->di['mod_service']('Currency'); + $currencyRepository = $currencyService->getCurrencyRepository(); + $rate = $currencyRepository->getRateByCode($order->currency); + if ($rate === null) { + throw new \FOSSBilling\Exception("Currency rate for '{$order->currency}' is not configured"); + } + + $renewalLine = $repo->getRenewalLineConfig($product, $config); + $price = $renewalLine['price'] * $rate; + $line = [ + 'price' => $price, + 'quantity' => $renewalLine['quantity'], + ]; + } + } $invoiceItemService = $this->di['mod_service']('Invoice', 'InvoiceItem'); - $invoiceItemService->generateFromOrder($proforma, $order, \Model_InvoiceItem::TASK_RENEW, $price); + $invoiceItemService->generateFromOrder($proforma, $order, \Model_InvoiceItem::TASK_RENEW, $price, $line); // invoice due date if ($due_days > 0) { diff --git a/src/modules/Invoice/ServiceInvoiceItem.php b/src/modules/Invoice/ServiceInvoiceItem.php index c96b84dfc..d9cc64c17 100644 --- a/src/modules/Invoice/ServiceInvoiceItem.php +++ b/src/modules/Invoice/ServiceInvoiceItem.php @@ -269,13 +269,16 @@ class ServiceInvoiceItem implements InjectionAwareInterface $this->di['db']->store($item); } - public function generateFromOrder(\Model_Invoice $proforma, \Model_ClientOrder $order, $task, $price): void + public function generateFromOrder(\Model_Invoice $proforma, \Model_ClientOrder $order, $task, $price, array $line = []): void { $corderService = $this->di['mod_service']('Order'); $clientService = $this->di['mod_service']('client'); $client = $this->di['db']->load('Client', $order->client_id); $taxed = $clientService->isClientTaxable($client); + $quantity = $line['quantity'] ?? $order->quantity; + $unit = $line['unit'] ?? $order->unit; + $period = $line['period'] ?? $order->period; $pi = $this->di['db']->dispense('InvoiceItem'); $pi->invoice_id = $proforma->id; @@ -284,9 +287,9 @@ class ServiceInvoiceItem implements InjectionAwareInterface $pi->task = $task; $pi->status = \Model_InvoiceItem::STATUS_PENDING_PAYMENT; $pi->title = $order->title; - $pi->period = $order->period; - $pi->quantity = $order->quantity; - $pi->unit = $order->unit; + $pi->period = $period; + $pi->quantity = $quantity; + $pi->unit = $unit; $pi->price = $price; $pi->taxed = $taxed; $pi->created_at = date('Y-m-d H:i:s'); @@ -297,8 +300,26 @@ class ServiceInvoiceItem implements InjectionAwareInterface // apply discount for new invoice if promo code is recurrent if ($order->promo_recurring) { - $order_total = $order->price * $order->quantity; + $order_total = $price * $quantity; $promo_discount = $order->discount; + + $product = $this->di['db']->getExistingModelById('Product', $order->product_id, 'Product not found'); + if ($product->type === \Model_ProductTable::DOMAIN && $order->promo_id) { + $promo = $this->di['db']->getExistingModelById('Promo', $order->promo_id, 'Promo not found'); + $productService = $this->di['mod_service']('Product'); + $config = json_decode($order->config ?? '', true) ?? []; + $promo_discount = $productService->getRenewalProductDiscount($product, $promo, $config); + + $currencyService = $this->di['mod_service']('Currency'); + $currencyRepository = $currencyService->getCurrencyRepository(); + $rate = $currencyRepository->getRateByCode($order->currency); + if ($rate === null) { + throw new \FOSSBilling\Exception("Currency conversion rate cannot be determined for code {$order->currency}"); + } + + $promo_discount *= $rate; + } + if ($promo_discount > $order_total) { $promo_discount = $order_total; } diff --git a/src/modules/Invoice/ServiceSubscription.php b/src/modules/Invoice/ServiceSubscription.php index 61284b167..6ea6c0004 100644 --- a/src/modules/Invoice/ServiceSubscription.php +++ b/src/modules/Invoice/ServiceSubscription.php @@ -186,48 +186,12 @@ class ServiceSubscription implements InjectionAwareInterface public function isSubscribable($invoice_id): bool { - $query = 'SELECT COUNT(id) as cc - FROM invoice_item - WHERE invoice_id = :id - GROUP BY invoice_id - '; - $count = $this->di['db']->getCell($query, ['id' => $invoice_id]); - if ($count > 1) { - return false; - } - - // check if first invoice line has denied period - $query = 'SELECT id, period - FROM invoice_item - WHERE invoice_id = :id - LIMIT 1 - '; - $list = $this->di['db']->getAll($query, [':id' => $invoice_id]); - - if ( - isset($list[0]) - && isset($list[0]['period']) - && !empty($list[0]['period']) - ) { - return true; - } - - return false; + return $this->getSubscriptionPeriodByInvoiceId((int) $invoice_id) !== null; } public function getSubscriptionPeriod(\Model_Invoice $invoice) { - if (!$this->isSubscribable($invoice->id)) { - return null; - } - - $query = 'SELECT period - FROM invoice_item - WHERE invoice_id = :id - LIMIT 1 - '; - - return $this->di['db']->getCell($query, ['id' => $invoice->id]); + return $this->getSubscriptionPeriodByInvoiceId((int) $invoice->id); } public function unsubscribe(\Model_Subscription $model): void @@ -236,4 +200,42 @@ class ServiceSubscription implements InjectionAwareInterface $model->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($model); } + + private function getSubscriptionPeriodByInvoiceId(int $invoiceId): ?string + { + $query = 'SELECT period, price, quantity + FROM invoice_item + WHERE invoice_id = :id + ORDER BY id ASC'; + $items = $this->di['db']->getAll($query, [':id' => $invoiceId]); + + if (empty($items)) { + return null; + } + + $subscriptionPeriod = null; + foreach ($items as $item) { + $lineTotal = (float) ($item['price'] ?? 0) * (float) ($item['quantity'] ?? 0); + $period = $item['period'] ?? null; + + if ($lineTotal <= 0) { + continue; + } + + if (empty($period)) { + return null; + } + + if ($subscriptionPeriod === null) { + $subscriptionPeriod = $period; + continue; + } + + if ($subscriptionPeriod !== $period) { + return null; + } + } + + return $subscriptionPeriod; + } } diff --git a/src/modules/Order/Service.php b/src/modules/Order/Service.php index 0dedcf49f..019b47b58 100644 --- a/src/modules/Order/Service.php +++ b/src/modules/Order/Service.php @@ -692,7 +692,6 @@ class Service implements InjectionAwareInterface $order->group_master = ($parent_order) ? 0 : 1; $order->title = $generatedOrderTitle ?? $data['title'] ?? $product->title; $order->currency = $currency->getCode(); - $order->quantity = $qty; $order->service_type = $product->type; $order->unit = $product->unit; $order->status = \Model_ClientOrder::STATUS_PENDING_SETUP; @@ -704,15 +703,24 @@ class Service implements InjectionAwareInterface $order->period = $bp->getCode(); } + $line = null; + if (!isset($data['price']) || $product->type === \Model_Product::DOMAIN) { + $product->setDi($this->di); + $repo = $product->getTable(); + $line = $repo->getOrderLineConfig($product, array_merge($config, ['quantity' => $qty])); + $order->quantity = $line['quantity']; + } else { + $order->quantity = $qty; + } + if (isset($data['price'])) { $order->price = $data['price']; } else { - $repo = $product->getTable(); $rate = $currencyRepository->getRateByCode($currency->getCode()); if ($rate === null) { throw new \FOSSBilling\Exception("Currency rate for '{$currency->getCode()}' is not configured"); } - $order->price = $repo->getProductPrice($product, $config) * $rate; + $order->price = $line['price'] * $rate; } $order->notes = $data['notes'] ?? $order->notes; @@ -941,6 +949,9 @@ class Service implements InjectionAwareInterface public function stockSale(\Model_Product $product, $qty): bool { if ($product->stock_control) { + if ($product->quantity_in_stock < $qty) { + throw new InformationException('Product :id is out of stock.', [':id' => $product->id], 831); + } $product->quantity_in_stock -= $qty; $product->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($product); @@ -1075,13 +1086,6 @@ class Service implements InjectionAwareInterface throw $e; } - // do not extend renewal date if this is first paid invoice - $invoiceService = $this->di['mod_service']('invoice'); - $paidInvoices = $invoiceService->findPaidInvoicesForOrder($order); - if (count($paidInvoices) <= 1) { - return; - } - // set automatic order expiration if (!empty($order->period)) { $from_time = ($order->expires_at === null) ? time() : strtotime($order->expires_at); // from expiration date diff --git a/src/modules/Orderbutton/templates/client/mod_orderbutton_product_configuration.html.twig b/src/modules/Orderbutton/templates/client/mod_orderbutton_product_configuration.html.twig index d962ca69f..999c756e9 100644 --- a/src/modules/Orderbutton/templates/client/mod_orderbutton_product_configuration.html.twig +++ b/src/modules/Orderbutton/templates/client/mod_orderbutton_product_configuration.html.twig @@ -50,18 +50,24 @@ {% endif %}
- {# TODO: This does not seem to be implemented on the back-end {% if product.allow_quantity_select %}
{{ 'Quantity'|trans }}
- +
{% endif %} - #} {% endset %} diff --git a/src/modules/Product/Service.php b/src/modules/Product/Service.php index 066e0175a..e9ada5143 100644 --- a/src/modules/Product/Service.php +++ b/src/modules/Product/Service.php @@ -1012,15 +1012,16 @@ class Service implements InjectionAwareInterface } } + $product->setDi($this->di); $repo = $product->getTable(); - $price = $repo->getProductPrice($product, $config); + $line = $repo->getOrderLineConfig($product, $config); + $price = $line['price'] * $line['quantity']; if ($price == 0) { return 0; } $discount = 0; - $quantity = 1; switch ($promo->type) { case \Model_Promo::ABSOLUTE: @@ -1029,11 +1030,7 @@ class Service implements InjectionAwareInterface break; case \Model_Promo::PERCENTAGE: - if (isset($config['quantity']) && is_numeric($config['quantity'])) { - $quantity = $config['quantity']; - } - - $discount += round($price * $quantity * $promo->value / 100, 2); + $discount += round($price * $promo->value / 100, 2); break; @@ -1044,6 +1041,39 @@ class Service implements InjectionAwareInterface return $discount; } + public function getRenewalProductDiscount(\Model_Product $product, \Model_Promo $promo, ?array $config = null): float + { + if (!$this->isPromoLinkedToProduct($promo, $product)) { + return 0; + } + + if (isset($config['period'])) { + $periods = $this->getPeriods($promo); + if (!empty($periods) && !in_array($config['period'], $periods)) { + return 0; + } + } + + $product->setDi($this->di); + $repo = $product->getTable(); + if (!method_exists($repo, 'getRenewalLineConfig')) { + return $this->getProductDiscount($product, $promo, $config); + } + + $line = $repo->getRenewalLineConfig($product, $config); + $price = $line['price'] * $line['quantity']; + + if ($price == 0) { + return 0; + } + + return match ($promo->type) { + \Model_Promo::ABSOLUTE => (float) $promo->value, + \Model_Promo::PERCENTAGE => round($price * $promo->value / 100, 2), + default => 0, + }; + } + public function isPromoLinkedToTld(\Model_Promo $promo, \Model_Tld $tld): bool { foreach ($promo->PromoItem as $item) { diff --git a/src/modules/Redirect/Api/Admin.php b/src/modules/Redirect/Api/Admin.php index 0e0c13500..5b62f728b 100644 --- a/src/modules/Redirect/Api/Admin.php +++ b/src/modules/Redirect/Api/Admin.php @@ -49,8 +49,8 @@ class Admin extends \Api_Abstract $this->di['mod_service']('Staff')->checkPermissionsAndThrowException('redirect', 'create_and_edit'); $id = $this->getService()->create( - trim(htmlspecialchars((string) $data['path'], ENT_QUOTES | ENT_HTML5, 'UTF-8'), '/'), - trim(htmlspecialchars((string) $data['target'], ENT_QUOTES | ENT_HTML5, 'UTF-8'), '/') + (string) $data['path'], + (string) $data['target'] ); $this->di['logger']->info('Created new redirect #%s', $id); diff --git a/src/modules/Redirect/Controller/Client.php b/src/modules/Redirect/Controller/Client.php index de360db40..8135896f8 100644 --- a/src/modules/Redirect/Controller/Client.php +++ b/src/modules/Redirect/Controller/Client.php @@ -51,8 +51,27 @@ class Client implements \FOSSBilling\InjectionAwareInterface { $service = $this->di['mod_service']('redirect'); $target = $service->getRedirectByPath($app->uri); - header('HTTP/1.1 301 Moved Permanently'); - header('Location: ' . $target); + + if ($target === null || !$this->isTargetAllowed($target)) { + http_response_code(404); + exit; + } + + header('Location: ' . $target, true, 301); exit; } + + private function isTargetAllowed(string $target): bool + { + if (trim($target) === '' || strpbrk($target, "\r\n") !== false) { + return false; + } + + $scheme = parse_url($target, PHP_URL_SCHEME); + if (is_string($scheme) && !in_array(strtolower($scheme), ['http', 'https'], true)) { + return false; + } + + return true; + } } diff --git a/src/modules/Redirect/Service.php b/src/modules/Redirect/Service.php index 2a1028690..c3dfba381 100644 --- a/src/modules/Redirect/Service.php +++ b/src/modules/Redirect/Service.php @@ -14,6 +14,7 @@ namespace Box\Mod\Redirect; use Box\Mod\Extension\Entity\ExtensionMeta; use Box\Mod\Extension\Repository\ExtensionMetaRepository; +use FOSSBilling\Exception; class Service implements \FOSSBilling\InjectionAwareInterface { @@ -54,7 +55,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface { if ($this->extensionMetaRepository === null) { if ($this->di === null) { - throw new \FOSSBilling\Exception('The dependency injection container has not been set.'); + throw new Exception('The dependency injection container has not been set.'); } $this->extensionMetaRepository = $this->di['em']->getRepository(ExtensionMeta::class); @@ -81,7 +82,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface { $redirect = $this->getExtensionMetaRepository()->findOneByExtensionAndId('mod_redirect', $id); if (!$redirect instanceof ExtensionMeta) { - throw new \FOSSBilling\Exception('Redirect not found'); + throw new Exception('Redirect not found'); } return $redirect; @@ -89,6 +90,9 @@ class Service implements \FOSSBilling\InjectionAwareInterface public function create(string $path, string $target): int { + $path = $this->validatePath($path); + $target = $this->validateTarget($target); + $redirect = (new ExtensionMeta()) ->setExtension('mod_redirect') ->setMetaKey($path) @@ -99,7 +103,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface $id = $redirect->getId(); if ($id === null) { - throw new \FOSSBilling\Exception('Failed to create redirect.'); + throw new Exception('Failed to create redirect.'); } return $id; @@ -107,9 +111,13 @@ class Service implements \FOSSBilling\InjectionAwareInterface public function update(ExtensionMeta $redirect, array $data): bool { - $redirect - ->setMetaKey(trim(htmlspecialchars((string) ($data['path'] ?? $redirect->getMetaKey()), ENT_QUOTES | ENT_HTML5, 'UTF-8'), '/')) - ->setMetaValue(trim(htmlspecialchars((string) ($data['target'] ?? $redirect->getMetaValue()), ENT_QUOTES | ENT_HTML5, 'UTF-8'), '/')); + if (isset($data['path'])) { + $redirect->setMetaKey($this->validatePath((string) $data['path'])); + } + + if (isset($data['target'])) { + $redirect->setMetaValue($this->validateTarget((string) $data['target'])); + } $this->di['em']->flush(); @@ -132,4 +140,35 @@ class Service implements \FOSSBilling\InjectionAwareInterface 'target' => $redirect->getMetaValue(), ]; } + + public function validateTarget(string $target): string + { + $target = trim($target); + + if ($target === '' || strpbrk($target, "\r\n") !== false) { + throw new Exception('Invalid redirect target.'); + } + + $scheme = parse_url($target, PHP_URL_SCHEME); + if (is_string($scheme) && !in_array(strtolower($scheme), ['http', 'https'], true)) { + throw new Exception('Only HTTP and HTTPS redirect targets are allowed.'); + } + + return $target; + } + + public function validatePath(string $path): string + { + $path = trim($path, '/'); + + if ($path === '' || strpbrk($path, "\r\n") !== false) { + throw new Exception('Invalid redirect path.'); + } + + if (str_contains($path, '..')) { + throw new Exception('Redirect path must not contain path traversal sequences.'); + } + + return $path; + } } diff --git a/src/modules/Redirect/templates/admin/mod_redirect_settings.html.twig b/src/modules/Redirect/templates/admin/mod_redirect_settings.html.twig index 3b83372ac..17006baa2 100644 --- a/src/modules/Redirect/templates/admin/mod_redirect_settings.html.twig +++ b/src/modules/Redirect/templates/admin/mod_redirect_settings.html.twig @@ -48,7 +48,7 @@ {{ ''|link }} - + diff --git a/src/modules/Servicedomain/Service.php b/src/modules/Servicedomain/Service.php index 631706265..7408ef793 100644 --- a/src/modules/Servicedomain/Service.php +++ b/src/modules/Servicedomain/Service.php @@ -146,7 +146,6 @@ class Service implements \FOSSBilling\InjectionAwareInterface // return by reference $data['period'] = $years . 'Y'; - $data['quantity'] = $years; } } diff --git a/src/modules/Staff/Controller/Admin.php b/src/modules/Staff/Controller/Admin.php index 56a218183..294d03eb1 100644 --- a/src/modules/Staff/Controller/Admin.php +++ b/src/modules/Staff/Controller/Admin.php @@ -114,19 +114,35 @@ class Admin implements InjectionAwareInterface { $data = []; $this->di['events_manager']->fire(['event' => 'onBeforePasswordResetStaff']); + + $apiService = $this->di['mod_service']('api'); + $ip = $this->di['request']->getClientIp(); + $apiConfig = \FOSSBilling\Config::getProperty('api', []); + $loginSpan = $apiConfig['rate_span_login'] ?? 60; + $loginLimit = $apiConfig['rate_limit_login'] ?? 20; + + if ($apiService->isRateLimited($ip, $loginLimit, $loginSpan, 'page:/staff/email/')) { + usleep(random_int(50000, 100000)); + + return $app->render('mod_staff_password_reset'); + } + $mod = $this->di['mod']('staff'); $config = $mod->getConfig(); if (isset($config['public']['reset_pw']) && $config['public']['reset_pw'] == '0') { - throw new \FOSSBilling\InformationException('Password reset has been disabled'); + return $app->render('mod_staff_password_reset'); } - // send confirmation email $service = $this->di['mod_service']('staff'); $reset = $this->di['db']->findOne('AdminPasswordReset', 'hash = ?', [$hash]); if (!$reset instanceof \Model_AdminPasswordReset) { - throw new \FOSSBilling\InformationException('The link has expired or you have already confirmed the password reset.'); + usleep(random_int(50000, 100000)); + + return $app->render('mod_staff_password_reset'); } if (strtotime($reset->created_at) - time() + 900 < 0) { - throw new \FOSSBilling\InformationException('The link has expired or you have already confirmed the password reset.'); + usleep(random_int(50000, 100000)); + + return $app->render('mod_staff_password_reset'); } $admin = $this->di['db']->getExistingModelById('Admin', $reset->admin_id, 'User not found'); $data['hash'] = $reset->hash; diff --git a/src/modules/Staff/Service.php b/src/modules/Staff/Service.php index 25ebb6176..957f71d83 100644 --- a/src/modules/Staff/Service.php +++ b/src/modules/Staff/Service.php @@ -212,17 +212,36 @@ class Service implements InjectionAwareInterface $extensionService = $this->di['mod_service']('Extension'); $modulePermissions = $extensionService->getSpecificModulePermissions($module); $permissions = $this->getPermissions($member->id); + $defaultPermissions = $permissions['default'] ?? []; + $hasWildcardAccess = is_array($defaultPermissions) && (bool) ($defaultPermissions['all'] ?? false); $canAlwaysAccess = $modulePermissions['can_always_access'] ?? false; if (!$canAlwaysAccess) { // They have no permissions or don't have any access to that module - if (empty($permissions) || !array_key_exists($module, $permissions) || !is_array($permissions[$module]) || !($permissions[$module]['access'] ?? false)) { + if ( + empty($permissions) + || ( + !array_key_exists($module, $permissions) + && !$hasWildcardAccess + ) + || ( + array_key_exists($module, $permissions) + && ( + !is_array($permissions[$module]) + || !($permissions[$module]['access'] ?? false) + ) + ) + ) { return false; } } if (!is_null($key)) { + if (!array_key_exists($module, $permissions) && $hasWildcardAccess) { + return true; + } + $modulePermissions = $permissions[$module] ?? []; if (!is_array($modulePermissions) || !array_key_exists($key, $modulePermissions)) { diff --git a/src/modules/Staff/templates/admin/mod_staff_manage.html.twig b/src/modules/Staff/templates/admin/mod_staff_manage.html.twig index d415ba027..560257aff 100644 --- a/src/modules/Staff/templates/admin/mod_staff_manage.html.twig +++ b/src/modules/Staff/templates/admin/mod_staff_manage.html.twig @@ -144,7 +144,7 @@ {% set prms = admin.staff_permissions_get({ 'id': staff.id }) %}
- + {% for modName, mod in mods|filter(mod => mod.permissions.hide_permissions is not true) %}
@@ -248,6 +248,24 @@ element.checked = check; } }); + + const wildcardInput = document.getElementById('permissions-default-all'); + if (wildcardInput) { + wildcardInput.value = check ? '1' : ''; + } } + + document.addEventListener('DOMContentLoaded', function () { + const wildcardInput = document.getElementById('permissions-default-all'); + if (!wildcardInput) { + return; + } + + document.querySelectorAll('.permission-box, .permission-select').forEach((element) => { + element.addEventListener('change', function () { + wildcardInput.value = ''; + }); + }); + }); {% endblock %} diff --git a/tests-legacy/library/Model/ProductDomainTableTest.php b/tests-legacy/library/Model/ProductDomainTableTest.php new file mode 100644 index 000000000..1bcaae1ad --- /dev/null +++ b/tests-legacy/library/Model/ProductDomainTableTest.php @@ -0,0 +1,110 @@ +table = new Model_ProductDomainTable(); + } + + public function testGetOrderLineConfigUsesRegistrationAndRenewalPricing(): void + { + $tld = new Model_Tld(); + $tld->loadBean(new DummyBean()); + $tld->tld = '.com'; + $tld->price_registration = 13; + $tld->price_renew = 20; + $tld->price_transfer = 15; + + $tldService = $this->getMockBuilder(\Box\Mod\Servicedomain\ServiceTld::class) + ->disableOriginalConstructor() + ->onlyMethods(['findOneByTld']) + ->getMock(); + $tldService->expects($this->atLeastOnce()) + ->method('findOneByTld') + ->with('.com') + ->willReturn($tld); + + $di = $this->getDi(); + $di['period'] = $di->protect(fn (string $period): Box_Period => new Box_Period($period)); + $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $tldService); + $this->table->setDi($di); + + $product = new Model_Product(); + $product->loadBean(new DummyBean()); + + $line = $this->table->getOrderLineConfig($product, [ + 'action' => 'register', + 'register_tld' => '.com', + 'register_years' => 2, + 'period' => '2Y', + ]); + + $renewal = $this->table->getRenewalLineConfig($product, [ + 'action' => 'register', + 'register_tld' => '.com', + 'register_years' => 2, + 'period' => '2Y', + ]); + + $this->assertSame(['price' => 33.0, 'quantity' => 1, 'setup_price' => 0.0], $line); + $this->assertSame(['price' => 20.0, 'quantity' => 2], $renewal); + } + + public function testGetRelatedDiscountUsesRenewalPricingForFreeMultiYearDomain(): void + { + $tld = new Model_Tld(); + $tld->loadBean(new DummyBean()); + $tld->tld = '.com'; + $tld->price_registration = 13; + $tld->price_renew = 20; + $tld->price_transfer = 15; + + $tldService = $this->getMockBuilder(\Box\Mod\Servicedomain\ServiceTld::class) + ->disableOriginalConstructor() + ->onlyMethods(['findOneByTld']) + ->getMock(); + $tldService->expects($this->once()) + ->method('findOneByTld') + ->with('.com') + ->willReturn($tld); + + $di = $this->getDi(); + $di['period'] = $di->protect(fn (string $period): Box_Period => new Box_Period($period)); + $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $tldService); + $this->table->setDi($di); + + $product = new Model_Product(); + $product->loadBean(new DummyBean()); + + $discount = $this->table->getRelatedDiscount([ + [ + 'config' => [ + 'action' => 'register', + 'domain' => [ + 'action' => 'register', + 'register_sld' => 'example', + 'register_tld' => '.com', + ], + 'free_domain' => true, + 'free_domain_periods' => ['2Y'], + 'period' => '2Y', + ], + ], + ], $product, [ + 'action' => 'register', + 'register_sld' => 'example', + 'register_tld' => '.com', + 'period' => '2Y', + ]); + + $this->assertSame(33.0, $discount); + } +} diff --git a/tests-legacy/modules/Api/Controller/ClientTest.php b/tests-legacy/modules/Api/Controller/ClientTest.php index 340846e2f..144d2c04f 100644 --- a/tests-legacy/modules/Api/Controller/ClientTest.php +++ b/tests-legacy/modules/Api/Controller/ClientTest.php @@ -145,14 +145,22 @@ final class ClientTest extends \BBTestCase $this->assertSame([], $controller->calls); } - private function createController(): TestableClient + public function testRateLimitExceededReturns429(): void + { + $controller = $this->createController(rateLimited: true); + $controller->hasValidSession = false; + + $this->expectException(InformationException::class); + $this->expectExceptionCode(429); + + $this->invokeApiCall($controller, 'guest', 'test', 'testMethod', []); + } + + private function createController(bool $rateLimited = false): TestableClient { $service = $this->createMock(\Box\Mod\Api\Service::class); - $service->expects($this->once()) - ->method('logRequest'); - $service->expects($this->once()) - ->method('getRequestCount') - ->willReturn(0); + $service->method('getRemainingRequests') + ->willReturn($rateLimited ? 0 : 100); $request = $this->createMock(Request::class); $request->expects($this->atLeastOnce()) diff --git a/tests-legacy/modules/Api/ControllerClientTest.php b/tests-legacy/modules/Api/ControllerClientTest.php index f09568e51..071c21210 100644 --- a/tests-legacy/modules/Api/ControllerClientTest.php +++ b/tests-legacy/modules/Api/ControllerClientTest.php @@ -55,6 +55,29 @@ final class ControllerClientTest extends \BBTestCase $this->assertFalse($result); } + public function testShouldUseTokenLoginReturnsFalseWhenOnlyUsernameSet(): void + { + $controller = new Client(); + + $_SERVER['PHP_AUTH_USER'] = 'client'; + + $result = $this->invokePrivate($controller, 'shouldUseTokenLogin', ['client']); + + $this->assertFalse($result); + } + + public function testShouldUseTokenLoginReturnsTrueWhenBothUsernameAndPasswordSet(): void + { + $controller = new Client(); + + $_SERVER['PHP_AUTH_USER'] = 'client'; + $_SERVER['PHP_AUTH_PW'] = 'some-token'; + + $result = $this->invokePrivate($controller, 'shouldUseTokenLogin', ['client']); + + $this->assertTrue($result); + } + public function testShouldUseTokenLoginRejectsRouteRoleMismatch(): void { $controller = new Client(); diff --git a/tests-legacy/modules/Api/ServiceTest.php b/tests-legacy/modules/Api/ServiceTest.php index 884107c3f..7bf5f7022 100644 --- a/tests-legacy/modules/Api/ServiceTest.php +++ b/tests-legacy/modules/Api/ServiceTest.php @@ -45,4 +45,32 @@ final class ServiceTest extends \BBTestCase $this->assertIsInt($result); $this->assertEquals($requestNumber, $result); } + + public function testGetRequestCountFiltersByRequestPrefix(): void + { + $since = 674_690_401; + $ip = '1.2.3.4'; + $requestPrefix = 'api:/api/guest/client/login'; + + $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->once()) + ->method('getCell') + ->with( + $this->stringContains('request LIKE :request_prefix'), + $this->callback(function (array $values) use ($ip, $requestPrefix): bool { + return $values['ip'] === $ip + && $values['request_prefix'] === $requestPrefix . '%' + && isset($values['since']); + }) + ) + ->willReturn(3); + + $di = $this->getDi(); + $di['db'] = $dbMock; + + $this->service->setDi($di); + $result = $this->service->getRequestCount($since, $ip, $requestPrefix); + + $this->assertSame(3, $result); + } } diff --git a/tests-legacy/modules/Cart/DomainPricingTest.php b/tests-legacy/modules/Cart/DomainPricingTest.php new file mode 100644 index 000000000..5bca270fe --- /dev/null +++ b/tests-legacy/modules/Cart/DomainPricingTest.php @@ -0,0 +1,78 @@ +getMockBuilder(\Model_ProductTable::class) + ->onlyMethods(['getOrderLineConfig', 'getUnit']) + ->getMock(); + $productTable->expects($this->once()) + ->method('getOrderLineConfig') + ->willReturn([ + 'price' => 33.0, + 'quantity' => 1, + 'setup_price' => 0.0, + ]); + $productTable->expects($this->once()) + ->method('getUnit') + ->willReturn('year'); + + $product = $this->getMockBuilder(\Model_Product::class) + ->onlyMethods(['getTable', 'getService']) + ->getMock(); + $product->loadBean(new \DummyBean()); + $product->id = 1; + $product->form_id = 2; + $product->type = 'domain'; + $product->title = 'Domain example.com registration'; + $product->expects($this->exactly(2)) + ->method('getTable') + ->willReturn($productTable); + $product->expects($this->once()) + ->method('getService') + ->willReturn(new \stdClass()); + + $cart = new \Model_Cart(); + $cart->loadBean(new \DummyBean()); + + $cartProduct = new \Model_CartProduct(); + $cartProduct->loadBean(new \DummyBean()); + $cartProduct->id = 10; + $cartProduct->cart_id = 20; + $cartProduct->product_id = 1; + $cartProduct->config = json_encode([ + 'action' => 'register', + 'register_sld' => 'example', + 'register_tld' => '.com', + 'register_years' => 2, + 'period' => '2Y', + ]); + + $db = $this->createMock('Box_Database'); + $db->expects($this->atLeast(4)) + ->method('load') + ->willReturnCallback(static function (string $model) use ($product, $cart) { + return $model === 'Cart' ? $cart : $product; + }); + + $di = $this->getDi(); + $di['db'] = $db; + $service->setDi($di); + + $result = $service->cartProductToApiArray($cartProduct); + + $this->assertSame(1, $result['quantity']); + $this->assertSame(33.0, $result['price']); + $this->assertSame(33.0, $result['total']); + } +} diff --git a/tests-legacy/modules/Cart/ServiceTest.php b/tests-legacy/modules/Cart/ServiceTest.php index d0fcf4036..4b7f20299 100644 --- a/tests-legacy/modules/Cart/ServiceTest.php +++ b/tests-legacy/modules/Cart/ServiceTest.php @@ -756,10 +756,11 @@ final class ServiceTest extends \BBTestCase { $promo = new \Model_Promo(); $promo->loadBean(new \DummyBean()); + $promo->id = 1; $dbMock = $this->createMock('Box_Database'); $dbMock->expects($this->atLeastOnce()) - ->method('store') + ->method('exec') ->willReturn(1); $di = $this->getDi(); @@ -771,6 +772,25 @@ final class ServiceTest extends \BBTestCase $this->assertNull($result); } + public function testUsePromoLimitReached(): void + { + $promo = new \Model_Promo(); + $promo->loadBean(new \DummyBean()); + $promo->id = 1; + + $dbMock = $this->createMock('Box_Database'); + $dbMock->expects($this->atLeastOnce()) + ->method('exec') + ->willReturn(0); + + $di = $this->getDi(); + $di['db'] = $dbMock; + $this->service->setDi($di); + + $this->expectException(\FOSSBilling\InformationException::class); + $this->service->usePromo($promo); + } + public function testFindActivePromoByCode(): void { $promo = new \Model_Promo(); @@ -897,7 +917,13 @@ final class ServiceTest extends \BBTestCase ->method('isStockAvailable') ->willReturn(false); + $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->atLeastOnce()) + ->method('find') + ->willReturn([]); + $di = $this->getDi(); + $di['db'] = $dbMock; $di['events_manager'] = $eventMock; $di['mod_service'] = $di->protect(fn ($name): \PHPUnit\Framework\MockObject\MockObject => $serviceHostingServiceMock); @@ -909,6 +935,58 @@ final class ServiceTest extends \BBTestCase $serviceMock->addItem($cartModel, $productModel, $data); } + public function testAddItemRejectsCumulativeStockOverflow(): void + { + $cartModel = new \Model_Cart(); + $cartModel->loadBean(new \DummyBean()); + $cartModel->id = 10; + + $productModel = new \Model_Product(); + $productModel->loadBean(new \DummyBean()); + $productModel->id = 7; + $productModel->type = 'hosting'; + $productModel->stock_control = true; + $productModel->quantity_in_stock = 1; + + $existingCartProduct = new \Model_CartProduct(); + $existingCartProduct->loadBean(new \DummyBean()); + $existingCartProduct->product_id = 7; + $existingCartProduct->config = json_encode(['quantity' => 1]); + + $eventMock = $this->createMock('\Box_EventManager'); + $eventMock->expects($this->atLeastOnce()) + ->method('fire'); + + $serviceHostingServiceMock = $this->getMockBuilder(\Box\Mod\Servicehosting\Service::class)->getMock(); + + $dbMock = $this->createMock('Box_Database'); + $dbMock->expects($this->atLeastOnce()) + ->method('find') + ->with('CartProduct') + ->willReturn([$existingCartProduct]); + $dbMock->expects($this->never()) + ->method('store'); + + $serviceMock = $this->getMockBuilder(\Box\Mod\Cart\Service::class) + ->onlyMethods(['isRecurrentPricing']) + ->getMock(); + $serviceMock->expects($this->atLeastOnce()) + ->method('isRecurrentPricing') + ->willReturn(false); + + $di = $this->getDi(); + $di['db'] = $dbMock; + $di['events_manager'] = $eventMock; + $di['mod_service'] = $di->protect(fn ($name): \PHPUnit\Framework\MockObject\MockObject => $serviceHostingServiceMock); + + $serviceMock->setDi($di); + $productModel->setDi($di); + + $this->expectException(\FOSSBilling\Exception::class); + $this->expectExceptionMessage('This item is currently out of stock'); + $serviceMock->addItem($cartModel, $productModel, ['quantity' => 1]); + } + public function testAddItemmTypeHosting(): void { $cartModel = new \Model_Cart(); @@ -948,7 +1026,13 @@ final class ServiceTest extends \BBTestCase $serviceMock->expects($this->atLeastOnce()) ->method('addProduct'); + $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->atLeastOnce()) + ->method('find') + ->willReturn([]); + $di = $this->getDi(); + $di['db'] = $dbMock; $di['events_manager'] = $eventMock; $di['mod_service'] = $di->protect(fn ($name): \PHPUnit\Framework\MockObject\MockObject => $serviceHostingServiceMock); $di['logger'] = new \Box_Log(); @@ -997,6 +1081,9 @@ final class ServiceTest extends \BBTestCase ->method('addProduct'); $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->atLeastOnce()) + ->method('find') + ->willReturn([]); $dbMock->expects($this->atLeastOnce()) ->method('load') ->willReturn($productModel); @@ -1044,6 +1131,9 @@ final class ServiceTest extends \BBTestCase ->willReturn(true); $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->atLeastOnce()) + ->method('find') + ->willReturn([]); $dbMock->expects($this->atLeastOnce()) ->method('toArray') ->willReturn([]); diff --git a/tests-legacy/modules/Client/ServiceTest.php b/tests-legacy/modules/Client/ServiceTest.php index 27796d17f..962ce8705 100644 --- a/tests-legacy/modules/Client/ServiceTest.php +++ b/tests-legacy/modules/Client/ServiceTest.php @@ -1176,4 +1176,77 @@ final class ServiceTest extends \BBTestCase $result = $service->checkCustomFields($data); $this->assertNull($result); } + + public function testGuestCreateClientStripsAdminOnlyFields(): void + { + $clientModel = new \Model_Client(); + $clientModel->loadBean(new \DummyBean()); + $clientModel->id = 1; + + $data = [ + 'email' => 'test@example.com', + 'first_name' => 'John', + 'password' => 'StrongPassword123!', + 'group_id' => '2', + 'auth_type' => 'oauth', + 'aid' => 'foreign-id', + 'notes' => 'admin notes', + 'created_at' => '2020-01-01 00:00:00', + 'currency' => 'USD', + 'lang' => 'en', + 'custom_1' => 'value', + ]; + + $requestMock = $this->createMock(\Symfony\Component\HttpFoundation\Request::class); + $requestMock->method('getClientIp')->willReturn('127.0.0.1'); + + $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->once()) + ->method('dispense') + ->willReturn($clientModel); + $capturedData = null; + $dbMock->expects($this->once()) + ->method('store') + ->willReturnCallback(function ($client) use (&$capturedData) { + $capturedData = $client; + + return 1; + }); + + $eventManagerMock = $this->createMock('\Box_EventManager'); + $eventManagerMock->expects($this->exactly(2)) + ->method('fire'); + + $passwordMock = $this->createMock(\FOSSBilling\PasswordManager::class); + $passwordMock->method('hashIt')->willReturn('hashed'); + + $modMock = $this->getMockBuilder(\FOSSBilling\Module::class)->disableOriginalConstructor()->getMock(); + $modMock->method('getConfig')->willReturn([]); + + $di = $this->getDi(); + $di['db'] = $dbMock; + $di['events_manager'] = $eventManagerMock; + $di['logger'] = new \Box_Log(); + $di['mod'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $modMock); + $di['password'] = $passwordMock; + $di['request'] = $requestMock; + + $service = new \Box\Mod\Client\Service(); + $service->setDi($di); + + $service->guestCreateClient($data); + + $this->assertSame('test@example.com', $clientModel->email); + $this->assertSame('John', $clientModel->first_name); + $this->assertSame('value', $clientModel->custom_1); + $this->assertNull($clientModel->client_group_id); + $this->assertNull($clientModel->auth_type); + $this->assertNull($clientModel->aid); + $this->assertNull($clientModel->notes); + $this->assertNull($clientModel->currency); + $this->assertNull($clientModel->lang); + $this->assertSame('127.0.0.1', $clientModel->ip); + $this->assertSame(\Model_Client::ACTIVE, $clientModel->status); + $this->assertStringNotContainsString('2020', $clientModel->created_at); + } } diff --git a/tests-legacy/modules/Invoice/PaymentAdapterPayPalEmailTest.php b/tests-legacy/modules/Invoice/PaymentAdapterPayPalEmailTest.php new file mode 100644 index 000000000..7d0af0d74 --- /dev/null +++ b/tests-legacy/modules/Invoice/PaymentAdapterPayPalEmailTest.php @@ -0,0 +1,150 @@ + 'merchant@example.com', + 'test_mode' => true, + ]); + + $renewalInvoice = new Model_Invoice(); + $renewalInvoice->loadBean(new DummyBean()); + $renewalInvoice->id = 55; + $renewalInvoice->approved = false; + + $originalInvoice = new Model_Invoice(); + $originalInvoice->loadBean(new DummyBean()); + $originalInvoice->id = 10; + $originalInvoice->approved = true; + + $invoiceService = $this->getMockBuilder(Service::class) + ->onlyMethods(['generateRenewalInvoiceForSubscriptionPayment', 'isInvoiceTypeDeposit', 'approveInvoice']) + ->getMock(); + $invoiceService->expects($this->once()) + ->method('generateRenewalInvoiceForSubscriptionPayment') + ->with('SUB-123', 7) + ->willReturn($renewalInvoice); + $invoiceService->expects($this->once()) + ->method('isInvoiceTypeDeposit') + ->with($renewalInvoice) + ->willReturn(false); + $invoiceService->expects($this->once()) + ->method('approveInvoice') + ->with($renewalInvoice, ['use_credits' => false]); + + $dbMock = $this->createMock(Box_Database::class); + $dbMock->expects($this->once()) + ->method('load') + ->with('Invoice', 10) + ->willReturn($originalInvoice); + + $di = $this->getDi(); + $di['db'] = $dbMock; + $di['mod_service'] = $di->protect(function (string $service) use ($invoiceService) { + if ($service === 'Invoice') { + return $invoiceService; + } + + throw new RuntimeException('Unexpected service request: ' . $service); + }); + $adapter->setDi($di); + + $apiAdmin = new class() { + public array $updates = []; + public array $funds = []; + public array $paid = []; + private int $txReads = 0; + + public function invoice_transaction_get(array $data): array + { + ++$this->txReads; + + return match ($this->txReads) { + 1 => [ + 'invoice_id' => 10, + 'type' => 'subscr_payment', + 'txn_id' => null, + 'txn_status' => 'Pending', + 'amount' => 0, + 'currency' => null, + 'status' => 'received', + ], + 2 => [ + 'invoice_id' => 10, + 'type' => 'subscr_payment', + 'txn_id' => 'PAY-123', + 'txn_status' => 'Pending', + 'amount' => 0, + 'currency' => 'USD', + 'status' => Model_Transaction::STATUS_PROCESSING, + ], + default => throw new RuntimeException('Unexpected transaction read'), + }; + } + + public function invoice_get(array $data): array + { + return [ + 'id' => 10, + 'client' => ['id' => 7], + ]; + } + + public function invoice_transaction_claim_for_processing(array $data): bool + { + return true; + } + + public function invoice_transaction_update(array $data): void + { + $this->updates[] = $data; + } + + public function client_balance_add_funds(array $data): void + { + $this->funds[] = $data; + } + + public function invoice_pay_with_credits(array $data): void + { + $this->paid[] = $data; + } + }; + + $adapter->processTransaction($apiAdmin, 1, [ + 'get' => ['invoice_id' => 10], + 'post' => [ + 'txn_type' => 'subscr_payment', + 'payment_status' => 'Completed', + 'txn_id' => 'PAY-123', + 'mc_gross' => '14.99', + 'mc_currency' => 'USD', + 'subscr_id' => 'SUB-123', + ], + ], 2); + + $this->assertContains(['id' => 1, 'txn_id' => 'PAY-123'], $apiAdmin->updates); + $this->assertContains(['id' => 1, 'amount' => '14.99'], $apiAdmin->updates); + $this->assertContains(['id' => 1, 'currency' => 'USD'], $apiAdmin->updates); + $this->assertContains(['id' => 1, 'txn_status' => 'Completed'], $apiAdmin->updates); + $this->assertContains(['id' => 1, 'invoice_id' => 55], $apiAdmin->updates); + $this->assertSame(1, count($apiAdmin->funds)); + $this->assertSame([ + 'id' => 7, + 'amount' => '14.99', + 'description' => 'PayPal transaction PAY-123', + 'type' => 'PayPal', + 'rel_id' => 'PAY-123', + ], $apiAdmin->funds[0]); + $this->assertSame([['id' => 55]], $apiAdmin->paid); + $this->assertSame(Model_Transaction::STATUS_PROCESSED, $apiAdmin->updates[array_key_last($apiAdmin->updates)]['status']); + } +} diff --git a/tests-legacy/modules/Invoice/ServiceInvoiceItemTest.php b/tests-legacy/modules/Invoice/ServiceInvoiceItemTest.php index f5181870b..6ed7ede67 100644 --- a/tests-legacy/modules/Invoice/ServiceInvoiceItemTest.php +++ b/tests-legacy/modules/Invoice/ServiceInvoiceItemTest.php @@ -417,4 +417,125 @@ final class ServiceInvoiceItemTest extends \BBTestCase $result = $this->service->getAllNotExecutePaidItems(); $this->assertIsArray($result); } + + public function testGenerateFromOrderConvertsRecurringDomainPromoDiscountToOrderCurrency(): void + { + $serviceMock = $this->getMockBuilder(ServiceInvoiceItem::class) + ->onlyMethods(['addNew']) + ->getMock(); + + $proforma = new \Model_Invoice(); + $proforma->loadBean(new \DummyBean()); + $proforma->id = 10; + + $order = new \Model_ClientOrder(); + $order->loadBean(new \DummyBean()); + $order->id = 20; + $order->client_id = 30; + $order->product_id = 40; + $order->promo_id = 50; + $order->currency = 'EUR'; + $order->quantity = 1; + $order->unit = 'service'; + $order->period = '1Y'; + $order->title = 'example.com'; + $order->promo_recurring = true; + $order->discount = 1; + $order->config = json_encode(['period' => '1Y']); + + $client = new \Model_Client(); + $client->loadBean(new \DummyBean()); + + $product = new \Model_Product(); + $product->loadBean(new \DummyBean()); + $product->type = \Model_ProductTable::DOMAIN; + + $promo = new \Model_Promo(); + $promo->loadBean(new \DummyBean()); + $promo->code = 'PROMO'; + $promo->type = \Model_Promo::ABSOLUTE; + $promo->value = 5.0; + + $invoiceItem = new \Model_InvoiceItem(); + $invoiceItem->loadBean(new \DummyBean()); + + $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->once()) + ->method('dispense') + ->with('InvoiceItem') + ->willReturn($invoiceItem); + $dbMock->expects($this->exactly(2)) + ->method('store'); + $dbMock->expects($this->once()) + ->method('load') + ->with('Client', $order->client_id) + ->willReturn($client); + $dbMock->expects($this->exactly(2)) + ->method('getExistingModelById') + ->willReturnOnConsecutiveCalls($product, $promo); + $dbMock->expects($this->once()) + ->method('findOne') + ->with('Promo', 'id = ?', [$order->promo_id]) + ->willReturn($promo); + + $orderService = $this->createMock(\Box\Mod\Order\Service::class); + $orderService->expects($this->once()) + ->method('setUnpaidInvoice') + ->with($order, $proforma); + + $clientService = $this->createMock(\Box\Mod\Client\Service::class); + $clientService->expects($this->once()) + ->method('isClientTaxable') + ->with($client) + ->willReturn(false); + + $productService = $this->createMock(\Box\Mod\Product\Service::class); + $productService->expects($this->once()) + ->method('getRenewalProductDiscount') + ->with($product, $promo, ['period' => '1Y']) + ->willReturn(5.0); + + $currencyRepository = $this->createMock(\Box\Mod\Currency\Repository\CurrencyRepository::class); + $currencyRepository->expects($this->once()) + ->method('getRateByCode') + ->with('EUR') + ->willReturn(2.0); + + $currencyService = $this->createMock(\Box\Mod\Currency\Service::class); + $currencyService->expects($this->once()) + ->method('getCurrencyRepository') + ->willReturn($currencyRepository); + + $serviceMock->expects($this->once()) + ->method('addNew') + ->with( + $proforma, + $this->callback(function (array $discountLine) use ($order): bool { + return $discountLine['price'] === -10.0 + && $discountLine['quantity'] === 1 + && $discountLine['rel_id'] === $order->id; + }) + ); + + $di = $this->getDi(); + $di['db'] = $dbMock; + $di['api_guest'] = new class { + public function currency_format(array $data): string + { + return $data['code'] . ' ' . $data['price']; + } + }; + $di['mod_service'] = $di->protect(function (string $serviceName) use ($orderService, $clientService, $productService, $currencyService) { + return match ($serviceName) { + 'Order' => $orderService, + 'client' => $clientService, + 'Product' => $productService, + 'Currency' => $currencyService, + default => throw new \RuntimeException('Unexpected service request: ' . $serviceName), + }; + }); + + $serviceMock->setDi($di); + $serviceMock->generateFromOrder($proforma, $order, \Model_InvoiceItem::TASK_RENEW, 20.0, ['quantity' => 1]); + } } diff --git a/tests-legacy/modules/Invoice/ServiceSubscriptionTest.php b/tests-legacy/modules/Invoice/ServiceSubscriptionTest.php index 7e3eca2db..2031b3220 100644 --- a/tests-legacy/modules/Invoice/ServiceSubscriptionTest.php +++ b/tests-legacy/modules/Invoice/ServiceSubscriptionTest.php @@ -231,8 +231,10 @@ final class ServiceSubscriptionTest extends \BBTestCase $dbMock = $this->getMockBuilder('\Box_Database') ->getMock(); $dbMock->expects($this->atLeastOnce()) - ->method('getCell') - ->willReturn(['']); + ->method('getAll') + ->willReturn([ + ['period' => '', 'price' => 10, 'quantity' => 1], + ]); $di = $this->getDi(); $di['db'] = $dbMock; @@ -248,16 +250,11 @@ final class ServiceSubscriptionTest extends \BBTestCase { $dbMock = $this->getMockBuilder('\Box_Database') ->getMock(); - $dbMock->expects($this->atLeastOnce()) - ->method('getCell') - ->willReturn(null); - - $getAllResults = [ - 0 => ['period' => '1W'], - ]; $dbMock->expects($this->atLeastOnce()) ->method('getAll') - ->willReturn($getAllResults); + ->willReturn([ + ['period' => '1W', 'price' => 10, 'quantity' => 1], + ]); $di = $this->getDi(); $di['db'] = $dbMock; @@ -269,30 +266,61 @@ final class ServiceSubscriptionTest extends \BBTestCase $this->assertTrue($result); } - public function testGetSubscriptionPeriod(): void + public function testIsSubscribableWithRecurringAddonLines(): void { - $serviceMock = $this->getMockBuilder(ServiceSubscription::class) - ->onlyMethods(['isSubscribable']) + $dbMock = $this->getMockBuilder('\Box_Database') ->getMock(); - - $serviceMock->expects($this->atLeastOnce()) - ->method('isSubscribable') - ->willReturn(true); - - $period = '1W'; - $dbMock = $this->createMock('\Box_Database'); - $dbMock->expects($this->atLeastOnce()) - ->method('getCell') - ->willReturn($period); + $dbMock->expects($this->once()) + ->method('getAll') + ->willReturn([ + ['period' => '1M', 'price' => 10, 'quantity' => 1], + ['period' => '1M', 'price' => 2, 'quantity' => 1], + ]); $di = $this->getDi(); $di['db'] = $dbMock; - $serviceMock->setDi($di); + $this->service->setDi($di); + + $this->assertTrue($this->service->isSubscribable(2)); + } + + public function testIsSubscribableRejectsMixedRecurringAndOneTimeLines(): void + { + $dbMock = $this->getMockBuilder('\Box_Database') + ->getMock(); + $dbMock->expects($this->once()) + ->method('getAll') + ->willReturn([ + ['period' => '1M', 'price' => 10, 'quantity' => 1], + ['period' => '', 'price' => 5, 'quantity' => 1], + ]); + + $di = $this->getDi(); + $di['db'] = $dbMock; + $this->service->setDi($di); + + $this->assertFalse($this->service->isSubscribable(2)); + } + + public function testGetSubscriptionPeriod(): void + { + $period = '1W'; + $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->atLeastOnce()) + ->method('getAll') + ->willReturn([ + ['period' => $period, 'price' => 10, 'quantity' => 1], + ['period' => '', 'price' => -2, 'quantity' => 1], + ]); + + $di = $this->getDi(); + $di['db'] = $dbMock; + $this->service->setDi($di); $invoiceModel = new \Model_Invoice(); $invoiceModel->loadBean(new \DummyBean()); - $result = $serviceMock->getSubscriptionPeriod($invoiceModel); + $result = $this->service->getSubscriptionPeriod($invoiceModel); $this->assertIsString($result); $this->assertEquals($period, $result); } diff --git a/tests-legacy/modules/Invoice/ServiceTest.php b/tests-legacy/modules/Invoice/ServiceTest.php index e3da3e1d4..ca044710f 100644 --- a/tests-legacy/modules/Invoice/ServiceTest.php +++ b/tests-legacy/modules/Invoice/ServiceTest.php @@ -327,13 +327,14 @@ final class ServiceTest extends \BBTestCase $di = $this->getDi(); $di['mod_service'] = $di->protect(function ($serviceName) use ($emailService, $serviceMock) { - $serviceName = strtolower((string) $serviceName); if ($serviceName === 'invoice') { return $serviceMock; } if ($serviceName === 'email') { return $emailService; } + + throw new \RuntimeException('Unexpected service request: ' . $serviceName); }); $di['db'] = $dbMock; @@ -345,6 +346,90 @@ final class ServiceTest extends \BBTestCase $this->service->onAfterAdminInvoiceReminderSent($eventMock); } + public function testOnAfterAdminInvoiceApprove(): void + { + $params = [ + 'id' => 1, + 'total' => 10, + 'client' => [ + 'id' => 2, + ], + ]; + + $eventMock = $this->getMockBuilder('\Box_Event') + ->disableOriginalConstructor() + ->getMock(); + $eventMock->expects($this->atLeastOnce()) + ->method('getParameters') + ->willReturn($params); + + $emailService = $this->createMock(\Box\Mod\Email\Service::class); + $emailService->expects($this->once()) + ->method('sendTemplate') + ->with([ + 'to_client' => 2, + 'code' => 'mod_invoice_created', + 'invoice' => $params, + ]); + + $di = $this->getDi(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($emailService) { + if ($serviceName === 'email') { + return $emailService; + } + + throw new \RuntimeException('Unexpected service request: ' . $serviceName); + }); + + $this->service->setDi($di); + $eventMock->expects($this->atLeastOnce()) + ->method('getDi') + ->willReturn($di); + + $result = $this->service->onAfterAdminInvoiceApprove($eventMock); + $this->assertTrue($result); + } + + public function testOnAfterAdminInvoiceApproveSkipsPaidInvoices(): void + { + $params = [ + 'id' => 1, + 'total' => 10, + 'status' => \Model_Invoice::STATUS_PAID, + 'client' => [ + 'id' => 2, + ], + ]; + + $eventMock = $this->getMockBuilder('\Box_Event') + ->disableOriginalConstructor() + ->getMock(); + $eventMock->expects($this->atLeastOnce()) + ->method('getParameters') + ->willReturn($params); + + $emailService = $this->createMock(\Box\Mod\Email\Service::class); + $emailService->expects($this->never()) + ->method('sendTemplate'); + + $di = $this->getDi(); + $di['mod_service'] = $di->protect(function ($serviceName) use ($emailService) { + if ($serviceName === 'email') { + return $emailService; + } + + throw new \RuntimeException('Unexpected service request: ' . $serviceName); + }); + + $this->service->setDi($di); + $eventMock->expects($this->atLeastOnce()) + ->method('getDi') + ->willReturn($di); + + $result = $this->service->onAfterAdminInvoiceApprove($eventMock); + $this->assertTrue($result); + } + public function testOnAfterAdminCronRun(): void { $eventMock = $this->getMockBuilder('\Box_Event') @@ -686,25 +771,38 @@ final class ServiceTest extends \BBTestCase public function testApproveInvoice(): void { - $serviceMock = $this->getMockBuilder(Service::class) - ->onlyMethods(['tryPayWithCredits', 'toApiArray']) - ->getMock(); - - $serviceMock->expects($this->atLeastOnce()) - ->method('tryPayWithCredits'); - - $serviceMock->expects($this->atLeastOnce()) - ->method('toApiArray') - ->willReturn(['id' => 1]); - $data['use_credits'] = true; $invoiceModel = new \Model_Invoice(); $invoiceModel->loadBean(new \DummyBean()); + $invoiceModel->status = \Model_Invoice::STATUS_UNPAID; + $serviceMock = $this->getMockBuilder(Service::class) + ->onlyMethods(['tryPayWithCredits', 'toApiArray']) + ->getMock(); + + $serviceMock->expects($this->once()) + ->method('tryPayWithCredits') + ->willReturnCallback(function () use ($invoiceModel): void { + $invoiceModel->status = \Model_Invoice::STATUS_PAID; + }); + + $serviceMock->expects($this->exactly(2)) + ->method('toApiArray') + ->willReturnCallback(function () use ($invoiceModel): array { + return [ + 'id' => 1, + 'status' => $invoiceModel->status, + ]; + }); + + $events = []; $eventManagerMock = $this->createMock('\Box_EventManager'); - $eventManagerMock->expects($this->atLeastOnce()) - ->method('fire'); + $eventManagerMock->expects($this->exactly(2)) + ->method('fire') + ->willReturnCallback(function (array $event) use (&$events): void { + $events[] = $event; + }); $dbMock = $this->createMock('\Box_Database'); $dbMock->expects($this->atLeastOnce()) @@ -719,6 +817,9 @@ final class ServiceTest extends \BBTestCase $result = $serviceMock->approveInvoice($invoiceModel, $data); $this->assertTrue($result); + $this->assertSame('onBeforeAdminInvoiceApprove', $events[0]['event']); + $this->assertSame('onAfterAdminInvoiceApprove', $events[1]['event']); + $this->assertSame(\Model_Invoice::STATUS_PAID, $events[1]['params']['status']); } public function testGetTotalWithTax(): void @@ -1111,6 +1212,112 @@ final class ServiceTest extends \BBTestCase $this->assertInstanceOf('\Model_Invoice', $result); } + public function testGenerateForOrderUsesRenewalPricingForActiveDomainOrders(): void + { + $serviceMock = $this->getMockBuilder(Service::class) + ->onlyMethods(['setInvoiceDefaults']) + ->getMock(); + $serviceMock->expects($this->once()) + ->method('setInvoiceDefaults'); + + $orderModel = new \Model_ClientOrder(); + $orderModel->loadBean(new \DummyBean()); + $orderModel->client_id = 1; + $orderModel->product_id = 2; + $orderModel->currency = 'USD'; + $orderModel->price = 33; + $orderModel->quantity = 1; + $orderModel->status = \Model_ClientOrder::STATUS_ACTIVE; + $orderModel->config = json_encode([ + 'action' => 'register', + 'register_tld' => '.com', + 'register_years' => 2, + 'period' => '2Y', + ]); + + $clientModel = new \Model_Client(); + $clientModel->loadBean(new \DummyBean()); + + $productTable = $this->getMockBuilder(\Model_ProductDomainTable::class) + ->onlyMethods(['getRenewalLineConfig']) + ->getMock(); + $productTable->expects($this->once()) + ->method('getRenewalLineConfig') + ->willReturn([ + 'price' => 20.0, + 'quantity' => 2, + ]); + + $productModel = $this->getMockBuilder(\Model_Product::class) + ->onlyMethods(['getTable']) + ->getMock(); + $productModel->expects($this->once()) + ->method('getTable') + ->willReturn($productTable); + + $invoiceModel = new \Model_Invoice(); + $invoiceModel->loadBean(new \DummyBean()); + + $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->exactly(2)) + ->method('getExistingModelById') + ->willReturnOnConsecutiveCalls($clientModel, $productModel); + $dbMock->expects($this->atLeastOnce()) + ->method('dispense') + ->willReturn($invoiceModel); + $dbMock->expects($this->atLeastOnce()) + ->method('store'); + + $currencyRepository = $this->getMockBuilder(\Box\Mod\Currency\Repository\CurrencyRepository::class) + ->disableOriginalConstructor() + ->getMock(); + $currencyRepository->expects($this->once()) + ->method('getRateByCode') + ->with('USD') + ->willReturn(1.0); + + $currencyService = $this->getMockBuilder(\Box\Mod\Currency\Service::class) + ->onlyMethods(['getCurrencyRepository']) + ->getMock(); + $currencyService->expects($this->once()) + ->method('getCurrencyRepository') + ->willReturn($currencyRepository); + + $invoiceItemServiceMock = $this->getMockBuilder(ServiceInvoiceItem::class) + ->onlyMethods(['generateFromOrder']) + ->getMock(); + $invoiceItemServiceMock->expects($this->once()) + ->method('generateFromOrder') + ->with( + $this->identicalTo($invoiceModel), + $this->identicalTo($orderModel), + \Model_InvoiceItem::TASK_RENEW, + 20.0, + [ + 'price' => 20.0, + 'quantity' => 2, + ] + ); + + $di = $this->getDi(); + $di['db'] = $dbMock; + $di['mod_service'] = $di->protect(function (string $service, ?string $sub = null) use ($currencyService, $invoiceItemServiceMock) { + if ($service === 'Currency') { + return $currencyService; + } + + if ($service === 'Invoice' && $sub === 'InvoiceItem') { + return $invoiceItemServiceMock; + } + + throw new \RuntimeException('Unexpected service request'); + }); + + $serviceMock->setDi($di); + $result = $serviceMock->generateForOrder($orderModel); + $this->assertInstanceOf('\Model_Invoice', $result); + } + public function testGenerateForOrderAmountIsZero(): void { $clientOrder = new \Model_ClientOrder(); diff --git a/tests-legacy/modules/Order/ServiceTest.php b/tests-legacy/modules/Order/ServiceTest.php index b2479424b..3589ddefa 100644 --- a/tests-legacy/modules/Order/ServiceTest.php +++ b/tests-legacy/modules/Order/ServiceTest.php @@ -1780,6 +1780,7 @@ final class ServiceTest extends \BBTestCase $productModel = new \Model_Product(); $productModel->loadBean(new \DummyBean()); $productModel->stock_control = 1; + $productModel->quantity_in_stock = 5; $dbMock = $this->createMock('\Box_Database'); $dbMock->expects($this->atLeastOnce()) @@ -1794,6 +1795,27 @@ final class ServiceTest extends \BBTestCase $this->assertTrue($result); } + public function testStockSaleThrowsWhenQuantityWouldGoNegative(): void + { + $productModel = new \Model_Product(); + $productModel->loadBean(new \DummyBean()); + $productModel->id = 1; + $productModel->stock_control = 1; + $productModel->quantity_in_stock = 1; + + $dbMock = $this->createMock('\Box_Database'); + $dbMock->expects($this->never()) + ->method('store'); + + $di = $this->getDi(); + $di['db'] = $dbMock; + $this->service->setDi($di); + + $this->expectException(\FOSSBilling\InformationException::class); + $this->expectExceptionMessage('Product 1 is out of stock.'); + $this->service->stockSale($productModel, 2); + } + public function testUpdateOrder(): void { $clientOrderModel = new \Model_ClientOrder(); @@ -1882,23 +1904,76 @@ final class ServiceTest extends \BBTestCase $clientOrderModel = new \Model_ClientOrder(); $clientOrderModel->loadBean(new \DummyBean()); $clientOrderModel->period = '1Y'; + $clientOrderModel->expires_at = '2026-01-01 00:00:00'; + $expectedExpiration = strtotime('2027-01-01 00:00:00'); $periodMock = $this->getMockBuilder('\Box_Period')->disableOriginalConstructor()->getMock(); + $periodMock->expects($this->atLeastOnce()) + ->method('getExpirationTime') + ->with(strtotime('2026-01-01 00:00:00')) + ->willReturn($expectedExpiration); $dbMock = $this->createMock('Box_Database'); + $dbMock->expects($this->atLeastOnce()) + ->method('store'); - $invoiceServiceMock = $this->createMock(\Box\Mod\Invoice\Service::class); - $invoiceServiceMock->expects($this->atLeastOnce()) - ->method('findPaidInvoicesForOrder'); + $serviceMock->expects($this->atLeastOnce()) + ->method('saveStatusChange') + ->with($clientOrderModel, 'Order renewed'); $di = $this->getDi(); $di['mod_config'] = $di->protect(fn ($name): array => []); - $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $invoiceServiceMock); $di['period'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $periodMock); $di['db'] = $dbMock; $serviceMock->setDi($di); $serviceMock->renewFromOrder($clientOrderModel); + + $this->assertEquals('2027-01-01 00:00:00', $clientOrderModel->expires_at); + $this->assertEquals(\Model_ClientOrder::STATUS_ACTIVE, $clientOrderModel->status); + } + + public function testRenewFromOrderExtendsFreeFirstTermOnFirstPaidRenewal(): void + { + $clientOrderModel = new \Model_ClientOrder(); + $clientOrderModel->loadBean(new \DummyBean()); + $clientOrderModel->period = '1Y'; + $clientOrderModel->status = \Model_ClientOrder::STATUS_ACTIVE; + $clientOrderModel->activated_at = '2025-01-01 00:00:00'; + $clientOrderModel->expires_at = '2026-01-01 00:00:00'; + + $serviceMock = $this->getMockBuilder(Service::class) + ->onlyMethods(['_callOnService', 'saveStatusChange']) + ->getMock(); + $serviceMock->expects($this->once()) + ->method('_callOnService') + ->with($this->identicalTo($clientOrderModel), \Model_ClientOrder::ACTION_RENEW); + + $expectedExpiration = strtotime('2027-01-01 00:00:00'); + $periodMock = $this->getMockBuilder('\Box_Period')->disableOriginalConstructor()->getMock(); + $periodMock->expects($this->once()) + ->method('getExpirationTime') + ->with(strtotime('2026-01-01 00:00:00')) + ->willReturn($expectedExpiration); + + $dbMock = $this->createMock('Box_Database'); + $dbMock->expects($this->atLeastOnce()) + ->method('store'); + + $serviceMock->expects($this->once()) + ->method('saveStatusChange') + ->with($clientOrderModel, 'Order renewed'); + + $di = $this->getDi(); + $di['mod_config'] = $di->protect(fn ($name): array => []); + $di['period'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $periodMock); + $di['db'] = $dbMock; + + $serviceMock->setDi($di); + $serviceMock->renewFromOrder($clientOrderModel); + + $this->assertEquals('2027-01-01 00:00:00', $clientOrderModel->expires_at); + $this->assertEquals(\Model_ClientOrder::STATUS_ACTIVE, $clientOrderModel->status); } public function testSuspendFromOrderExceptionNotActiveOrder(): void diff --git a/tests-legacy/modules/Redirect/Api/AdminTest.php b/tests-legacy/modules/Redirect/Api/AdminTest.php index 8ca68f067..79db9b013 100644 --- a/tests-legacy/modules/Redirect/Api/AdminTest.php +++ b/tests-legacy/modules/Redirect/Api/AdminTest.php @@ -34,12 +34,12 @@ final class AdminTest extends \BBTestCase $this->assertSame(['id' => 3, 'path' => 'old-page', 'target' => 'new-page'], $result); } - public function testCreateSanitizesBeforeDelegating(): void + public function testCreateDelegatesToService(): void { $service = $this->createMock(\Box\Mod\Redirect\Service::class); $service->expects($this->once()) ->method('create') - ->with('old-page', 'new-page') + ->with('/old-page/', '/new-page/') ->willReturn(7); $staffService = $this->createMock(\Box\Mod\Staff\Service::class); diff --git a/tests-legacy/modules/Redirect/ServiceTest.php b/tests-legacy/modules/Redirect/ServiceTest.php new file mode 100644 index 000000000..fb1080f5d --- /dev/null +++ b/tests-legacy/modules/Redirect/ServiceTest.php @@ -0,0 +1,152 @@ +assertSame('/new-page', $service->validateTarget('/new-page')); + } + + public function testValidateTargetAllowsRelativePathWithoutSlash(): void + { + $service = new Service(); + $this->assertSame('new-page', $service->validateTarget('new-page')); + } + + public function testValidateTargetAllowsHttpUrl(): void + { + $service = new Service(); + $this->assertSame('http://example.com/page', $service->validateTarget('http://example.com/page')); + } + + public function testValidateTargetAllowsHttpsUrl(): void + { + $service = new Service(); + $this->assertSame('https://example.com/page', $service->validateTarget('https://example.com/page')); + } + + public function testValidateTargetTrimsWhitespace(): void + { + $service = new Service(); + $this->assertSame('/new-page', $service->validateTarget(' /new-page ')); + } + + public function testValidateTargetRejectsEmptyString(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validateTarget(''); + } + + public function testValidateTargetRejectsWhitespaceOnly(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validateTarget(' '); + } + + public function testValidateTargetRejectsJavascriptScheme(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validateTarget('javascript:alert(1)'); + } + + public function testValidateTargetRejectsJavascriptSchemeMixedCase(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validateTarget('JaVaScRiPt:alert(1)'); + } + + public function testValidateTargetRejectsDataScheme(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validateTarget('data:text/html,

test

'); + } + + public function testValidateTargetRejectsFtpScheme(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validateTarget('ftp://example.com/file'); + } + + public function testValidateTargetRejectsCrLfInjection(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validateTarget("/new-page\r\nLocation: https://evil.com"); + } + + public function testValidateTargetRejectsLfInjection(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validateTarget("/new-page\nLocation: https://evil.com"); + } + + public function testValidateTargetRejectsCrInjection(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validateTarget("/new-page\rLocation: https://evil.com"); + } + + public function testValidatePathStripsSlashes(): void + { + $service = new Service(); + $this->assertSame('old-page', $service->validatePath('/old-page/')); + } + + public function testValidatePathAllowsNestedPath(): void + { + $service = new Service(); + $this->assertSame('some/nested/path', $service->validatePath('/some/nested/path/')); + } + + public function testValidatePathRejectsEmptyString(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validatePath(''); + } + + public function testValidatePathRejectsSlashOnly(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validatePath('/'); + } + + public function testValidatePathRejectsPathTraversal(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validatePath('../config'); + } + + public function testValidatePathRejectsEmbeddedPathTraversal(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validatePath('foo/../../etc/passwd'); + } + + public function testValidatePathRejectsCrLf(): void + { + $service = new Service(); + $this->expectException(Exception::class); + $service->validatePath("old-page\r\nX-Header: evil"); + } +} diff --git a/tests-legacy/modules/Staff/ServiceTest.php b/tests-legacy/modules/Staff/ServiceTest.php index 513997719..88fc22d24 100644 --- a/tests-legacy/modules/Staff/ServiceTest.php +++ b/tests-legacy/modules/Staff/ServiceTest.php @@ -237,6 +237,37 @@ final class ServiceTest extends \BBTestCase $this->assertFalse($result); } + public function testHasPermissionRoleStaffWithWildcardPermissionsForNewModule(): void + { + $member = new \Model_Admin(); + $member->loadBean(new \DummyBean()); + $member->role = 'staff'; + + $serviceMock = $this->getMockBuilder(Service::class) + ->onlyMethods(['getPermissions']) + ->getMock(); + + $serviceMock->expects($this->atLeastOnce()) + ->method('getPermissions') + ->willReturn([ + 'default' => ['all' => 1], + 'extension' => ['access' => 1, 'manage_extensions' => 1], + ]); + + $extensionServiceMock = $this->getMockBuilder(\Box\Mod\Extension\Service::class)->onlyMethods(['getSpecificModulePermissions'])->getMock(); + $extensionServiceMock->expects($this->atLeastOnce()) + ->method('getSpecificModulePermissions') + ->willReturn(['manage_settings' => ['type' => 'bool']]); + + $di = $this->getDi(); + $di['mod_service'] = $di->protect(fn (): \PHPUnit\Framework\MockObject\MockObject => $extensionServiceMock); + + $serviceMock->setDi($di); + + $this->assertTrue($serviceMock->hasPermission($member, 'massmailer')); + $this->assertTrue($serviceMock->hasPermission($member, 'massmailer', 'manage_settings')); + } + public function testOnAfterClientReplyTicket(): void { $eventMock = $this->getMockBuilder('\Box_Event')