mirror of
https://github.com/FOSSBilling/FOSSBilling.git
synced 2026-11-30 12:18:43 +09:00
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().
This commit is contained in:
1 parent
cc9a2aade9
commit
d7f0ed20a5
22 files changed
+756
-205
No files matched your search
+7
-5
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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.
|
||||
|
||||
+9
-11
@@ -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;
|
||||
]));
|
||||
+20
-37
@@ -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');
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2025 FOSSBilling
|
||||
* Copyright 2011-2021 BoxBilling, Inc.
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
class Box_UrlHelper
|
||||
{
|
||||
public array $params = [];
|
||||
public bool $match = false;
|
||||
|
||||
public function __construct(private readonly string $method, string $url, private ?array $conditions, string $requestUri, string $requestMethod)
|
||||
{
|
||||
// Respond identically to a HEAD request as if it's a GET request
|
||||
if ($requestMethod === 'HEAD') {
|
||||
$requestMethod = 'GET';
|
||||
}
|
||||
|
||||
if (strtoupper($method) == $requestMethod) {
|
||||
$paramNames = [];
|
||||
$paramValues = [];
|
||||
|
||||
preg_match_all('@:([a-zA-Z]+)@', $url, $paramNames, PREG_PATTERN_ORDER); // get param names
|
||||
$paramNames = $paramNames[1]; // we want the set of matches
|
||||
$regexedUrl = preg_replace_callback('@:[a-zA-Z_\-]+@', $this->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_\-]+)';
|
||||
}
|
||||
}
|
||||
@@ -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: <code> $message </code>";
|
||||
@@ -138,7 +138,7 @@ class ErrorPage
|
||||
$instanceID = 'Unknown';
|
||||
}
|
||||
|
||||
$page = '
|
||||
return '
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
@@ -305,7 +305,5 @@ class ErrorPage
|
||||
</script>
|
||||
</body>
|
||||
</html>';
|
||||
echo $page;
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
namespace FOSSBilling\Http;
|
||||
|
||||
use FOSSBilling\Security\RateLimitException;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final readonly class ApiResponseFactory
|
||||
{
|
||||
private const array NO_CACHE_HEADERS = [
|
||||
'Cache-Control' => '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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
namespace FOSSBilling\Http;
|
||||
|
||||
use FOSSBilling\Environment;
|
||||
use FOSSBilling\ErrorPage;
|
||||
use Symfony\Component\Filesystem\Filesystem;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Whoops\Handler\PrettyPageHandler;
|
||||
use Whoops\Run;
|
||||
|
||||
final readonly class ExceptionResponseFactory
|
||||
{
|
||||
public function create(\Throwable $exception): Response
|
||||
{
|
||||
$message = htmlspecialchars($exception->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
namespace FOSSBilling\Http;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Exception\JsonException;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
final readonly class RequestPayloadParser
|
||||
{
|
||||
/**
|
||||
* @throws \FOSSBilling\Exception
|
||||
*/
|
||||
public function all(Request $request): array
|
||||
{
|
||||
try {
|
||||
return $request->getPayload()->all();
|
||||
} catch (JsonException $e) {
|
||||
$message = $e->getPrevious()?->getMessage() ?? $e->getMessage();
|
||||
|
||||
throw new \FOSSBilling\Exception('Malformed JSON input: :error', [':error' => $message], 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
namespace FOSSBilling\Http;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final readonly class ResponseEmitter
|
||||
{
|
||||
public function emit(Response $response, Request $request): void
|
||||
{
|
||||
$response->prepare($request)->send();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
namespace FOSSBilling\Http;
|
||||
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final readonly class ResponseFactory
|
||||
{
|
||||
public function normalize(mixed $result): Response
|
||||
{
|
||||
if ($result instanceof Response) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return new Response((string) ($result ?? ''));
|
||||
}
|
||||
|
||||
public function html(string $content, int $statusCode = Response::HTTP_OK, array $headers = []): Response
|
||||
{
|
||||
$response = new Response($content, $statusCode);
|
||||
$response->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
namespace FOSSBilling\Http;
|
||||
|
||||
final readonly class RouteMatch
|
||||
{
|
||||
public function __construct(
|
||||
public bool $matched,
|
||||
public array $params = [],
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
namespace FOSSBilling\Http;
|
||||
|
||||
final readonly class RouteMatcher
|
||||
{
|
||||
public function match(string $routeMethod, string $routePath, ?array $conditions, string $requestPath, string $requestMethod): RouteMatch
|
||||
{
|
||||
if ($requestMethod === 'HEAD') {
|
||||
$requestMethod = 'GET';
|
||||
}
|
||||
|
||||
if (strtoupper($routeMethod) !== $requestMethod) {
|
||||
return new RouteMatch(false);
|
||||
}
|
||||
|
||||
$paramNames = [];
|
||||
$paramValues = [];
|
||||
|
||||
preg_match_all('@:([a-zA-Z_\-]+)@', $routePath, $paramNames, PREG_PATTERN_ORDER);
|
||||
$paramNames = $paramNames[1];
|
||||
$conditions ??= [];
|
||||
|
||||
$regexedRoute = preg_replace_callback(
|
||||
'@:[a-zA-Z_\-]+@',
|
||||
static function (array $matches) use ($conditions): string {
|
||||
$key = str_replace(':', '', $matches[0]);
|
||||
if (array_key_exists($key, $conditions)) {
|
||||
return '(' . $conditions[$key] . ')';
|
||||
}
|
||||
|
||||
return '([a-zA-Z0-9_\-]+)';
|
||||
},
|
||||
$routePath,
|
||||
);
|
||||
|
||||
if (!is_string($regexedRoute) || preg_match('@^' . $regexedRoute . '$@', $requestPath, $paramValues) !== 1) {
|
||||
return new RouteMatch(false);
|
||||
}
|
||||
|
||||
array_shift($paramValues);
|
||||
$params = [];
|
||||
$counted = count($paramNames);
|
||||
for ($i = 0; $i < $counted; ++$i) {
|
||||
$params[$paramNames[$i]] = $paramValues[$i];
|
||||
}
|
||||
|
||||
return new RouteMatch(true, $params);
|
||||
}
|
||||
}
|
||||
+28
-50
@@ -12,14 +12,25 @@ declare(strict_types=1);
|
||||
|
||||
use FOSSBilling\Config;
|
||||
use FOSSBilling\Environment;
|
||||
use FOSSBilling\Http\ExceptionResponseFactory;
|
||||
use FOSSBilling\Http\RequestFactory;
|
||||
use FOSSBilling\Http\ResponseEmitter;
|
||||
use FOSSBilling\SentryHelper;
|
||||
use FOSSBilling\Tools;
|
||||
use Symfony\Component\Filesystem\Filesystem;
|
||||
use Symfony\Component\Filesystem\Path;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Whoops\Handler\PrettyPageHandler;
|
||||
use Whoops\Run;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
function emitResponse(Response $response): never
|
||||
{
|
||||
global $request;
|
||||
|
||||
$currentRequest = $request instanceof Request ? $request : Request::createFromGlobals();
|
||||
(new ResponseEmitter())->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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use FOSSBilling\Http\ApiResponseFactory;
|
||||
use FOSSBilling\Security\RateLimitException;
|
||||
use FOSSBilling\Security\RateLimitResult;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
test('API response factory creates the standard success envelope', function (): void {
|
||||
$response = (new ApiResponseFactory())->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);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use FOSSBilling\ErrorPage;
|
||||
use FOSSBilling\Http\ExceptionResponseFactory;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
test('exception response factory creates plain text responses while testing', function (): void {
|
||||
putenv('APP_ENV=test');
|
||||
$exception = new RuntimeException('Broken loader state', 500);
|
||||
|
||||
$response = (new ExceptionResponseFactory())->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');
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use FOSSBilling\Http\RequestPayloadParser;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
test('parser returns form request parameters', function (): void {
|
||||
$request = Request::create('/api/client/profile/update', 'POST', [
|
||||
'first_name' => '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');
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use FOSSBilling\Http\ResponseEmitter;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
test('emitter prepares the response for the request before sending it', function (): void {
|
||||
$request = Request::create('https://billing.example.com/download', 'HEAD');
|
||||
$response = new class('file contents') extends Response {
|
||||
public bool $sent = false;
|
||||
|
||||
public function send(bool $flush = true): static
|
||||
{
|
||||
$this->sent = true;
|
||||
|
||||
return $this;
|
||||
}
|
||||
};
|
||||
|
||||
(new ResponseEmitter())->emit($response, $request);
|
||||
|
||||
expect($response->sent)->toBeTrue()
|
||||
->and($response->getContent())->toBe('');
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use FOSSBilling\Http\ResponseFactory;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
test('response factory returns existing responses unchanged', function (): void {
|
||||
$response = new Response('ready');
|
||||
|
||||
expect((new ResponseFactory())->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);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use FOSSBilling\Http\RouteMatcher;
|
||||
|
||||
test('route matcher matches exact routes for the same HTTP method', function (): void {
|
||||
$match = (new RouteMatcher())->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']);
|
||||
});
|
||||
Reference in new issue
Block a user