Compare commits

...

29 Commits

Author SHA1 Message Date
tracer 289e6530a8 fixed a bug in CLIController 2024-07-13 16:48:15 +02:00
tracer 1db989d7c8 adaptet to KH v24.1 api changes 2024-07-13 16:34:27 +02:00
tracer 9ed956ad7d patch version bump 2024-07-09 19:13:47 +02:00
tracer 3a29039bde some bugfixes 2024-07-09 19:03:48 +02:00
tracer 02cdc70e9b pushed to 1.1.1 2024-05-03 20:15:37 +02:00
tracer ac0d8c776e moved check:version to dev enviroment, for regular check use -v 2024-05-03 20:06:06 +02:00
tracer b147cda096 added check:bootstrap 2024-05-03 19:41:18 +02:00
tracer 17e70f14a2 refactored command groups, migrations:make only available in dev/test 2024-05-03 19:15:19 +02:00
tracer bb1a16988d moced color consts to a utility class 2024-05-02 20:18:22 +02:00
tracer f04c306f91 added chekcs for cron job 2024-05-01 18:57:37 +02:00
tracer 5d2e95ac3d added chekcs for cron job 2024-05-01 18:41:24 +02:00
tracer 4e056f6831 added chekcs for cron job 2024-05-01 18:39:55 +02:00
tracer 753e96ed85 added self for nameservers for openApi defaults. 2024-04-30 19:33:07 +02:00
tracer d31ee8bdec added self for nameservers for openApi defaults. 2024-04-30 17:27:31 +02:00
tracer 26b0b6de6b modified version update 2024-04-30 17:22:43 +02:00
tracer efb069eb5a modified version update 2024-04-30 14:11:54 +02:00
tracer 514c77de55 modified version update 2024-04-30 14:08:59 +02:00
tracer 7b40624218 modified version update 2024-04-30 13:49:59 +02:00
tracer 06df37ed3c modified version update 2024-04-30 13:35:21 +02:00
tracer c6ece08a0b changed config table 2024-04-30 13:21:01 +02:00
tracer 0f13e29fe9 changed config table 2024-04-30 13:14:05 +02:00
tracer b06128e819 changed config table 2024-04-30 13:11:54 +02:00
tracer f25e90f292 added self for nameservers for openApi defaults. 2024-04-30 11:13:24 +02:00
tracer d0224f6746 new migration 2024-04-27 15:43:37 +02:00
tracer 71a275198f added version to api 2024-04-26 19:24:04 +02:00
tracer 578f76426e added version to api 2024-04-26 19:22:44 +02:00
tracer 96689879c4 try to fix cors issues 2024-04-25 21:03:35 +02:00
tracer e9b14a11d7 try to fix cors issues 2024-04-25 20:58:01 +02:00
tracer a312ad9095 move log out of root 2024-04-23 19:53:57 +02:00
33 changed files with 4564 additions and 946 deletions

3
.gitignore vendored
View File

@ -14,3 +14,6 @@
/config.json.prod
keys.txt
/.phpunit.cache
/var/log/*
/public/openapi/bindapi.json
/public/openapi/bootstrap.php

6
TODO
View File

@ -1,3 +1,7 @@
check keytype of panel/bindApi
API Endpoint cleanup
check keytype of panel
check keytype of 1bindApi
check:configkey => update config.json
more UNIT tests

View File

@ -10,11 +10,11 @@ if (php_sapi_name() !== 'cli') {
// check php version (must be >= 8.1)
/** @noinspection PhpArgumentWithoutNamedIdentifierInspection */
if (version_compare(PHP_VERSION, '8.1.0', '<')) {
echo 'This application requires PHP 8.1 or newer. You are running ' . PHP_VERSION . PHP_EOL;
echo 'If you are using KeyHelp, use keyhelp-php81 ' . $argv[0] . ' instead.' . PHP_EOL;
if (version_compare(PHP_VERSION, '8.2.0', '<')) {
echo 'This application requires PHP 8.2 or newer. You are running ' . PHP_VERSION . PHP_EOL;
echo 'If you are using KeyHelp, use keyhelp-php82 ' . $argv[0] . ' instead.' . PHP_EOL;
exit;
}
/** @noinspection PhpArgumentWithoutNamedIdentifierInspection */
require dirname(__DIR__, 1) . '/src/Util/Console.php';
require dirname(__DIR__, 1) . '/src/Utilities/Console.php';

148
bindapi.json Normal file
View File

@ -0,0 +1,148 @@
{
"openapi": "3.0.0",
"info": {
"title": "bindAPI",
"version": "1.0.9"
},
"servers": [
{
"url": "{schema}://{hostname}/api",
"description": "The bindAPI URL.",
"variables": {
"schema": {
"enum": [
"http",
"https"
],
"default": "https"
},
"hostname": {
"enum": [
"ns1.24unix.net",
"ns2.24unix.net"
],
"default": "ns2.24unix.net"
}
}
}
],
"paths": {
"/ping": {
"get": {
"tags": [
"Server"
],
"description": "Checks for connectivity and valid APIkey",
"operationId": "ping",
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "API key is missing or invalid."
}
},
"security": [
{
"Authorization": []
}
]
}
},
"/version": {
"get": {
"tags": [
"Server"
],
"description": "Check the API version of the nameserver.",
"operationId": "version",
"responses": {
"200": {
"description": "x.y.z, aka major, minor, patch"
},
"401": {
"description": "API key is missing or invalid."
}
},
"security": [
{
"Authorization": []
}
]
}
},
"/domains": {
"get": {
"tags": [
"Domains"
],
"summary": "List all domains.",
"description": "Returns a list of all domains on this server.",
"operationId": "getAllDomains",
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "API key is missing or invalid."
},
"404": {
"description": "Domain not found."
}
},
"security": [
{
"Authorization": []
}
]
}
},
"/domains/{name}": {
"get": {
"tags": [
"Domains"
],
"summary": "Returns a single domain.",
"description": "Returns information of a single domain specified by its domain name.",
"operationId": "getSingleDomain",
"parameters": [
{
"name": "name",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
},
"401": {
"description": "API key is missing or invalid."
},
"404": {
"description": "Domain not found."
}
},
"security": []
}
}
},
"components": {
"securitySchemes": {
"Authorization": {
"type": "apiKey",
"description": "Api Authentication",
"name": "X-API-Key",
"in": "header"
}
}
},
"tags": [
{
"name": "Server"
}
]
}

