From d7f0ed20a534cbfcf26953a153c511b1fcce8505 Mon Sep 17 00:00:00 2001 From: Adam Daley Date: Thu, 2 Jul 2026 22:20:10 +0100 Subject: [PATCH] Refactor HTTP helpers and centralize response handling (#3877) * Refactor API request/response HTTP helpers * Centralize exception and response handling * Use ResponseEmitter in installer entrypoints * Add HTTP ResponseFactory and refactor Box_App * Extract route matching into HTTP matcher * Fix route param parsing and remove UrlHelper * Fix exception status code crash and clean up refactor leftovers ApiResponseFactory::getStatusCode() required an int code, but Throwable::getCode() can return a string (e.g. PDOException's SQLSTATE), so any non-FOSSBilling exception with a non-integer code crashed API error handling with a TypeError instead of returning a JSON error. Numeric-string codes are normalized to int to preserve prior loose- comparison behavior; non-numeric codes fall back to the default status. Also removes now-dead ErrorPage::generatePage(), redundant manual requires of ResponseEmitter (already covered by composer's classmap autoload), and duplicate emitResponse() calls in exceptionHandler(). --- src/index.php | 12 +-- src/install/index.php | 9 +- src/install/install.php | 3 +- src/ipn.php | 20 ++--- src/library/Box/App.php | 57 +++++------- src/library/Box/UrlHelper.php | 51 ----------- src/library/FOSSBilling/ErrorPage.php | 6 +- .../FOSSBilling/Http/ApiResponseFactory.php | 71 +++++++++++++++ .../Http/ExceptionResponseFactory.php | 75 ++++++++++++++++ .../FOSSBilling/Http/RequestPayloadParser.php | 32 +++++++ .../FOSSBilling/Http/ResponseEmitter.php | 23 +++++ .../FOSSBilling/Http/ResponseFactory.php | 65 ++++++++++++++ src/library/FOSSBilling/Http/RouteMatch.php | 21 +++++ src/library/FOSSBilling/Http/RouteMatcher.php | 59 +++++++++++++ src/load.php | 78 ++++++----------- src/modules/Api/Controller/Client.php | 50 ++--------- .../FOSSBilling/ApiResponseFactoryTest.php | 86 +++++++++++++++++++ .../ExceptionResponseFactoryTest.php | 41 +++++++++ .../FOSSBilling/RequestPayloadParserTest.php | 54 ++++++++++++ .../Unit/FOSSBilling/ResponseEmitterTest.php | 26 ++++++ .../Unit/FOSSBilling/ResponseFactoryTest.php | 66 ++++++++++++++ tests/Unit/FOSSBilling/RouteMatcherTest.php | 56 ++++++++++++ 22 files changed, 756 insertions(+), 205 deletions(-) delete mode 100644 src/library/Box/UrlHelper.php create mode 100644 src/library/FOSSBilling/Http/ApiResponseFactory.php create mode 100644 src/library/FOSSBilling/Http/ExceptionResponseFactory.php create mode 100644 src/library/FOSSBilling/Http/RequestPayloadParser.php create mode 100644 src/library/FOSSBilling/Http/ResponseEmitter.php create mode 100644 src/library/FOSSBilling/Http/ResponseFactory.php create mode 100644 src/library/FOSSBilling/Http/RouteMatch.php create mode 100644 src/library/FOSSBilling/Http/RouteMatcher.php create mode 100644 tests/Unit/FOSSBilling/ApiResponseFactoryTest.php create mode 100644 tests/Unit/FOSSBilling/ExceptionResponseFactoryTest.php create mode 100644 tests/Unit/FOSSBilling/RequestPayloadParserTest.php create mode 100644 tests/Unit/FOSSBilling/ResponseEmitterTest.php create mode 100644 tests/Unit/FOSSBilling/ResponseFactoryTest.php create mode 100644 tests/Unit/FOSSBilling/RouteMatcherTest.php diff --git a/src/index.php b/src/index.php index 3ee278a8c..ecba61276 100644 --- a/src/index.php +++ b/src/index.php @@ -15,6 +15,7 @@ global $di; use DebugBar\DataCollector\TimeDataCollector; use FOSSBilling\Http\RequestFactory; +use FOSSBilling\Http\ResponseEmitter; use Symfony\Component\HttpFoundation\Response; $config = FOSSBilling\Config::getConfig(); @@ -101,16 +102,17 @@ if (!is_null($http_err_code)) { switch ($http_err_code) { case 404: $e = new FOSSBilling\Exception('Page :url not found', [':url' => $url], 404); - $app->show404($e)->send(); + $response = $app->show404($e); break; default: $e = new FOSSBilling\Exception('HTTP Error :err_code occurred while attempting to load :url', [':err_code' => $http_err_code, ':url' => $url], $http_err_code); - (new Response($app->render('error', ['exception' => $e]), $http_err_code))->send(); + $response = new Response($app->render('error', ['exception' => $e]), $http_err_code); } - exit; +} else { + // If no HTTP error passed, run the app. + $response = $app->run(); } -// If no HTTP error passed, run the app. -$app->run()->send(); +(new ResponseEmitter())->emit($response, $request); exit; diff --git a/src/install/index.php b/src/install/index.php index 47c067599..4292bda7e 100644 --- a/src/install/index.php +++ b/src/install/index.php @@ -2,12 +2,14 @@ declare(strict_types=1); +use FOSSBilling\Http\ResponseEmitter; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Response; if (version_compare(PHP_VERSION, '8.3.0', '<')) { - (new Response('Error: PHP version 8.3.0 or higher is required. You have version ' . PHP_VERSION, 500))->send(); + http_response_code(500); + header('Content-Type: text/plain; charset=UTF-8'); + echo 'Error: PHP version 8.3.0 or higher is required. You have version ' . PHP_VERSION; exit; } @@ -16,5 +18,6 @@ require dirname(__DIR__) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR $request = Request::createFromGlobals(); $installPath = rtrim(dirname((string) $request->server->get('PHP_SELF', '')), '/'); -(new RedirectResponse($installPath . '/install.php'))->send(); +$response = new RedirectResponse($installPath . '/install.php'); +(new ResponseEmitter())->emit($response, $request); exit; diff --git a/src/install/install.php b/src/install/install.php index cbb08432e..e5b70d997 100644 --- a/src/install/install.php +++ b/src/install/install.php @@ -13,6 +13,7 @@ declare(strict_types=1); use Box\Mod\Email\Service; use FOSSBilling\Environment; use FOSSBilling\Http\RequestFactory; +use FOSSBilling\Http\ResponseEmitter; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Path; @@ -81,7 +82,7 @@ $installer = new FOSSBilling_Installer($request, $preConfigProxyCandidate); // Run the installer only in non-CLI mode if (!Environment::isCLI()) { - $installer->run($action)->send(); + (new ResponseEmitter())->emit($installer->run($action), $request); } // Inline installer class. diff --git a/src/ipn.php b/src/ipn.php index 6b8a64188..a8e3f8caa 100644 --- a/src/ipn.php +++ b/src/ipn.php @@ -11,6 +11,7 @@ declare(strict_types=1); */ require_once __DIR__ . DIRECTORY_SEPARATOR . 'load.php'; +use FOSSBilling\Http\ResponseEmitter; use Symfony\Component\Filesystem\Path; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; @@ -25,8 +26,7 @@ $invoiceID = $request->get('invoice_id'); if ($invoiceID !== null) { $invoiceID = filter_var($invoiceID, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); if ($invoiceID === false) { - (new JsonResponse(['error' => ['message' => 'Invalid invoice ID']], 400))->send(); - exit; + emitResponse(new JsonResponse(['error' => ['message' => 'Invalid invoice ID']], 400)); } } @@ -35,8 +35,7 @@ $gatewayID = $request->get('gateway_id'); if ($gatewayID !== null) { $gatewayID = filter_var($gatewayID, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); if ($gatewayID === false) { - (new JsonResponse(['error' => ['message' => 'Invalid gateway ID']], 400))->send(); - exit; + emitResponse(new JsonResponse(['error' => ['message' => 'Invalid gateway ID']], 400)); } } @@ -68,10 +67,11 @@ try { if ($isJsonWebhook && function_exists('fastcgi_finish_request')) { $transactionId = $service->create($ipn); $res = ['result' => $transactionId, 'error' => null]; - (new JsonResponse($res, 200, [ + $response = new JsonResponse($res, 200, [ 'Cache-Control' => 'no-cache, must-revalidate', 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', - ]))->send(); + ]); + (new ResponseEmitter())->emit($response, $request); fastcgi_finish_request(); // Process in the background — errors are logged on the transaction. @@ -91,12 +91,10 @@ if ($request->query->has('redirect') && $request->query->has('invoice_hash')) { $invoiceHash = $request->query->get('invoice_hash'); $hash = preg_replace('/[^a-zA-Z0-9]/', '', is_string($invoiceHash) ? $invoiceHash : ''); $url = $di['url']->link('invoice/' . $hash); - (new RedirectResponse($url))->send(); - exit; + emitResponse(new RedirectResponse($url)); } -(new JsonResponse($res, 200, [ +emitResponse(new JsonResponse($res, 200, [ 'Cache-Control' => 'no-cache, must-revalidate', 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', -]))->send(); -exit; +])); diff --git a/src/library/Box/App.php b/src/library/Box/App.php index e973930f5..9f4f0dc03 100644 --- a/src/library/Box/App.php +++ b/src/library/Box/App.php @@ -15,11 +15,11 @@ use DebugBar\StandardDebugBar; use FOSSBilling\Config; use FOSSBilling\Http\HttpResponseException; use FOSSBilling\Http\RequestFactory; +use FOSSBilling\Http\ResponseFactory; +use FOSSBilling\Http\RouteMatcher; use FOSSBilling\InjectionAwareInterface; use FOSSBilling\Security\AuthenticationRequiredException; use FOSSBilling\Security\EmailValidationRequiredException; -use Symfony\Component\HttpFoundation\BinaryFileResponse; -use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -135,26 +135,17 @@ class Box_App protected function normalizeResponse(mixed $result): Response { - if ($result instanceof Response) { - return $result; - } - - return new Response((string) ($result ?? '')); + return (new ResponseFactory())->normalize($result); } public function renderResponse(string $fileName, array $variableArray = [], int $statusCode = 200, array $headers = []): Response { - $response = new Response($this->render($fileName, $variableArray), $statusCode); - $response->headers->add($headers); - - return $response; + return (new ResponseFactory())->html($this->render($fileName, $variableArray), $statusCode, $headers); } public function errorResponse(Exception $e, ?int $statusCode = null, array $headers = []): Response { - $statusCode ??= $e->getCode() > 0 ? $e->getCode() : 500; - - return $this->renderResponse('error', ['exception' => $e], $statusCode, $headers); + return (new ResponseFactory())->error($this->render('error', ['exception' => $e]), $e, $statusCode, $headers); } public function abortWithResponse(Response $response): never @@ -185,14 +176,14 @@ class Box_App if ($e->getArea() === 'admin') { $this->di['set_return_uri']; - return new RedirectResponse($this->di['url']->adminLink('staff/login')); + return (new ResponseFactory())->redirect($this->di['url']->adminLink('staff/login')); } $this->di['set_return_uri']; - return new RedirectResponse($this->di['url']->link('login')); + return (new ResponseFactory())->redirect($this->di['url']->link('login')); } catch (EmailValidationRequiredException) { - return new RedirectResponse($this->di['url']->link('client/profile')); + return (new ResponseFactory())->redirect($this->di['url']->link('client/profile')); } catch (HttpResponseException $e) { return $e->getResponse(); } @@ -204,18 +195,18 @@ class Box_App public function redirect($path): never { $location = $this->di['url']->link($path); - $this->abortWithResponse(new RedirectResponse($location)); + $this->abortWithResponse((new ResponseFactory())->redirect($location)); } public function permanentRedirect($path): never { $location = $this->di['url']->link($path); - $this->abortWithResponse(new RedirectResponse($location, 301)); + $this->abortWithResponse((new ResponseFactory())->redirect($location, 301)); } public function redirectUrl(string $url, int $statusCode = 302): never { - $this->abortWithResponse(new RedirectResponse($url, $statusCode)); + $this->abortWithResponse((new ResponseFactory())->redirect($url, $statusCode)); } public function render($fileName, $variableArray = []): string @@ -225,21 +216,12 @@ class Box_App public function sendFile($filename, $contentType, $path): never { - $response = new BinaryFileResponse($path); - $response->headers->set('Content-Type', $contentType); - $response->setContentDisposition('attachment', $filename); - - $this->abortWithResponse($response); + $this->abortWithResponse((new ResponseFactory())->file($filename, $contentType, $path)); } public function sendDownload($filename, $path): never { - $response = new BinaryFileResponse($path); - $response->headers->set('Content-Type', 'application/octet-stream'); - $response->headers->set('Content-Description', 'File Transfer'); - $response->setContentDisposition('attachment', $filename); - - $this->abortWithResponse($response); + $this->abortWithResponse((new ResponseFactory())->download($filename, $path)); } protected function executeShared($classname, $methodName, $params): mixed @@ -390,13 +372,14 @@ class Box_App $timeCollector->startMeasure('sharedMapping', 'Checking shared mappings'); $sharedCount = count($this->shared); + $routeMatcher = new RouteMatcher(); for ($i = 0; $i < $sharedCount; ++$i) { $mapping = $this->shared[$i]; - $url = new Box_UrlHelper($mapping[0], $mapping[1], $mapping[3], $this->url, $this->getRequest()->getMethod()); - if ($url->match) { + $routeMatch = $routeMatcher->match($mapping[0], $mapping[1], $mapping[3], $this->url, $this->getRequest()->getMethod()); + if ($routeMatch->matched) { $timeCollector->stopMeasure('sharedMapping'); - return $this->normalizeResponse($this->executeShared($mapping[4], $mapping[2], $url->params)); + return $this->normalizeResponse($this->executeShared($mapping[4], $mapping[2], $routeMatch->params)); } } $timeCollector->stopMeasure('sharedMapping'); @@ -406,11 +389,11 @@ class Box_App $mappingsCount = count($this->mappings); for ($i = 0; $i < $mappingsCount; ++$i) { $mapping = $this->mappings[$i]; - $url = new Box_UrlHelper($mapping[0], $mapping[1], $mapping[3], $this->url, $this->getRequest()->getMethod()); - if ($url->match) { + $routeMatch = $routeMatcher->match($mapping[0], $mapping[1], $mapping[3], $this->url, $this->getRequest()->getMethod()); + if ($routeMatch->matched) { $timeCollector->stopMeasure('mapping'); - return $this->normalizeResponse($this->execute($mapping[2], $url->params)); + return $this->normalizeResponse($this->execute($mapping[2], $routeMatch->params)); } } $timeCollector->stopMeasure('mapping'); diff --git a/src/library/Box/UrlHelper.php b/src/library/Box/UrlHelper.php deleted file mode 100644 index 19bd90f84..000000000 --- a/src/library/Box/UrlHelper.php +++ /dev/null @@ -1,51 +0,0 @@ -regexValue(...), $url); // replace param with regex capture - if (preg_match('@^' . $regexedUrl . '$@', $requestUri, $paramValues)) { // determine match and get param values - array_shift($paramValues); // remove the complete text match - $counted = count($paramNames); - for ($i = 0; $i < $counted; ++$i) { - $this->params[$paramNames[$i]] = $paramValues[$i]; - } - $this->match = true; - } - } - } - - private function regexValue($matches): string - { - $key = str_replace(':', '', $matches[0]); - if (array_key_exists($key, $this->conditions)) { - return '(' . $this->conditions[$key] . ')'; - } - - return '([a-zA-Z0-9_\-]+)'; - } -} diff --git a/src/library/FOSSBilling/ErrorPage.php b/src/library/FOSSBilling/ErrorPage.php index 3ddb1a74d..bf64ae63f 100644 --- a/src/library/FOSSBilling/ErrorPage.php +++ b/src/library/FOSSBilling/ErrorPage.php @@ -128,7 +128,7 @@ class ErrorPage * @param int $code Error code * @param string $message The original exception message */ - public function generatePage(int $code, string $message): never + public function renderPage(int $code, string $message): string { $error = static::getCodeInfo($code); $error['message'] ??= "You've received a generic error message: $message "; @@ -138,7 +138,7 @@ class ErrorPage $instanceID = 'Unknown'; } - $page = ' + return ' @@ -305,7 +305,5 @@ class ErrorPage '; - echo $page; - exit; } } diff --git a/src/library/FOSSBilling/Http/ApiResponseFactory.php b/src/library/FOSSBilling/Http/ApiResponseFactory.php new file mode 100644 index 000000000..4283ce93b --- /dev/null +++ b/src/library/FOSSBilling/Http/ApiResponseFactory.php @@ -0,0 +1,71 @@ + 'no-cache, must-revalidate', + 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', + ]; + + public function create(mixed $data = null, ?\Exception $exception = null): JsonResponse + { + if ($exception instanceof \Exception) { + return $this->error($exception); + } + + return new JsonResponse(['result' => $data, 'error' => null], Response::HTTP_OK, self::NO_CACHE_HEADERS); + } + + public function error(\Exception $exception): JsonResponse + { + $code = $exception->getCode() ?: 9999; + $headers = self::NO_CACHE_HEADERS; + + if ($exception instanceof RateLimitException && $exception->hasRetryAfter()) { + $headers['Retry-After'] = (string) $exception->getRetryAfterSeconds(); + } + + return new JsonResponse( + ['result' => null, 'error' => ['message' => $exception->getMessage(), 'code' => $code]], + $this->getStatusCode($code), + $headers, + ); + } + + private function getStatusCode(int|string $code): int + { + // Exception codes are not guaranteed to be integers (e.g. PDOException uses SQLSTATE strings), + // so non-numeric codes never match one of the known application error codes below. + if (is_string($code)) { + if (!is_numeric($code)) { + return Response::HTTP_OK; + } + $code = (int) $code; + } + + return match (true) { + in_array($code, [201, 202, 203, 204, 205, 206, 1002, 1004], true) => Response::HTTP_UNAUTHORIZED, + $code === 403 => Response::HTTP_FORBIDDEN, + $code === 740 => Response::HTTP_NOT_FOUND, + $code === 429 => Response::HTTP_TOO_MANY_REQUESTS, + $code === 503 => Response::HTTP_SERVICE_UNAVAILABLE, + in_array($code, [701, 879], true) => Response::HTTP_BAD_REQUEST, + default => Response::HTTP_OK, + }; + } +} diff --git a/src/library/FOSSBilling/Http/ExceptionResponseFactory.php b/src/library/FOSSBilling/Http/ExceptionResponseFactory.php new file mode 100644 index 000000000..f49f38989 --- /dev/null +++ b/src/library/FOSSBilling/Http/ExceptionResponseFactory.php @@ -0,0 +1,75 @@ +getMessage()); + + if (Environment::isTesting()) { + return new Response($this->formatTestingMessage($exception), $this->getStatusCode($exception), [ + 'Content-Type' => 'text/plain; charset=UTF-8', + ]); + } + + if (defined('API_MODE')) { + $code = $exception->getCode() ?: 9998; + + return new JsonResponse(['result' => null, 'error' => ['message' => $message, 'code' => $code]]); + } + + if (defined('DEBUG') && DEBUG && (new Filesystem())->exists(PATH_VENDOR)) { + return new Response($this->renderWhoops($exception), $this->getStatusCode($exception)); + } + + return new Response((new ErrorPage())->renderPage($exception->getCode(), $message), $this->getStatusCode($exception)); + } + + public function formatTestingMessage(\Throwable $exception): string + { + return $exception::class . ': ' . $exception->getMessage() . ' in ' . $exception->getFile() . ':' . $exception->getLine() . PHP_EOL; + } + + private function renderWhoops(\Throwable $exception): string + { + $whoops = new Run(); + $prettyPage = new PrettyPageHandler(); + $prettyPage->setPageTitle('An error occurred'); + $prettyPage->addDataTable('FOSSBilling environment', [ + 'PHP Version' => PHP_VERSION, + 'Error code' => $exception->getCode(), + 'Instance ID' => defined('INSTANCE_ID') ? INSTANCE_ID : 'Unknown', + ]); + $whoops->pushHandler($prettyPage); + $whoops->allowQuit(false); + $whoops->writeToOutput(false); + + return $whoops->handleException($exception); + } + + private function getStatusCode(\Throwable $exception): int + { + $code = $exception->getCode(); + + return $code >= 400 && $code <= 599 ? $code : Response::HTTP_INTERNAL_SERVER_ERROR; + } +} diff --git a/src/library/FOSSBilling/Http/RequestPayloadParser.php b/src/library/FOSSBilling/Http/RequestPayloadParser.php new file mode 100644 index 000000000..ffce7c293 --- /dev/null +++ b/src/library/FOSSBilling/Http/RequestPayloadParser.php @@ -0,0 +1,32 @@ +getPayload()->all(); + } catch (JsonException $e) { + $message = $e->getPrevious()?->getMessage() ?? $e->getMessage(); + + throw new \FOSSBilling\Exception('Malformed JSON input: :error', [':error' => $message], 400); + } + } +} diff --git a/src/library/FOSSBilling/Http/ResponseEmitter.php b/src/library/FOSSBilling/Http/ResponseEmitter.php new file mode 100644 index 000000000..cacca2fa6 --- /dev/null +++ b/src/library/FOSSBilling/Http/ResponseEmitter.php @@ -0,0 +1,23 @@ +prepare($request)->send(); + } +} diff --git a/src/library/FOSSBilling/Http/ResponseFactory.php b/src/library/FOSSBilling/Http/ResponseFactory.php new file mode 100644 index 000000000..e87d5e02a --- /dev/null +++ b/src/library/FOSSBilling/Http/ResponseFactory.php @@ -0,0 +1,65 @@ +headers->add($headers); + + return $response; + } + + public function error(string $content, \Exception $exception, ?int $statusCode = null, array $headers = []): Response + { + $statusCode ??= $exception->getCode() > 0 ? $exception->getCode() : Response::HTTP_INTERNAL_SERVER_ERROR; + + return $this->html($content, $statusCode, $headers); + } + + public function redirect(string $location, int $statusCode = Response::HTTP_FOUND): RedirectResponse + { + return new RedirectResponse($location, $statusCode); + } + + public function file(string $filename, string $contentType, mixed $path): BinaryFileResponse + { + $response = new BinaryFileResponse($path); + $response->headers->set('Content-Type', $contentType); + $response->setContentDisposition('attachment', $filename); + + return $response; + } + + public function download(string $filename, mixed $path): BinaryFileResponse + { + $response = $this->file($filename, 'application/octet-stream', $path); + $response->headers->set('Content-Description', 'File Transfer'); + + return $response; + } +} diff --git a/src/library/FOSSBilling/Http/RouteMatch.php b/src/library/FOSSBilling/Http/RouteMatch.php new file mode 100644 index 000000000..aaf6c447e --- /dev/null +++ b/src/library/FOSSBilling/Http/RouteMatch.php @@ -0,0 +1,21 @@ +emit($response, $currentRequest); + exit; +} /* * Check if the installer is present. @@ -57,8 +68,7 @@ function checkSSL(): void if (Config::getProperty('security.force_https') && !Environment::isCLI()) { if (!$request->isSecure()) { - (new RedirectResponse('https://' . $request->getHost() . $request->getRequestUri()))->send(); - exit; + emitResponse(new RedirectResponse('https://' . $request->getHost() . $request->getRequestUri())); } } } @@ -138,52 +148,17 @@ function errorHandler(int $number, string $message, string $file, int $line): bo */ function exceptionHandler(Exception|Error $e) { - global $filesystem; + $exceptionResponseFactory = new ExceptionResponseFactory(); if (Environment::isTesting()) { - $msg = $e::class . ': ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() . PHP_EOL; + $msg = $exceptionResponseFactory->formatTestingMessage($e); @file_put_contents(Path::join(PATH_LOG, 'exception_handler.log'), date('c') . ' ' . $msg, FILE_APPEND); @file_put_contents(Path::join(PATH_ROOT, 'data', 'log', 'exception_handler.log'), date('c') . ' ' . $msg, FILE_APPEND); - echo $msg; - - return; - } - error_log("{$e->getMessage()} at {$e->getFile()} : {$e->getLine()}"); - - $message = htmlspecialchars($e->getMessage()); - - if (defined('API_MODE')) { - $code = $e->getCode() ?: 9998; - $result = ['result' => null, 'error' => ['message' => $message, 'code' => $code]]; - echo json_encode($result); - - return false; - } - - // @phpstan-ignore booleanAnd.alwaysFalse, booleanAnd.rightAlwaysFalse (DEBUG is a runtime constant) - if (defined('DEBUG') && DEBUG && $filesystem->exists(PATH_VENDOR)) { - /** - * If advanced debugging is enabled, print Whoops instead of our error page. - * filp/whoops documentation: https://github.com/filp/whoops/blob/master/docs/API%20Documentation.md. - */ - $whoops = new Run(); - $prettyPage = new PrettyPageHandler(); - $prettyPage->setPageTitle('An error occurred'); - $prettyPage->addDataTable('FOSSBilling environment', [ - 'PHP Version' => PHP_VERSION, - 'Error code' => $e->getCode(), - // @phpstan-ignore nullCoalesce.expr (INSTANCE_ID is a runtime constant that may not be defined during analysis) - 'Instance ID' => INSTANCE_ID ?? 'Unknown', - ]); - $whoops->pushHandler($prettyPage); - $whoops->allowQuit(false); - $whoops->writeToOutput(false); - - echo $whoops->handleException($e); } else { - $errorPage = new FOSSBilling\ErrorPage(); - $errorPage->generatePage($e->getCode(), $message); + error_log("{$e->getMessage()} at {$e->getFile()} : {$e->getLine()}"); } + + emitResponse($exceptionResponseFactory->create($e)); } /* @@ -220,7 +195,14 @@ function preInit(): void require Path::join(PATH_LIBRARY, 'FOSSBilling', 'ErrorPage.php'); require Path::join(PATH_LIBRARY, 'FOSSBilling', 'SentryHelper.php'); require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Environment.php'); + require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Http', 'ApiResponseFactory.php'); + require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Http', 'ExceptionResponseFactory.php'); require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Http', 'RequestFactory.php'); + require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Http', 'RequestPayloadParser.php'); + require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Http', 'ResponseFactory.php'); + require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Http', 'ResponseEmitter.php'); + require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Http', 'RouteMatch.php'); + require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Http', 'RouteMatcher.php'); require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Config.php'); require Path::join(PATH_LIBRARY, 'FOSSBilling', 'Tools.php'); } @@ -246,17 +228,13 @@ function init(): void $installerExists = $filesystem->exists(Path::join('install', 'install.php')); if (!$configExists && $installerExists) { - $response = new RedirectResponse($request->getBasePath() . '/install/install.php', 307); - $response->send(); - exit; + emitResponse(new RedirectResponse($request->getBasePath() . '/install/install.php', 307)); } elseif (!$configIsValid) { throw new Exception('The FOSSBilling configuration file is empty or invalid.', 3); } if (Environment::isDevelopment() && Config::getProperty('debug_and_monitoring.debug', false) && $installerExists && !hasDatabaseTables()) { - $response = new RedirectResponse($request->getBasePath() . '/install/install.php', 307); - $response->send(); - exit; + emitResponse(new RedirectResponse($request->getBasePath() . '/install/install.php', 307)); } RequestFactory::configureFromConfig($request); diff --git a/src/modules/Api/Controller/Client.php b/src/modules/Api/Controller/Client.php index 9a76267ec..d4f2419b9 100644 --- a/src/modules/Api/Controller/Client.php +++ b/src/modules/Api/Controller/Client.php @@ -18,12 +18,12 @@ namespace Box\Mod\Api\Controller; use FOSSBilling\Config; use FOSSBilling\Environment; +use FOSSBilling\Http\ApiResponseFactory; use FOSSBilling\Http\HttpResponseException; +use FOSSBilling\Http\RequestPayloadParser; use FOSSBilling\InjectionAwareInterface; use FOSSBilling\Security\AuthenticationRequiredException; use FOSSBilling\Security\EmailValidationRequiredException; -use FOSSBilling\Security\RateLimitException; -use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Response; @@ -69,18 +69,10 @@ class Client implements InjectionAwareInterface public function post_method(\Box_App $app, $role, $class, $method): Response { - $request = $app->getRequest(); - $p = $request->request->all(); - - // adding support for raw post input with json string - $input = $request->getContent(); - if (empty($p) && !empty($input)) { - $p = json_decode($input, true); - if (json_last_error() !== JSON_ERROR_NONE) { - $exc = new \FOSSBilling\Exception('Malformed JSON input: :error', [':error' => json_last_error_msg()], 400); - - return $this->renderJson(null, $exc); - } + try { + $p = (new RequestPayloadParser())->all($app->getRequest()); + } catch (\FOSSBilling\Exception $exc) { + return $this->renderJson(null, $exc); } $call = $class . '_' . $method; @@ -441,39 +433,11 @@ class Client implements InjectionAwareInterface { $this->_loadConfig(); - $headers = [ - 'Cache-Control' => 'no-cache, must-revalidate', - 'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT', - ]; - $statusCode = 200; - 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)) { - $statusCode = 401; - } elseif ($code == 403) { - $statusCode = 403; - } elseif ($code == 740) { - $statusCode = 404; - } elseif ($code == 429) { - $statusCode = 429; - if ($e instanceof RateLimitException && $e->hasRetryAfter()) { - $headers['Retry-After'] = (string) $e->getRetryAfterSeconds(); - } - } elseif ($code == 503) { - $statusCode = 503; - } elseif ($code == 701 || $code == 879) { - $statusCode = 400; - } - } else { - $result = ['result' => $data, 'error' => null]; } - return new JsonResponse($result, $statusCode, $headers); + return (new ApiResponseFactory())->create($data, $e); } protected function sendResponse(Response $response): Response diff --git a/tests/Unit/FOSSBilling/ApiResponseFactoryTest.php b/tests/Unit/FOSSBilling/ApiResponseFactoryTest.php new file mode 100644 index 000000000..d2b952f04 --- /dev/null +++ b/tests/Unit/FOSSBilling/ApiResponseFactoryTest.php @@ -0,0 +1,86 @@ +create(['id' => 42]); + + expect($response->getStatusCode())->toBe(Response::HTTP_OK) + ->and($response->headers->hasCacheControlDirective('no-cache'))->toBeTrue() + ->and($response->headers->hasCacheControlDirective('must-revalidate'))->toBeTrue() + ->and($response->headers->get('Expires'))->toBe('Mon, 26 Jul 1997 05:00:00 GMT') + ->and(json_decode((string) $response->getContent(), true))->toBe([ + 'result' => ['id' => 42], + 'error' => null, + ]); +}); + +test('API response factory maps authentication errors to unauthorized responses', function (): void { + $response = (new ApiResponseFactory())->create(null, new FOSSBilling\Exception('Authentication Failed', null, 201)); + + expect($response->getStatusCode())->toBe(Response::HTTP_UNAUTHORIZED) + ->and(json_decode((string) $response->getContent(), true))->toBe([ + 'result' => null, + 'error' => [ + 'message' => 'Authentication Failed', + 'code' => 201, + ], + ]); +}); + +test('API response factory preserves legacy ok status for unmapped application errors', function (): void { + $response = (new ApiResponseFactory())->create(null, new FOSSBilling\Exception('Unexpected API error', null, 9999)); + + expect($response->getStatusCode())->toBe(Response::HTTP_OK); +}); + +test('API response factory adds retry after header for rate limit errors', function (): void { + $retryAfter = new DateTimeImmutable('+60 seconds'); + $exception = new RateLimitException(new RateLimitResult('api_guest', true, 10, 0, $retryAfter)); + + $response = (new ApiResponseFactory())->create(null, $exception); + + expect($response->getStatusCode())->toBe(Response::HTTP_TOO_MANY_REQUESTS) + ->and((int) $response->headers->get('Retry-After'))->toBeGreaterThan(0); +}); + +test('API response factory does not crash on non-integer exception codes', function (): void { + // PDOException (and other libraries) can carry a string SQLSTATE code instead of an int. + $exception = new class('Table does not exist') extends PDOException { + public function __construct(string $message) + { + parent::__construct($message); + $this->code = '42S02'; + } + }; + + $response = (new ApiResponseFactory())->create(null, $exception); + + expect($response->getStatusCode())->toBe(Response::HTTP_OK) + ->and(json_decode((string) $response->getContent(), true))->toBe([ + 'result' => null, + 'error' => [ + 'message' => 'Table does not exist', + 'code' => '42S02', + ], + ]); +}); + +test('API response factory maps numeric string exception codes like their integer equivalents', function (): void { + $exception = new class('Forbidden') extends Exception { + public function __construct(string $message) + { + parent::__construct($message); + $this->code = '403'; + } + }; + + $response = (new ApiResponseFactory())->create(null, $exception); + + expect($response->getStatusCode())->toBe(Response::HTTP_FORBIDDEN); +}); diff --git a/tests/Unit/FOSSBilling/ExceptionResponseFactoryTest.php b/tests/Unit/FOSSBilling/ExceptionResponseFactoryTest.php new file mode 100644 index 000000000..fd08139d5 --- /dev/null +++ b/tests/Unit/FOSSBilling/ExceptionResponseFactoryTest.php @@ -0,0 +1,41 @@ +create($exception); + + expect($response->getStatusCode())->toBe(Response::HTTP_INTERNAL_SERVER_ERROR) + ->and($response->headers->get('Content-Type'))->toContain('text/plain') + ->and($response->getContent())->toContain('RuntimeException: Broken loader state'); +}); + +test('exception response factory creates FOSSBilling error pages outside testing', function (): void { + $previousEnv = getenv('APP_ENV'); + putenv('APP_ENV=prod'); + + try { + $response = (new ExceptionResponseFactory())->create(new RuntimeException('Config missing', 3)); + } finally { + putenv($previousEnv === false ? 'APP_ENV' : 'APP_ENV=' . $previousEnv); + } + + expect($response->getStatusCode())->toBe(Response::HTTP_INTERNAL_SERVER_ERROR) + ->and($response->getContent())->toContain('FOSSBilling Error') + ->and($response->getContent())->toContain('Your Configuration is Empty'); +}); + +test('error page can render without sending output', function (): void { + $page = (new ErrorPage())->renderPage(404, 'Missing route'); + + expect($page)->toContain('FOSSBilling Error') + ->and($page)->toContain('Error Code: #404') + ->and($page)->toContain('Missing route'); +}); diff --git a/tests/Unit/FOSSBilling/RequestPayloadParserTest.php b/tests/Unit/FOSSBilling/RequestPayloadParserTest.php new file mode 100644 index 000000000..aeef131a4 --- /dev/null +++ b/tests/Unit/FOSSBilling/RequestPayloadParserTest.php @@ -0,0 +1,54 @@ + 'Ada', + 'last_name' => 'Lovelace', + ]); + + $payload = (new RequestPayloadParser())->all($request); + + expect($payload)->toBe([ + 'first_name' => 'Ada', + 'last_name' => 'Lovelace', + ]); +}); + +test('parser returns JSON request parameters', function (): void { + $request = Request::create( + '/api/client/profile/update', + 'POST', + server: ['CONTENT_TYPE' => 'application/json'], + content: '{"first_name":"Ada","flags":{"newsletter":true}}', + ); + + $payload = (new RequestPayloadParser())->all($request); + + expect($payload)->toBe([ + 'first_name' => 'Ada', + 'flags' => ['newsletter' => true], + ]); +}); + +test('parser returns an empty payload for empty request bodies', function (): void { + $request = Request::create('/api/client/profile/update', 'POST'); + + expect((new RequestPayloadParser())->all($request))->toBe([]); +}); + +test('parser wraps malformed JSON as a FOSSBilling API exception', function (): void { + $request = Request::create( + '/api/client/profile/update', + 'POST', + server: ['CONTENT_TYPE' => 'application/json'], + content: '{"first_name"', + ); + + expect(fn (): array => (new RequestPayloadParser())->all($request)) + ->toThrow(FOSSBilling\Exception::class, 'Malformed JSON input: Syntax error'); +}); diff --git a/tests/Unit/FOSSBilling/ResponseEmitterTest.php b/tests/Unit/FOSSBilling/ResponseEmitterTest.php new file mode 100644 index 000000000..87de9ab9f --- /dev/null +++ b/tests/Unit/FOSSBilling/ResponseEmitterTest.php @@ -0,0 +1,26 @@ +sent = true; + + return $this; + } + }; + + (new ResponseEmitter())->emit($response, $request); + + expect($response->sent)->toBeTrue() + ->and($response->getContent())->toBe(''); +}); diff --git a/tests/Unit/FOSSBilling/ResponseFactoryTest.php b/tests/Unit/FOSSBilling/ResponseFactoryTest.php new file mode 100644 index 000000000..b973dc744 --- /dev/null +++ b/tests/Unit/FOSSBilling/ResponseFactoryTest.php @@ -0,0 +1,66 @@ +normalize($response))->toBe($response); +}); + +test('response factory normalizes scalar and null controller results', function (): void { + $factory = new ResponseFactory(); + + expect($factory->normalize('body')->getContent())->toBe('body') + ->and($factory->normalize(null)->getContent())->toBe(''); +}); + +test('response factory creates HTML responses with status and headers', function (): void { + $response = (new ResponseFactory())->html('body', 201, ['X-Test' => 'yes']); + + expect($response->getStatusCode())->toBe(201) + ->and($response->getContent())->toBe('body') + ->and($response->headers->get('X-Test'))->toBe('yes'); +}); + +test('response factory creates error responses using exception codes or internal server error fallback', function (): void { + $factory = new ResponseFactory(); + + expect($factory->error('not found', new RuntimeException('Missing', 404))->getStatusCode())->toBe(404) + ->and($factory->error('error', new RuntimeException('Broken'))->getStatusCode())->toBe(Response::HTTP_INTERNAL_SERVER_ERROR); +}); + +test('response factory creates redirect responses', function (): void { + $response = (new ResponseFactory())->redirect('/target', Response::HTTP_MOVED_PERMANENTLY); + + expect($response)->toBeInstanceOf(RedirectResponse::class) + ->and($response->getStatusCode())->toBe(Response::HTTP_MOVED_PERMANENTLY) + ->and($response->headers->get('Location'))->toBe('/target'); +}); + +test('response factory creates binary file and download responses', function (): void { + $file = tempnam(sys_get_temp_dir(), 'fossbilling-response-factory-'); + file_put_contents($file, 'content'); + + try { + $factory = new ResponseFactory(); + $fileResponse = $factory->file('report.txt', 'text/plain', $file); + $downloadResponse = $factory->download('archive.zip', $file); + + expect($fileResponse)->toBeInstanceOf(BinaryFileResponse::class) + ->and($fileResponse->headers->get('Content-Type'))->toBe('text/plain') + ->and($fileResponse->headers->get('Content-Disposition'))->toContain('report.txt') + ->and($downloadResponse->headers->get('Content-Type'))->toBe('application/octet-stream') + ->and($downloadResponse->headers->get('Content-Description'))->toBe('File Transfer') + ->and($downloadResponse->headers->get('Content-Disposition'))->toContain('archive.zip'); + } finally { + if (is_string($file) && file_exists($file)) { + unlink($file); + } + } +}); diff --git a/tests/Unit/FOSSBilling/RouteMatcherTest.php b/tests/Unit/FOSSBilling/RouteMatcherTest.php new file mode 100644 index 000000000..d3dc97460 --- /dev/null +++ b/tests/Unit/FOSSBilling/RouteMatcherTest.php @@ -0,0 +1,56 @@ +match('get', '/invoice', [], '/invoice', 'GET'); + + expect($match->matched)->toBeTrue() + ->and($match->params)->toBe([]); +}); + +test('route matcher rejects different HTTP methods', function (): void { + $match = (new RouteMatcher())->match('post', '/invoice', [], '/invoice', 'GET'); + + expect($match->matched)->toBeFalse(); +}); + +test('route matcher treats HEAD requests as GET requests', function (): void { + $match = (new RouteMatcher())->match('get', '/invoice/:hash', ['hash' => '[a-z0-9]+'], '/invoice/abc123', 'HEAD'); + + expect($match->matched)->toBeTrue() + ->and($match->params)->toBe(['hash' => 'abc123']); +}); + +test('route matcher extracts default route parameters', function (): void { + $match = (new RouteMatcher())->match('get', '/kb/:slug', [], '/kb/getting-started_1', 'GET'); + + expect($match->matched)->toBeTrue() + ->and($match->params)->toBe(['slug' => 'getting-started_1']); +}); + +test('route matcher applies custom route parameter conditions', function (): void { + $matcher = new RouteMatcher(); + + $matched = $matcher->match('get', '/invoice/:hash', ['hash' => '[a-z0-9]+'], '/invoice/abc123', 'GET'); + $rejected = $matcher->match('get', '/invoice/:hash', ['hash' => '[a-z0-9]+'], '/invoice/ABC123', 'GET'); + + expect($matched->matched)->toBeTrue() + ->and($matched->params)->toBe(['hash' => 'abc123']) + ->and($rejected->matched)->toBeFalse(); +}); + +test('route matcher accepts null conditions for routes without constrained parameters', function (): void { + $match = (new RouteMatcher())->match('get', '/servicehosting', null, '/servicehosting', 'GET'); + + expect($match->matched)->toBeTrue(); +}); + +test('route matcher extracts full placeholder names', function (): void { + $match = (new RouteMatcher())->match('get', '/item/:item_id', ['item_id' => '[0-9]+'], '/item/42', 'GET'); + + expect($match->matched)->toBeTrue() + ->and($match->params)->toBe(['item_id' => '42']); +});