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 %}