View File

@ -1,8 +1,8 @@
{
"name": "24unix/bindapi",
"description": "manage Bind9 DNS server via REST API",
"version": "1.0.8",
"build_number": "354",
"name": "tracer/bindapi",
"description": "manage Bind9 client zones for KeyHelp",
"version": "1.1.2",
"build_number": "380",
"authors": [
{
"name": "Micha Espey",
@ -23,6 +23,7 @@
"ext-posix": "*",
"ext-sodium": "*",
"arubacao/tld-checker": "^1.2",
"bartlett/php-compatinfo": "^7.1",
"monolog/monolog": "^3.1",
"netresearch/jsonmapper": "^4.4",
"php-di/php-di": "^6.3",
@ -30,7 +31,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,

3015
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,10 @@
{
"env": "prod",
"dbHost": "localhost",
"dbPort": 3306,
"dbDatabase": "sampledb",
"dbUser": "sampleuser",
"dbPassword": "secret",
"encryptionKey": "changeme",
"encryptionKey": "1bad::babe",
"debug": false
}

View File

@ -0,0 +1,37 @@
<?php
use Phinx\Db\Adapter\MysqlAdapter;
class AddSelfToNameservers extends Phinx\Migration\AbstractMigration
{
public function change()
{
// $this->table('domains', [
// 'id' => false,
// 'primary_key' => ['id'],
// 'engine' => 'InnoDB',
// 'encoding' => 'utf8mb4',
// 'collation' => 'utf8mb4_unicode_ci',
// 'comment' => '',
// 'row_format' => 'DYNAMIC',
// ])
// ->removeColumn('self')
// ->save();
$this->table('nameservers', [
'id' => false,
'primary_key' => ['id'],
'engine' => 'InnoDB',
'encoding' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'comment' => '',
'row_format' => 'DYNAMIC',
])
->addColumn('self', 'enum', [
'null' => false,
'limit' => 3,
'values' => ['yes', 'no'],
'after' => 'apikey_prefix',
])
->save();
}
}

View File

@ -0,0 +1,41 @@
<?php
use Phinx\Db\Adapter\MysqlAdapter;
class UUIDForConfig extends Phinx\Migration\AbstractMigration
{
public function change()
{
$this->table('config', [
'id' => false,
'primary_key' => ['id'],
'engine' => 'InnoDB',
'encoding' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
'comment' => '',
'row_format' => 'DYNAMIC',
])
->addColumn('id', 'uuid', [
'null' => false,
])
->changeColumn('name', 'string', [
'null' => false,
'limit' => 256,
'collation' => 'utf8mb4_general_ci',
'encoding' => 'utf8mb4',
'after' => 'id',
])
->changeColumn('value', 'string', [
'null' => false,
'limit' => 256,
'collation' => 'utf8mb4_general_ci',
'encoding' => 'utf8mb4',
'after' => 'name',
])
->addIndex(['id'], [
'name' => 'id',
'unique' => true,
])
->save();
}
}

View File

@ -0,0 +1,24 @@
<?php
use Phinx\Db\Adapter\MysqlAdapter;
class DefaultUUIDforConfig extends Phinx\Migration\AbstractMigration
{
public function change()
{
$this->table('config', [
'id' => false,
'primary_key' => ['id'],
'engine' => 'InnoDB',
'encoding' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
'comment' => '',
'row_format' => 'DYNAMIC',
])
->changeColumn('id', 'uuid', [
'null' => false,
'default' => 'uuid()',
])
->save();
}
}

View File

@ -112,12 +112,36 @@ return array (
),
'columns' =>
array (
'id' =>
array (
'TABLE_CATALOG' => 'def',
'TABLE_NAME' => 'config',
'COLUMN_NAME' => 'id',
'ORDINAL_POSITION' => 1,
'COLUMN_DEFAULT' => 'uuid()',
'IS_NULLABLE' => 'NO',
'DATA_TYPE' => 'uuid',
'CHARACTER_MAXIMUM_LENGTH' => NULL,
'CHARACTER_OCTET_LENGTH' => NULL,
'NUMERIC_PRECISION' => NULL,
'NUMERIC_SCALE' => NULL,
'DATETIME_PRECISION' => NULL,
'CHARACTER_SET_NAME' => NULL,
'COLLATION_NAME' => NULL,
'COLUMN_TYPE' => 'uuid',
'COLUMN_KEY' => 'PRI',
'EXTRA' => '',
'PRIVILEGES' => 'select,insert,update,references',
'COLUMN_COMMENT' => '',
'IS_GENERATED' => 'NEVER',
'GENERATION_EXPRESSION' => NULL,
),
'name' =>
array (
'TABLE_CATALOG' => 'def',
'TABLE_NAME' => 'config',
'COLUMN_NAME' => 'name',
'ORDINAL_POSITION' => 1,
'ORDINAL_POSITION' => 2,
'COLUMN_DEFAULT' => NULL,
'IS_NULLABLE' => 'NO',
'DATA_TYPE' => 'varchar',
@ -129,7 +153,7 @@ return array (
'CHARACTER_SET_NAME' => 'utf8mb4',
'COLLATION_NAME' => 'utf8mb4_general_ci',
'COLUMN_TYPE' => 'varchar(256)',
'COLUMN_KEY' => 'PRI',
'COLUMN_KEY' => 'UNI',
'EXTRA' => '',
'PRIVILEGES' => 'select,insert,update,references',
'COLUMN_COMMENT' => '',
@ -141,7 +165,7 @@ return array (
'TABLE_CATALOG' => 'def',
'TABLE_NAME' => 'config',
'COLUMN_NAME' => 'value',
'ORDINAL_POSITION' => 2,
'ORDINAL_POSITION' => 3,
'COLUMN_DEFAULT' => NULL,
'IS_NULLABLE' => 'NO',
'DATA_TYPE' => 'varchar',
@ -163,6 +187,24 @@ return array (
),
'indexes' =>
array (
'PRIMARY' =>
array (
1 =>
array (
'Table' => 'config',
'Non_unique' => 0,
'Key_name' => 'PRIMARY',
'Seq_in_index' => 1,
'Column_name' => 'id',
'Collation' => 'A',
'Sub_part' => NULL,
'Packed' => NULL,
'Null' => '',
'Index_type' => 'BTREE',
'Comment' => '',
'Index_comment' => '',
),
),
'name' =>
array (
1 =>
@ -181,6 +223,24 @@ return array (
'Index_comment' => '',
),
),
'id' =>
array (
1 =>
array (
'Table' => 'config',
'Non_unique' => 0,
'Key_name' => 'id',
'Seq_in_index' => 1,
'Column_name' => 'id',
'Collation' => 'A',
'Sub_part' => NULL,
'Packed' => NULL,
'Null' => '',
'Index_type' => 'BTREE',
'Comment' => '',
'Index_comment' => '',
),
),
),
'foreign_keys' => NULL,
),
@ -1126,6 +1186,30 @@ return array (
'IS_GENERATED' => 'NEVER',
'GENERATION_EXPRESSION' => NULL,
),
'self' =>
array (
'TABLE_CATALOG' => 'def',
'TABLE_NAME' => 'nameservers',
'COLUMN_NAME' => 'self',
'ORDINAL_POSITION' => 7,
'COLUMN_DEFAULT' => NULL,
'IS_NULLABLE' => 'NO',
'DATA_TYPE' => 'enum',
'CHARACTER_MAXIMUM_LENGTH' => 3,
'CHARACTER_OCTET_LENGTH' => 12,
'NUMERIC_PRECISION' => NULL,
'NUMERIC_SCALE' => NULL,
'DATETIME_PRECISION' => NULL,
'CHARACTER_SET_NAME' => 'utf8mb4',
'COLLATION_NAME' => 'utf8mb4_unicode_ci',
'COLUMN_TYPE' => 'enum(\'yes\',\'no\')',
'COLUMN_KEY' => '',
'EXTRA' => '',
'PRIVILEGES' => 'select,insert,update,references',
'COLUMN_COMMENT' => '',
'IS_GENERATED' => 'NEVER',
'GENERATION_EXPRESSION' => NULL,
),
),
'indexes' =>
array (

View File

@ -1,4 +1,4 @@
Copy this files to /etc/systems/system, adapt the path in the service unit and enable the timer by issuing:
Copy these files to /etc/systems/system, adapt the path in the service unit and enable the timer by issuing:
systemctl daemon-reload
systemctl enable bindAPI.timer

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";
@ -21,10 +26,16 @@ header(header: "Access-Control-Allow-Origin: *");
header(header: "Content-Type: application/json; charset=UTF-8");
header(header: "Access-Control-Allow-Methods: OPTIONS,GET,POST,PUT,DELETE");
header(header: "Access-Control-Max-Age: 3600");
header(header: "Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header(header: "Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, x-api-key");
$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);
@ -33,3 +44,4 @@ try {
'error' => $e->getMessage()
]);
}

View File

@ -0,0 +1,5 @@
<?php
const DEFAULT_NS = 'ns2.24unix.net';
const NAMESERVERS = ['ns1.24unix.net', 'ns2.24unix.net'];

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -2,6 +2,8 @@
namespace App\Controller\Commands;
use App\Utilities\Colors;
/**
*
*/
@ -31,17 +33,17 @@ class CommandGroup
public function printCommands(int $longestCommandLength): void
{
echo COLOR_YELLOW . str_pad(string: $this->name, length: $longestCommandLength + 1) . COLOR_WHITE . $this->description . COLOR_DEFAULT . PHP_EOL;
echo Colors::YELLOW . str_pad(string: $this->name, length: $longestCommandLength + 1) . Colors::WHITE . $this->description . Colors::DEFAULT . PHP_EOL;
foreach ($this->commands as $command) {
echo COLOR_GREEN . str_pad(string: ' ', length: $longestCommandLength + 1, pad_type: STR_PAD_LEFT) . $this->name . ':' . $command->getName();
echo Colors::GREEN . str_pad(string: ' ', length: $longestCommandLength + 1, pad_type: STR_PAD_LEFT) . $this->name . ':' . $command->getName();
foreach ($command->getMandatoryParameters() as $optionals) {
echo ' <' . $optionals . '>';
}
foreach ($command->getOptionalParameters() as $mandatory) {
echo ' {' . $mandatory . '}';
}
echo COLOR_WHITE . ' ' . $command->getDescription();
echo COLOR_DEFAULT . PHP_EOL;
echo Colors::WHITE . ' ' . $command->getDescription();
echo Colors::DEFAULT . PHP_EOL;
}
}

View File

@ -2,6 +2,8 @@
namespace App\Controller\Commands;
use App\Utilities\Colors;
/**
*
*/
@ -64,23 +66,23 @@ class CommandGroupContainer
if ($group->exec(subcommand: $subcommand)) {
exit(0);
} else {
echo COLOR_DEFAULT . 'Unknown subcommand ' . COLOR_YELLOW . $subcommand . COLOR_DEFAULT .' for ' . COLOR_YELLOW . $command . COLOR_DEFAULT . '.' . PHP_EOL;
echo Colors::DEFAULT . 'Unknown subcommand ' . Colors::YELLOW . $subcommand . Colors::DEFAULT .' for ' . Colors::YELLOW . $command . Colors::DEFAULT . '.' . PHP_EOL;
exit(1);
}
} else {
echo COLOR_DEFAULT . 'Unknown command group ' . COLOR_YELLOW . $command . COLOR_DEFAULT . '.' . PHP_EOL;
echo Colors::DEFAULT . 'Unknown command group ' . Colors::YELLOW . $command . Colors::DEFAULT . '.' . PHP_EOL;
exit(1);
}
} else {
// check for command group and print available commands
foreach ($this->commandGroups as $group) {
if ($group->getName() === $command) {
echo 'Available subcommands for: ' . COLOR_YELLOW . $group->getName() . COLOR_DEFAULT . ':' . PHP_EOL;
echo 'Available subcommands for: ' . Colors::YELLOW . $group->getName() . Colors::DEFAULT . ':' . PHP_EOL;
$group->printCommands(strlen(string: $group->getName()));
exit(0);
}
}
}
echo COLOR_DEFAULT . 'Unknown command ' . COLOR_YELLOW . $command . COLOR_DEFAULT . '.' . PHP_EOL;
echo Colors::DEFAULT . 'Unknown command ' . Colors::YELLOW . $command . Colors::DEFAULT . '.' . PHP_EOL;
}
}

