try to fix cors issues

This commit is contained in:
tracer 2024-04-25 20:58:01 +02:00
parent a312ad9095
commit e9b14a11d7
10 changed files with 220 additions and 214 deletions

View File

@ -2,7 +2,7 @@
"name": "24unix/bindapi",
"description": "manage Bind9 DNS server via REST API",
"version": "1.0.9",
"build_number": "355",
"build_number": "356",
"authors": [
{
"name": "Micha Espey",
@ -30,7 +30,7 @@
"robmorgan/phinx": "^0.15",
"symfony/property-access": "^6.1",
"symfony/serializer": "^6.1",
"zircote/swagger-php": "^4.2"
"zircote/swagger-php": "^4.8"
},
"config": {
"optimize-autoloader": true,

24
composer.lock generated
View File

@ -4,20 +4,20 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "39a97c9f763fcd937f90143307fa8185",
"content-hash": "5dbbe0ea570912e4a3664e4798edaccd",
"packages": [
{
"name": "arubacao/tld-checker",
"version": "1.2.228",
"version": "1.2.229",
"source": {
"type": "git",
"url": "https://github.com/arubacao/tld-checker.git",
"reference": "2b203b2ceac5bad62fed07f1613c9cf118fe6f96"
"reference": "194a704aef0b5e07b5695c5a2769f664e7cf9185"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/arubacao/tld-checker/zipball/2b203b2ceac5bad62fed07f1613c9cf118fe6f96",
"reference": "2b203b2ceac5bad62fed07f1613c9cf118fe6f96",
"url": "https://api.github.com/repos/arubacao/tld-checker/zipball/194a704aef0b5e07b5695c5a2769f664e7cf9185",
"reference": "194a704aef0b5e07b5695c5a2769f664e7cf9185",
"shasum": ""
},
"require": {
@ -65,9 +65,9 @@
],
"support": {
"issues": "https://github.com/arubacao/tld-checker/issues",
"source": "https://github.com/arubacao/tld-checker/tree/1.2.228"
"source": "https://github.com/arubacao/tld-checker/tree/1.2.229"
},
"time": "2024-04-14T04:01:22+00:00"
"time": "2024-04-21T04:01:27+00:00"
},
{
"name": "cakephp/chronos",
@ -4116,16 +4116,16 @@
},
{
"name": "squizlabs/php_codesniffer",
"version": "3.9.1",
"version": "3.9.2",
"source": {
"type": "git",
"url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git",
"reference": "267a4405fff1d9c847134db3a3c92f1ab7f77909"
"reference": "aac1f6f347a5c5ac6bc98ad395007df00990f480"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/267a4405fff1d9c847134db3a3c92f1ab7f77909",
"reference": "267a4405fff1d9c847134db3a3c92f1ab7f77909",
"url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/aac1f6f347a5c5ac6bc98ad395007df00990f480",
"reference": "aac1f6f347a5c5ac6bc98ad395007df00990f480",
"shasum": ""
},
"require": {
@ -4192,7 +4192,7 @@
"type": "open_collective"
}
],
"time": "2024-03-31T21:03:09+00:00"
"time": "2024-04-23T20:25:34+00:00"
},
{
"name": "theseer/tokenizer",

View File

@ -2,4 +2,5 @@
Description=BindAPI Service to check zone file and reload configuration
[Service]
User=<paneluser>
ExecStart=/home/users/<user>/<bindApi>/bin/console -q cron:run

View File

@ -6,10 +6,15 @@ error_reporting(error_level: E_ALL);
require dirname(path: __DIR__) . '/vendor/autoload.php';
$uri = parse_url(url: $_SERVER['REQUEST_URI'], component: PHP_URL_PATH);
$uri = explode(separator: '/', string: $uri);
$parsedUrl = parse_url(url: $_SERVER['REQUEST_URI'], component: PHP_URL_PATH);
$uri = explode(separator: '/', string: $parsedUrl);
if ($uri[1] !== 'api') {
$baseRoutes = ['app', 'api'];
$uriPrefix = $uriFirstThreeLetters = substr(string: $uri[1], offset: 0, length: 3);
if (!in_array(needle: $uriPrefix, haystack: $baseRoutes)) {
// only handle $baseRoutes, elso go to swagger ui
$scheme = $_SERVER['REQUEST_SCHEME'];
$host = $_SERVER['SERVER_NAME'];
$header = "$scheme://$host/openapi/index.html";
@ -25,6 +30,12 @@ header(header: "Access-Control-Allow-Headers: Content-Type, Access-Control-Allow
$requestMethod = $_SERVER["REQUEST_METHOD"];
if ($requestMethod === "OPTIONS") {
// Respond with OK status code for preflight requests
http_response_code(response_code: 200);
exit();
}
try {
$app = new BindAPI(quiet: false);
$app->handleRequest(requestMethod: $requestMethod, uri: $uri);

View File

@ -19,8 +19,9 @@
<script>
window.onload = function () {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "/openapi/bindapi.json",
let ui;
ui = SwaggerUIBundle({
url: "/app/apidoc",
dom_id: "#swagger-ui",
deepLinking: true,
presets: [

View File

@ -1,5 +1,4 @@
<?php
declare(strict_types=1);
<?php declare(strict_types=1);
namespace App\Controller;
@ -27,6 +26,7 @@ use App\Repository\DynDNSRepository;
use App\Repository\NameserverRepository;
use App\Repository\PanelRepository;
use App\Repository\SettingsRepository;
use App\Service\ApiClient;
use Arubacao\TldChecker\Validator;
use Exception;
use JsonMapper;
@ -36,9 +36,7 @@ use Odan\Migration\Command\GenerateCommand;
use Phinx\Console\PhinxApplication;
use SodiumException;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
if (php_sapi_name() !== 'cli') {
exit;
@ -54,7 +52,7 @@ class CLIController
* @throws Exception
*/
public function __construct(
private readonly ApiController $apiController,
private readonly ApiClient $apiClient,
private readonly ApikeyRepository $apikeyRepository,
private readonly DomainController $domainController,
private readonly DomainRepository $domainRepository,
@ -65,7 +63,7 @@ class CLIController
private readonly EncryptionController $encryptionController,
private readonly SettingsRepository $settingsRepository,
private $logger,
private bool $quiet
private readonly bool $quiet
)
{
$this->commandGroupContainer = (new CommandGroupContainer())
@ -74,13 +72,16 @@ class CLIController
name: 'list',
callback: function () {
$this->apikeysList();
}))
}
)
)
->addCommand(command: new Command(
name: 'create',
callback: function () {
$this->apikeysCreate();
},
mandatoryParameters: ['name']))
mandatoryParameters: ['name'])
)
->addCommand(command: new Command(
name: 'update',
callback: function () {
@ -524,7 +525,7 @@ class CLIController
}
if (!empty($panel->getA())) {
$panelRequest = $this->apiController->sendCommand(
$panelRequest = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
@ -532,7 +533,7 @@ class CLIController
command: '/server',
serverType: 'panel');
} else {
$panelRequest = $this->apiController->sendCommand(
$panelRequest = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
@ -553,7 +554,7 @@ class CLIController
}
if (empty($panel->getA())) {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
@ -562,7 +563,7 @@ class CLIController
serverType: 'panel'
);
} else {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
@ -726,7 +727,7 @@ class CLIController
echo COLOR_YELLOW . ' ' . $nameserver->getName();
}
if (!empty($nameserver->getA())) {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $nameserver->getName(),
versionIP: 4,
@ -734,7 +735,7 @@ class CLIController
command: 'domains/name/' . $domainName,
serverType: 'nameserver');
} else {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $nameserver->getName(),
versionIP: 6,
@ -754,7 +755,6 @@ class CLIController
echo COLOR_RED . ' Error: ' . COLOR_YELLOW . $result['data'] . COLOR_DEFAULT . PHP_EOL;
}
exit(1);
break;
case 404:
if (!$this->quiet) {
echo COLOR_RED . ' ' . $result['header'] . COLOR_DEFAULT;
@ -771,7 +771,7 @@ class CLIController
$decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $nameserver->getApikey(), key: $encryptionKey);
if (!empty($nameserver->getAaaa())) {
$create = $this->apiController->sendCommand(
$create = $this->apiClient->sendCommand(
requestType: 'POST',
serverName: $nameserver->getName(),
versionIP: 6,
@ -780,7 +780,7 @@ class CLIController
serverType: 'nameserver',
body: $body);
} else {
$create = $this->apiController->sendCommand(
$create = $this->apiClient->sendCommand(
requestType: 'POST',
serverName: $nameserver->getName(),
versionIP: 4,
@ -1094,7 +1094,7 @@ class CLIController
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo COLOR_DEFAULT . ' ' . str_pad(string: $a, length: $maxA, pad_type: STR_PAD_LEFT) . ' ';
}
if ($result = $this->apiController->sendCommand(
if ($result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $server->getName(),
versionIP: 4,
@ -1121,7 +1121,7 @@ class CLIController
if (!$this->configController->getConfig(configKey: 'quiet')) {
echo COLOR_DEFAULT . ' ' . str_pad(string: $aaaa, length: $maxAAAA, pad_type: STR_PAD_LEFT) . ' ';
}
if ($result = $this->apiController->sendCommand(
if ($result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $server->getName(),
versionIP: 6,
@ -1736,7 +1736,7 @@ class CLIController
$decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $panel->getApikey(), key: $encryptionKey);
if (!empty($panel->getAaaa())) {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'POST',
serverName: $panel->getName(),
versionIP: 6,
@ -1744,7 +1744,7 @@ class CLIController
command: 'dyndns/' . $hostName,
serverType: 'nameserver');
} else {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'POST',
serverName: $panel->getName(),
versionIP: 4,
@ -1806,7 +1806,7 @@ class CLIController
$currentDomains = $this->domainRepository->findByPanel(name: $panel->getName());
if (empty($panel->getA())) {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
@ -1815,7 +1815,7 @@ class CLIController
serverType: 'panel'
);
} else {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
@ -1928,7 +1928,7 @@ class CLIController
if (!$quiet) {
echo 'Check using IPv6: ' . COLOR_YELLOW . $panel->getAaaa() . '.' . COLOR_DEFAULT . PHP_EOL;
}
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
@ -1939,7 +1939,7 @@ class CLIController
if (!$quiet) {
echo 'Check using IPv4: ' . COLOR_YELLOW . $panel->getA() . COLOR_DEFAULT . PHP_EOL;
}
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
@ -1963,7 +1963,7 @@ class CLIController
if (!$quiet) {
echo "Found IPv4 entry: " . COLOR_YELLOW . $v4['ip'] . COLOR_DEFAULT . '.' . PHP_EOL;
}
$v4Test = $this->apiController->fileGetContents(url: $webmailDomain, versionIP: 4);
$v4Test = $this->apiClient->fileGetContents(url: $webmailDomain, versionIP: 4);
if ($v4Test['error']) {
if (!$quiet) {
@ -1986,7 +1986,7 @@ class CLIController
if (!$quiet) {
echo "Found IPv6 entry: " . COLOR_YELLOW . $v6['ipv6'] . COLOR_DEFAULT . '.' . PHP_EOL;
}
$v6Test = $this->apiController->fileGetContents(url: $webmailDomain, versionIP: 6);
$v6Test = $this->apiClient->fileGetContents(url: $webmailDomain, versionIP: 6);
if ($v6Test['error']) {
if (!$quiet) {

View File

@ -6,6 +6,7 @@ use App\Entity\Domain;
use App\Repository\DomainRepository;
use App\Repository\NameserverRepository;
use App\Repository\PanelRepository;
use App\Service\ApiClient;
use Monolog\Logger;
error_reporting(error_level: E_ALL);
@ -25,7 +26,7 @@ class DomainController
public function __construct(
private readonly NameserverRepository $nameserverRepository,
private readonly ApiController $checkController,
private readonly ApiClient $checkController,
private readonly DomainRepository $domainRepository,
private readonly PanelRepository $panelRepository,
private readonly ConfigController $configController,

View File

@ -12,7 +12,10 @@ use App\Repository\DynDNSRepository;
use App\Repository\PanelRepository;
use Monolog\Logger;
use OpenApi\Attributes as OAT;
use OpenApi\Attributes\OpenApi;
use OpenApi\Generator;
use UnhandledMatchError;
use function Symfony\Component\String\s;
// TODO attributes for swaggerUI
@ -26,13 +29,14 @@ use UnhandledMatchError;
description: "The bindAPI URL.",
variables: [
new OAT\ServerVariable(
serverVariable: "schema",
default: "https",
enum: ["https", "http"]
serverVariable: 'schema',
default: 'https',
enum: ['http', 'https']
),
new OAT\ServerVariable(
serverVariable: "hostname",
default: "ns2.24unix.net",
serverVariable: 'hostname',
default: 'ns1.24unix.net',
enum: ['ns1.24unix.net', 'ns2.24unix.net', 'ns3.24unix.net', 'ns4.24unix.net']
)
]
)]
@ -42,7 +46,7 @@ use UnhandledMatchError;
#[OAT\SecurityScheme(
securityScheme: "Authorization",
type: "apiKey",
description: "description",
description: "Api Authentication",
name: "X-API-Key",
in: "header"
)]
@ -56,19 +60,7 @@ class RequestController
private array $uri;
/**
* @param ApiController $apiController
* @param ApikeyRepository $apikeyRepository
* @param DomainController $domainController
* @param DomainRepository $domainRepository
* @param DynDNSRepository $dynDNSRepository
* @param PanelRepository $panelRepository
* @param ConfigController $configController
* @param EncryptionController $encryptionController
* @param Logger $logger
*/
public function __construct(
private readonly ApiController $apiController,
private readonly ApikeyRepository $apikeyRepository,
private readonly DomainController $domainController,
private readonly DomainRepository $domainRepository,
@ -84,21 +76,68 @@ class RequestController
$this->result = [];
}
/**
* @return void
*/
public function handleRequest(string $requestMethod, array $uri): void
{
$this->logger->debug(message: "Request: $requestMethod $uri[1]");
$this->requestMethod = strtoupper(string: $requestMethod);
$this->uri = $uri;
$command = $this->uri[2];
// use my router class from address book?
$routes = ['domains', 'ping', 'apidoc', 'dyndns'];
if (empty($command) || !(in_array(needle: $command, haystack: $routes))) {
$this->status = "404 Not Found";
$this->message = "Endpoint not found.";
} else {
try {
match ($command) {
'dyndns' => $this->handleDynDNS(),
'ping' => $this->handlePing(),
'domains' => $this->handleDomains(),
'apidoc' => $this->apiDoc(),
};
} catch (UnhandledMatchError) {
$this->status = '400 Bad Request';
$this->message = 'Unknown path: ' . $command;
}
}
// process api requests
if (!empty($this->status)) {
header(header: $_SERVER['SERVER_PROTOCOL'] . ' ' . $this->status);
}
if (!empty($this->response)) {
echo json_encode(value: [
'response' => $this->response
]);
} elseif (!empty($this->result)) {
echo json_encode(value: [
'result' => $this->result
]);
} elseif (!empty($this->message)) {
echo json_encode(value: [
'message' => $this->message
]);
} else {
echo json_encode(value: [
'message' => $this->message ?? 'Error: No message.'
]);
}
}
#[OAT\Get(
path: '/domains',
operationId: 'getAllDomains',
description: 'Returns a list of all domains on this server.',
summary: 'Listing all domains.',
// security: [
// 'Authorization' => [
//
// "read:api"
// ]
// ],
servers: [],
security: [
['Authorization' => []]
],
tags: ['Domains'],
responses: [
new OAT\Response(
@ -236,58 +275,8 @@ class RequestController
)]
)]
public function handleRequest(string $requestMethod, array $uri): void
{
$this->logger->debug(message: "Request: $requestMethod $uri[1]");
$this->requestMethod = strtoupper(string: $requestMethod);
$this->uri = $uri;
$command = $this->uri[2];
if (empty($command) || !(($command == 'domains') || ($command == 'ping') || ($command == 'apidoc') || ($command == 'dyndns'))) {
$this->status = "404 Not Found";
$this->message = "Endpoint not found.";
} else {
try {
match ($command) {
'dyndns' => $this->handleDynDNS(),
'ping' => $this->handlePing(),
'domains' => $this->handleDomains(),
};
} catch (UnhandledMatchError) {
$this->status = '400 Bad Request';
$this->message = 'Unknown path: ' . $command;
}
}
if (!empty($this->status)) {
header(header: $_SERVER['SERVER_PROTOCOL'] . ' ' . $this->status);
}
if (!empty($this->response)) {
echo json_encode(value: [
'response' => $this->response
]);
} elseif (!empty($this->result)) {
echo json_encode(value: [
'result' => $this->result
]);
} elseif (!empty($this->message)) {
echo json_encode(value: [
'message' => $this->message
]);
} else {
echo json_encode(value: [
'message' => $this->message ?? 'Error: No message.'
]);
}
}
/**
* @return bool
*/
private function checkPassword(): bool
{
$headers = array_change_key_case(array: getallheaders(), case: CASE_UPPER);
@ -537,7 +526,7 @@ class RequestController
$panel = $this->panelRepository->findByName(name: $domain->getPanel());
if (!empty($panel->getAaaa())) {
$domainData = $this->apiController->sendCommand(
$domainData = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
@ -545,7 +534,7 @@ class RequestController
command: 'domains/name/' . $domainName,
serverType: 'panel');
} else {
$domainData = $this->apiController->sendCommand(
$domainData = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
@ -558,7 +547,7 @@ class RequestController
$domainID = $domainDecodedData->id;
if (!empty($panel->getAaaa())) {
$dnsData = $this->apiController->sendCommand(
$dnsData = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 6,
@ -566,7 +555,7 @@ class RequestController
command: 'dns/' . $domainID,
serverType: 'panel');
} else {
$dnsData = $this->apiController->sendCommand(
$dnsData = $this->apiClient->sendCommand(
requestType: 'GET',
serverName: $panel->getName(),
versionIP: 4,
@ -607,7 +596,7 @@ class RequestController
]);
if (!empty($panel->getAaaa())) {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'PUT',
serverName: $panel->getName(),
versionIP: 6,
@ -617,7 +606,7 @@ class RequestController
body: json_decode(json: $newDnsData, associative: true)
);
} else {
$result = $this->apiController->sendCommand(
$result = $this->apiClient->sendCommand(
requestType: 'PUT',
serverName: $panel->getName(),
versionIP: 4,
@ -664,5 +653,17 @@ class RequestController
return $host;
}
private function apiDoc(): void
{
$srcDir = dirname(path: __DIR__);
$requestControllerPath = $srcDir . '/Controller/RequestController.php';
$openApi = Generator::scan(sources: [$requestControllerPath]);
header(header: 'Content-Type: application/json');
echo $openApi->toJson();
exit(0);
}
}

View File

@ -1,25 +1,13 @@
<?php declare(strict_types=1);
namespace App\Controller;
namespace App\Service;
use UnhandledMatchError;
error_reporting(error_level: E_ALL);
class ApiController
class ApiClient
{
/**
* @param String $requestType
* @param String $serverName
* @param int $versionIP
* @param String $apiKey
* @param String $command
* @param String $serverType
* @param array $body
*
* @return array
*/
function sendCommand(string $requestType, string $serverName, int $versionIP, string $apiKey, string $command, string $serverType, array $body = []): array
{
$error = false;
@ -113,7 +101,7 @@ class ApiController
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_ENCODING => '',
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
@ -139,4 +127,6 @@ class ApiController
return $header;
}
}

View File

@ -10,6 +10,7 @@ use App\Controller\DomainController;
use App\Controller\RequestController;
use App\Repository\DomainRepository;
use App\Repository\DynDNSRepository;
use App\Service\ApiClient;
use DI\Container;
use DI\ContainerBuilder;
use DI\DependencyException;
@ -19,16 +20,15 @@ use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Level;
use Monolog\Logger;
use OpenApi\Attributes as OA;
use function DI\autowire;
#[OA\Info(version: '1.0.9', title: 'bindAPI')]
class BindAPI
{
private Logger $logger;
private Container $container;
/**
* @throws Exception
*/
public function __construct(bool $quiet)
{
// init the logger
@ -51,6 +51,7 @@ class BindAPI
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions([
ApiClient::class => autowire(),
ConfigController::class => autowire()
->constructorParameter(parameter: 'quiet', value: $quiet),
CLIController::class => autowire()