View File

@ -2,11 +2,14 @@
namespace App\Controller;
use App\Utilities\Colors;
class ConfigController
{
private array $config;
private static $missingEncryptionShown = false;
public function __construct(bool $quiet, bool $test = false)
public function __construct(private readonly bool $quiet, bool $test = false)
{
if ($test) {
@ -35,21 +38,33 @@ class ConfigController
}
$configJSON = file_get_contents(filename: $configFile);
if (json_decode(json: $configJSON) === null) {
// first check if json is valid, after make the assignment
if (json_decode(json: $configJSON, associative: true) === null) {
echo 'Config file is not valid JSON.' . PHP_EOL;
echo $configJSON . PHP_EOL;
exit(1);
}
$this->config = json_decode(json: $configJSON, associative: true);
if (!ConfigController::$missingEncryptionShown) {
if (!isset($this->config['encryptionKey']) || ($this->config['encryptionKey'] === '1bad::babe')) {
ConfigController::$missingEncryptionShown = true;
if (!$this->quiet) {
echo Colors::RED . 'Error: ' . Colors::DEFAULT . 'No encryption key, please run ' . Colors::YELLOW . './bin/console check:generatekey' . Colors::DEFAULT . PHP_EOL;
}
exit(1);
}
}
$this->config['quiet'] = (bool)$quiet;
$this->config['test'] = (bool)$test;
}
public function getConfig(string $configKey): string
public function getConfig(string $configKey): ?string
{
return $this->config[$configKey];
if (isset($this->config[$configKey])) {
return $this->config[$configKey];
} else {
return null;
}
}
}

View File

@ -6,6 +6,8 @@ use App\Entity\Domain;
use App\Repository\DomainRepository;
use App\Repository\NameserverRepository;
use App\Repository\PanelRepository;
use App\Service\ApiClient;
use App\Utilities\Colors;
use Monolog\Logger;
error_reporting(error_level: E_ALL);
@ -25,7 +27,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,
@ -81,13 +83,13 @@ class DomainController
foreach ($domains as $domain) {
$zoneFile = $this->localZonesDir . $domain->getName();
if (!$this->quiet) {
echo ' ' . COLOR_YELLOW . str_pad(string: $domain->getName(), length: $longestEntry + 1, pad_string: " ", pad_type: STR_PAD_RIGHT) ;
echo ' ' . Colors::YELLOW . str_pad(string: $domain->getName(), length: $longestEntry + 1, pad_string: " ", pad_type: STR_PAD_RIGHT) ;
}
if (strcmp(string1: $self->getName(), string2: $domain->getPanel()) !== 0) {
if (!file_exists(filename: $zoneFile)) {
if (!$this->quiet) {
echo COLOR_GREEN . ' OK' . COLOR_DEFAULT . PHP_EOL;
echo Colors::GREEN . ' OK' . Colors::DEFAULT . PHP_EOL;
}
$this->createSlaveZoneFile(domain: $domain);
} else {
@ -99,19 +101,19 @@ class DomainController
echo 'missing value: ' . $zoneFile;
}
if (!$this->quiet) {
echo COLOR_DEFAULT . 'Zone already exists.' . PHP_EOL;
echo Colors::DEFAULT . 'Zone already exists.' . PHP_EOL;
}
}
} else {
if (!$this->quiet) {
echo COLOR_DEFAULT . 'We are master for ' . COLOR_YELLOW . $domain->getName() . PHP_EOL;
echo Colors::DEFAULT . 'We are master for ' . Colors::YELLOW . $domain->getName() . PHP_EOL;
}
}
}
// remove stale zones
foreach ($existingZones as $zone) {
if (!$this->quiet) {
echo 'Removing stale zone: ' . COLOR_YELLOW . $zone . COLOR_DEFAULT . PHP_EOL;
echo 'Removing stale zone: ' . Colors::YELLOW . $zone . Colors::DEFAULT . PHP_EOL;
}
echo $zone . PHP_EOL;
unlink(filename: $zone);
@ -189,12 +191,12 @@ class DomainController
$uid = posix_geteuid();
}
if (!$this->quiet) {
echo "UID:\t" . COLOR_YELLOW . $uid . PHP_EOL;
echo "UID:\t" . Colors::YELLOW . $uid . PHP_EOL;
}
$pwuid = posix_getpwuid(user_id: $uid);
$name = $pwuid['name'];
if (!$this->quiet) {
echo COLOR_DEFAULT . "Name:\t" . COLOR_YELLOW . $name . PHP_EOL;
echo Colors::DEFAULT . "Name:\t" . Colors::YELLOW . $name . PHP_EOL;
}
if (!$bindGroup = posix_getgrnam(name: 'bind')) {
@ -203,40 +205,40 @@ class DomainController
$members = $bindGroup['members'] ?? [];
if (in_array(needle: $name, haystack: $members)) {
if (!$this->quiet) {
echo "\t$name" . COLOR_DEFAULT . ' is in group ' . COLOR_YELLOW . 'bind' . PHP_EOL;
echo "\t$name" . Colors::DEFAULT . ' is in group ' . Colors::YELLOW . 'bind' . PHP_EOL;
}
} else {
$setupIsValid = false;
if (!$this->quiet) {
echo COLOR_RED . "\t$name needs to be in group " . COLOR_YELLOW . 'bind' . COLOR_DEFAULT . '!' . PHP_EOL;
echo Colors::RED . "\t$name needs to be in group " . Colors::YELLOW . 'bind' . Colors::DEFAULT . '!' . PHP_EOL;
}
}
if (!$this->quiet) {
echo COLOR_DEFAULT . 'Checking ' . COLOR_YELLOW . $this->localZoneFile . PHP_EOL;
echo Colors::DEFAULT . 'Checking ' . Colors::YELLOW . $this->localZoneFile . PHP_EOL;
}
$localZoneFilePermissions = @fileperms(filename: $this->localZoneFile);
if ($localZoneFilePermissions & 0x0010) {
if (!$this->quiet) {
echo COLOR_DEFAULT . "\t✅ Group has write access." . PHP_EOL;
echo Colors::DEFAULT . "\t✅ Group has write access." . PHP_EOL;
}
} else {
$setupIsValid = false;
if (!$this->quiet) {
echo COLOR_RED . "\t❌Group needs write permission!" . COLOR_DEFAULT . PHP_EOL;
echo Colors::RED . "\t❌Group needs write permission!" . Colors::DEFAULT . PHP_EOL;
}
}
if (!$this->quiet) {
echo 'Checking ' . COLOR_YELLOW . $this->namedConfLocalFile . PHP_EOL;
echo 'Checking ' . Colors::YELLOW . $this->namedConfLocalFile . PHP_EOL;
}
if (file_exists(filename: $this->namedConfLocalFile) && $namedConfLocal = file_get_contents(filename: $this->namedConfLocalFile)) {
if (!str_contains(haystack: $namedConfLocal, needle: $this->localZoneFile)) {
$setupIsValid = false;
if (!$this->quiet) {
echo "\t$this->localZoneFile" . COLOR_RED . ' needs to be included in ' . COLOR_YELLOW . $this->namedConfLocalFile . PHP_EOL;
echo "\t$this->localZoneFile" . Colors::RED . ' needs to be included in ' . Colors::YELLOW . $this->namedConfLocalFile . PHP_EOL;
}
} else {
if (!$this->quiet) {
echo "\t$this->localZoneFile" . COLOR_DEFAULT . ' is included in ' . COLOR_YELLOW . $this->namedConfLocalFile . PHP_EOL;
echo "\t$this->localZoneFile" . Colors::DEFAULT . ' is included in ' . Colors::YELLOW . $this->namedConfLocalFile . PHP_EOL;
}
}
} else {
@ -246,7 +248,7 @@ class DomainController
}
}
if (!$this->quiet) {
echo COLOR_DEFAULT . 'Checking directory: ' . COLOR_YELLOW . $this->localZonesDir . PHP_EOL;
echo Colors::DEFAULT . 'Checking directory: ' . Colors::YELLOW . $this->localZonesDir . PHP_EOL;
}
$localZoneDirPermissions = @fileperms(filename: $this->localZonesDir);
if ($localZoneDirPermissions & 0x0010) {
@ -256,7 +258,7 @@ class DomainController
} else {
$setupIsValid = false;
if (!$this->quiet) {
echo COLOR_RED . "\t❌Group needs write permission!" . PHP_EOL;
echo Colors::RED . "\t❌Group needs write permission!" . PHP_EOL;
}
}
return $setupIsValid;
@ -270,7 +272,7 @@ class DomainController
{
if (!file_exists(filename: $this->localZoneFile)) {
if (!$this->quiet) {
echo COLOR_DEFAULT . 'Local Zone file ' . COLOR_YELLOW . $this->localZoneFile . COLOR_DEFAULT . ' does not exist.' . PHP_EOL;
echo Colors::DEFAULT . 'Local Zone file ' . Colors::YELLOW . $this->localZoneFile . Colors::DEFAULT . ' does not exist.' . PHP_EOL;
}
exit(1);
}
@ -281,33 +283,33 @@ class DomainController
foreach ($domains as $domain) {
$idString = '(' . $domain->getId() . ') ';
if (!$this->quiet) {
echo COLOR_YELLOW .
echo Colors::YELLOW .
str_pad(string: $domain->getName(), length: $maxNameLength + 1)
. COLOR_DEFAULT
. Colors::DEFAULT
. str_pad(string: $idString, length: 7, pad_type: STR_PAD_LEFT);
}
$hasError = false;
if ($this->isMasterZone(domain: $domain)) {
if (!$this->quiet) {
echo COLOR_GREEN . 'Master Zone';
echo Colors::GREEN . 'Master Zone';
}
} else {
if (!str_contains(haystack: $localZones, needle: $domain->getName())) {
if (!$this->quiet) {
echo COLOR_RED . 'is missing in ' . COLOR_YELLOW . $this->localZoneFile . COLOR_DEFAULT;
echo Colors::RED . 'is missing in ' . Colors::YELLOW . $this->localZoneFile . Colors::DEFAULT;
}
$hasError = true;
} else {
if (!$this->quiet) {
echo COLOR_GREEN . 'OK';
echo Colors::GREEN . 'OK';
}
}
$zoneFile = $this->localZonesDir . $domain->getName();
if (!file_exists(filename: $zoneFile)) {
echo ' Missing zone file for ' . COLOR_YELLOW . $zoneFile . COLOR_DEFAULT;
echo ' Missing zone file for ' . Colors::YELLOW . $zoneFile . Colors::DEFAULT;
$hasError = true;
}
@ -316,7 +318,7 @@ class DomainController
}
}
if (!$this->quiet) {
echo COLOR_DEFAULT . PHP_EOL;
echo Colors::DEFAULT . PHP_EOL;
}
}
@ -366,7 +368,7 @@ class DomainController
return true;
} else {
if (!$this->quiet) {
echo COLOR_RED . ' Error: ' . COLOR_DEFAULT . 'unable to create ' . COLOR_YELLOW . $this->localZonesDir . $domainName . COLOR_DEFAULT . PHP_EOL;
echo Colors::RED . ' Error: ' . Colors::DEFAULT . 'unable to create ' . Colors::YELLOW . $this->localZonesDir . $domainName . Colors::DEFAULT . PHP_EOL;
}
return false;
}

View File

@ -58,7 +58,7 @@ class EncryptionController
$plain = sodium_crypto_secretbox_open(ciphertext: $ciphertext, nonce: $nonce, key: $binKey);
if ($plain === false) {
throw new Exception(message: ' Incorrect key.');
throw new Exception(message: ' Incorrect key.' . PHP_EOL);
}
sodium_memzero(string: $ciphertext);
sodium_memzero(string: $key);

View File

@ -10,39 +10,40 @@ use App\Repository\ApikeyRepository;
use App\Repository\DomainRepository;
use App\Repository\DynDNSRepository;
use App\Repository\PanelRepository;
use App\Service\ApiClient;
use Monolog\Logger;
use OpenApi\Attributes as OAT;
use OpenApi\Attributes as OA;
use OpenApi\Attributes\OpenApi;
use OpenApi\Generator;
use UnhandledMatchError;
use function Symfony\Component\String\s;
// TODO attributes for swaggerUI
/**
*
*/
#[OAT\Info(version: '0.0.1', title: 'bindAPI')]
#[OAT\Server(
#[OA\Info(version: VERSION, title: 'bindAPI')]
#[OA\Server(
url: "{schema}://{hostname}/api",
description: "The bindAPI URL.",
variables: [
new OAT\ServerVariable(
serverVariable: "schema",
default: "https",
enum: ["https", "http"]
new OA\ServerVariable(
serverVariable: 'schema',
default: 'https',
enum: ['http', 'https']
),
new OAT\ServerVariable(
serverVariable: "hostname",
default: "ns2.24unix.net",
new OA\ServerVariable(
serverVariable: 'hostname',
default: DEFAULT_NS,
enum: NAMESERVERS
)
]
)]
#[OAT\Tag(
#[OA\Tag(
name: "Server"
)]
#[OAT\SecurityScheme(
#[OA\SecurityScheme(
securityScheme: "Authorization",
type: "apiKey",
description: "description",
description: "Api Authentication",
name: "X-API-Key",
in: "header"
)]
@ -56,60 +57,96 @@ 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,
private readonly DynDNSRepository $dynDNSRepository,
private readonly PanelRepository $panelRepository,
private readonly ConfigController $configController,
private readonly EncryptionController $encryptionController,
private readonly Logger $logger)
{
$this->status = '';
$this->response = '';
$this->message = '';
$this->result = [];
}
// server tag
private string $baseDir;
/**
* @return void
*/
#[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: [],
tags: ['Domains'],
#[OA\Get(
path: '/ping',
operationId: 'ping',
description: 'Checks for connectivity and valid APIkey',
security: [
['Authorization' => []]
],
tags: ['Server'],
responses: [
new OAT\Response(
new OA\Response(
response: 200,
description: 'OK'
),
new OAT\Response(
new OA\Response(
response: 401,
description: 'API key is missing or invalid.'
)
]
)]
private function handlePing(): void
{
if ($this->validateApiKey()) {
$this->status = '200 OK';
$this->response = 'pong';
} else {
$this->status = '401 Unauthorized';
$this->message = 'API key is missing or invalid';
}
}
#[OA\Get(
path: '/version',
operationId: 'version',
description: 'Check the API version of the nameserver.',
security: [
['Authorization' => []]
],
tags: ['Server'],
responses: [
new OA\Response(
response: 200,
description: 'x.y.z, aka major, minor, patch'
),
new OA\Response(
response: 401,
description: 'API key is missing or invalid.'
)
]
)]
private function getVersion(): void
{
if ($this->validateApiKey()) {
$this->status = '200 OK';
$composerJson = json_decode(json: file_get_contents(filename: $this->baseDir . 'composer.json'));
$version = $composerJson->version;
$buildNumber = $composerJson->build_number;
$this->result = [
'version' => $version,
'buildnumber' => $buildNumber,
];
} else {
$this->status = '401 Unauthorized';
$this->message = 'API key is missing or invalid';
}
}
#[OA\Get(
path: '/domains',
operationId: 'getAllDomains',
description: 'Returns a list of all domains on this server.',
summary: 'List all domains.',
security: [
['Authorization' => []]
],
tags: ['Domains'],
responses: [
new OA\Response(
response: 200,
description: 'OK'
),
new OA\Response(
response: 401,
description: 'API key is missing or invalid.'
),
new OAT\Response(
new OA\Response(
response: 404,
description: 'Domain not found.'
)]
@ -131,16 +168,6 @@ class RequestController
/**
*/
private function handlePing(): void
{
if ($this->checkPassword()) {
$this->status = '200 OK';
$this->response = 'pong';
} else {
$this->status = '401 Unauthorized';
$this->message = 'API key is missing or invalid';
}
}
/**
@ -148,7 +175,7 @@ class RequestController
*/
private function handleDomains(): void
{
if ($this->checkPassword()) {
if ($this->validateApiKey()) {
try {
match ($this->requestMethod) {
'GET' => $this->handleDomainsGetRequest(),
@ -164,131 +191,8 @@ class RequestController
}
/**
* @OA\Tag(name = "Server")
* @OA\Get(
* path = "/ping",
* summary = "Returning pong.",
* description = "Can be used to check API or server availability.",
* tags={"Server"},
* @OA\Response(response = "200", description = "OK"),
* @OA\Response(response = "401", description = "API key is missing or invalid."),
* security={
* {"Authorization":{"read"}}
* }
* )
*
* @OA\Tag(name = "Domains")
* @OA\Put(
* path="/domains/{name}",
* summary="Updates a domain.",
* description="Updates a domain. Only supplied fields will be updated, existing won't be affected.",
* tags={"Domains"},
* @OA\Response(response="200", description="OK"),
* @OA\Response(response = "401", description = "API key is missing or invalid."),
* @OA\Response(response="404", description="Domain not found."),
* security={
* {"Authorization":{"read":"write"}}
* }
* )
* @OA\Delete (
* path="/domains/{name}",
* summary="Deletes a domain.",
* description="Deletes a domain.",
* tags={"Domains"},
* @OA\Response(response="200", description="OK"),
* @OA\Response(response = "401", description = "API key is missing or invalid."),
* @OA\Response(response="404", description="Domain not found."),
* security={
* {"Authorization":{"read":"write"}}
* }
* )
* @param string $requestMethod
* @param array $uri
*
* @return void
*/
#[
OAT\Get(
path: '/domains/{name}',
operationId: 'getSingleDomain',
description: 'Returns information of a single domain specified by its domain name.',
summary: 'Returns a single domain.',
security: [
],
tags: ['Domains'],
parameters: [
new OAT\Parameter(name: 'name', in: 'path', required: true, schema: new OAT\Schema(type: 'string')),
],
responses: [
new OAT\Response(
response: 200,
description: 'OK'
),
new OAT\Response(
response: 401,
description: 'API key is missing or invalid.'
),
new OAT\Response(
response: 404,
description: 'Domain not found.'
)]
)]
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
private function validateApiKey(): bool
{
$headers = array_change_key_case(array: getallheaders(), case: CASE_UPPER);
$apiKey = $headers['X-API-KEY'] ?? '';
@ -318,10 +222,33 @@ class RequestController
return true;
}
#[OA\Get(
path: '/domains/{name}',
operationId: 'getSingleDomain',
description: 'Returns information of a single domain specified by its domain name.',
summary: 'Returns a single domain.',
security: [
['Authorization' => []]
],
tags: ['Domains'],
parameters: [
new OA\Parameter(name: 'name', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(