Repository navigation
Expand file tree
/
Copy pathPluginAdminbolt.php
More file actions
601 lines (494 loc) · 20.4 KB
/
Copy pathPluginAdminbolt.php
File metadata and controls
601 lines (494 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
<?php
use Composer\CaBundle\CaBundle;
require_once 'modules/admin/models/ServerPlugin.php';
class PluginAdminbolt extends ServerPlugin
{
public $features = [
'packageName' => true,
'testConnection' => true,
'showNameservers' => false,
'directlink' => true,
'upgrades' => true
];
private const ACCOUNT_ID_FIELD = 'Server Acct Properties';
private const DEFAULT_PORT = '8443';
private const MAX_RETRIES = 2;
private const MAX_RETRY_WAIT = 30;
private ?int $lastStatus = null;
private array $lastResponse = [];
public function getVariables(): array
{
$variables = [
'Name' => [
'type' => 'hidden',
'description' => 'Used by CE to show plugin',
'value' => 'AdminBolt'
],
'Description' => [
'type' => 'hidden',
'description' => 'Description viewable by admin in server settings',
'value' => 'AdminBolt control panel integration'
],
'API Key' => [
'type' => 'text',
'description' => 'API key from Security > API Keys in the AdminBolt admin panel (or the reseller panel when using the reseller API).',
'value' => ''
],
'API Secret' => [
'type' => 'password',
'description' => 'API secret shown once when the key pair was created.',
'value' => '',
'encryptable' => true
],
'Port' => [
'type' => 'text',
'description' => 'AdminBolt panel port. Defaults to 8443.',
'value' => self::DEFAULT_PORT
],
'Use Reseller API' => [
'type' => 'yesno',
'description' => 'Enable when the key pair above is a reseller key. Accounts are then created under that reseller and only its own plans can be used.',
'value' => '0'
],
'Verify SSL Certificate' => [
'type' => 'yesno',
'description' => 'Verify the panel SSL certificate. Only disable this for panels using a self-signed certificate.',
'value' => '1'
],
'Actions' => [
'type' => 'hidden',
'description' => 'Current actions that are active for this plugin per server',
'value' => 'Create,Delete,Suspend,UnSuspend'
],
'Registered Actions For Customer' => [
'type' => 'hidden',
'description' => 'Current actions that are active for this plugin per server for customers',
'value' => ''
],
'package_addons' => [
'type' => 'hidden',
'description' => 'Supported signup addons variables',
'value' => []
],
'package_vars' => [
'type' => 'hidden',
'description' => 'Whether package settings are set',
'value' => '0'
],
'package_vars_values' => [
'type' => 'hidden',
'description' => 'Package Settings',
'value' => []
]
];
return $variables;
}
public function validateCredentials($args)
{
}
public function doCreate($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage);
$this->create($args);
return sprintf('%s has been created.', $userPackage->getCustomField('Domain Name'));
}
public function doDelete($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage);
$this->delete($args);
return sprintf('%s has been deleted.', $userPackage->getCustomField('Domain Name'));
}
public function doUpdate($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage, $args);
$this->update($args);
return sprintf('%s has been updated.', $userPackage->getCustomField('Domain Name'));
}
public function doSuspend($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage);
$this->suspend($args);
return sprintf('%s has been suspended.', $userPackage->getCustomField('Domain Name'));
}
public function doUnSuspend($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$args = $this->buildParams($userPackage);
$this->unsuspend($args);
return sprintf('%s has been unsuspended.', $userPackage->getCustomField('Domain Name'));
}
public function create($args): void
{
$userPackage = new UserPackage($args['package']['id']);
$domain = trim((string) $args['package']['domain_name']);
if ($domain === '') {
throw new CE_Exception('A domain name is required to create an AdminBolt account.');
}
$username = trim((string) $args['package']['username']);
$password = (string) $args['package']['password'];
$data = [
'domain' => $domain,
'hosting_plan' => $this->getPlanName($args)
];
if ($username !== '') {
$data['username'] = $username;
}
if ($password !== '') {
$data['password'] = $password;
}
try {
$response = $this->request($args, 'POST', 'hosting-accounts', $data);
} catch (CE_Exception $e) {
if (!isset($data['username']) || !$this->isUsernameFormatError()) {
throw $e;
}
// AdminBolt rolls back a failed create, so resend without the username and let the panel derive one from the domain
CE_Lib::log(4, 'AdminBolt rejected username "' . $username . '" as an invalid format, retrying with a panel generated username');
unset($data['username']);
$response = $this->request($args, 'POST', 'hosting-accounts', $data);
}
$accountId = $response['id'] ?? ($response['hostingAccount']['id'] ?? null);
if (empty($accountId)) {
throw new CE_Exception(sprintf('AdminBolt created the account for %s but did not return an account id.', $domain));
}
$userPackage->setCustomField(self::ACCOUNT_ID_FIELD, (string) $accountId);
$panelUsername = (string) ($response['username'] ?? ($response['hostingAccount']['username'] ?? ''));
if ($panelUsername !== '' && $panelUsername !== $username) {
$userPackage->setCustomField('User Name', $panelUsername);
}
if ($password === '' && !empty($response['password'])) {
$userPackage->setCustomField('Password', (string) $response['password']);
}
}
public function delete($args): void
{
$userPackage = new UserPackage($args['package']['id']);
$accountId = $this->findAccountId($args);
if ($accountId === null) {
CE_Lib::log(4, 'AdminBolt: no account found for package ' . $args['package']['id'] . ', treating as already terminated');
$userPackage->setCustomField(self::ACCOUNT_ID_FIELD, '');
return;
}
// A 404 means the account is already gone on the panel, so let the cancellation complete
$this->request($args, 'DELETE', 'hosting-accounts/' . $accountId, [], [], [404]);
$userPackage->setCustomField(self::ACCOUNT_ID_FIELD, '');
}
public function suspend($args): void
{
$accountId = $this->getAccountId($args);
$this->request($args, 'POST', 'hosting-accounts/' . $accountId . '/suspend');
}
public function unsuspend($args): void
{
$accountId = $this->getAccountId($args);
$this->request($args, 'POST', 'hosting-accounts/' . $accountId . '/unsuspend');
}
public function update($args): void
{
$accountId = $this->getAccountId($args);
$unsupported = [];
foreach ($args['changes'] as $key => $value) {
switch ($key) {
case 'password':
$this->request($args, 'POST', 'hosting-accounts/' . $accountId . '/change-password', [
'password' => (string) $value
]);
break;
case 'package':
$this->request($args, 'PUT', 'hosting-accounts/' . $accountId, [
'hosting_plan' => $this->getPlanName($args)
]);
break;
case 'domain':
$unsupported[] = 'AdminBolt does not allow changing the main domain of an account.';
break;
case 'username':
$unsupported[] = 'AdminBolt does not allow changing the username of an account.';
break;
}
}
if (!empty($unsupported)) {
throw new CE_Exception(implode("\n", $unsupported));
}
}
public function getAvailableActions($userPackage): array
{
$args = $this->buildParams($userPackage);
$account = $this->lookupAccount($args);
if ($account === null) {
return ['Create'];
}
if (!empty($account['id']) && $userPackage->getCustomField(self::ACCOUNT_ID_FIELD) != $account['id']) {
$userPackage->setCustomField(self::ACCOUNT_ID_FIELD, (string) $account['id']);
}
$actions = [];
$suspended = $this->isSuspended($account);
if ($suspended === null) {
// Suspend and unsuspend are idempotent on AdminBolt, so offering both is safe when the state is unknown
$actions[] = 'Suspend';
$actions[] = 'UnSuspend';
} elseif ($suspended) {
$actions[] = 'UnSuspend';
} else {
$actions[] = 'Suspend';
}
$actions[] = 'Delete';
return $actions;
}
public function testConnection($args): void
{
CE_Lib::log(4, 'Testing connection to AdminBolt');
$response = $this->request($args, 'GET', 'health');
if (($response['status'] ?? '') !== 'ok') {
throw new CE_Exception('AdminBolt health check did not return an ok status.');
}
}
public function getDirectLink($userPackage, $getRealLink = true, $fromAdmin = false, $isReseller = false): array
{
$linkText = 'Login to AdminBolt';
if ($fromAdmin) {
return [
'cmd' => 'panellogin',
'label' => $linkText
];
}
if (!$getRealLink) {
$link = 'index.php?fuse=clients&controller=products&action=openpackagedirectlink&packageId=' . $userPackage->getId() . '&sessionHash=' . CE_Lib::getSessionHash();
return [
'fa' => 'fa fa-user fa-fw',
'link' => $link,
'text' => $linkText,
'form' => ''
];
}
$args = $this->buildParams($userPackage);
$accountId = $this->getAccountId($args);
$response = $this->request($args, 'POST', 'hosting-accounts/' . $accountId . '/generate-sso-token');
if (empty($response['sso_url'])) {
throw new CE_Exception('AdminBolt did not return a login URL.');
}
return [
'fa' => 'fa fa-user fa-fw',
'link' => $response['sso_url'],
'text' => $linkText,
'form' => ''
];
}
public function dopanellogin($args): string
{
$userPackage = new UserPackage($args['userPackageId']);
$response = $this->getDirectLink($userPackage);
return $response['link'];
}
private function getAccountId(array $args): int
{
$accountId = $this->findAccountId($args);
if ($accountId === null) {
throw new CE_Exception(sprintf('Unable to find the account for %s on AdminBolt.', $args['package']['domain_name']));
}
return $accountId;
}
private function findAccountId(array $args): ?int
{
$userPackage = new UserPackage($args['package']['id']);
$storedId = $userPackage->getCustomField(self::ACCOUNT_ID_FIELD);
if (is_numeric($storedId) && (int) $storedId > 0) {
return (int) $storedId;
}
// Nothing stored yet (imported or older service), so re-link on the unique username
$account = $this->lookupAccount($args);
if ($account === null || empty($account['id'])) {
return null;
}
$userPackage->setCustomField(self::ACCOUNT_ID_FIELD, (string) $account['id']);
return (int) $account['id'];
}
private function lookupAccount(array $args): ?array
{
$username = trim((string) $args['package']['username']);
if ($username === '') {
return null;
}
$response = $this->request($args, 'GET', 'hosting-accounts', [], ['username' => $username]);
foreach ($this->extractList($response) as $account) {
if (is_array($account) && ($account['username'] ?? '') === $username) {
return $account;
}
}
return null;
}
private function extractList(?array $response): array
{
if (empty($response)) {
return [];
}
if (isset($response['data']) && is_array($response['data'])) {
return $response['data'];
}
return array_is_list($response) ? $response : [];
}
private function isSuspended(array $account): ?bool
{
foreach (['suspended', 'is_suspended'] as $field) {
if (array_key_exists($field, $account)) {
return filter_var($account[$field], FILTER_VALIDATE_BOOLEAN);
}
}
if (isset($account['status']) && is_string($account['status'])) {
return mb_strtolower($account['status']) === 'suspended';
}
return null;
}
private function isUsernameFormatError(): bool
{
if ($this->lastStatus !== 422) {
return false;
}
$texts = [(string) ($this->lastResponse['message'] ?? '')];
$errors = $this->lastResponse['errors'] ?? [];
if (is_array($errors)) {
foreach ($errors as $fieldErrors) {
foreach ((array) $fieldErrors as $fieldError) {
$texts[] = (string) $fieldError;
}
}
}
foreach ($texts as $text) {
if (mb_stripos($text, 'invalid username format') !== false) {
return true;
}
}
return false;
}
private function getPlanName(array $args): string
{
$plan = trim((string) $args['package']['name_on_server']);
if ($plan === '') {
throw new CE_Exception('No package name on server is set. Enter the AdminBolt hosting plan name on the package.');
}
return $plan;
}
private function getBaseUrl(array $args): string
{
$host = trim((string) $args['server']['variables']['ServerHostName']);
$host = preg_replace('#^https?://#iu', '', $host);
$host = preg_replace('#/.*$#u', '', $host);
if ($host === '') {
throw new CE_Exception('The server hostname is not set.');
}
$port = trim((string) ($args['server']['variables']['plugin_adminbolt_Port'] ?? ''));
if (!ctype_digit($port)) {
$port = self::DEFAULT_PORT;
}
if (!preg_match('/:\d+$/u', $host)) {
$host .= ':' . $port;
}
$prefix = !empty($args['server']['variables']['plugin_adminbolt_Use_Reseller_API']) ? '/api/reseller' : '/api';
return 'https://' . $host . $prefix;
}
private function request(array $args, string $method, string $endpoint, array $data = [], array $query = [], array $passStatuses = []): ?array
{
$url = $this->getBaseUrl($args) . '/' . $endpoint;
if (!empty($query)) {
$url .= '?' . http_build_query($query);
}
$headers = [
'Accept: application/json',
'Content-Type: application/json',
'X-API-Key: ' . $args['server']['variables']['plugin_adminbolt_API_Key'],
'X-API-Secret: ' . $args['server']['variables']['plugin_adminbolt_API_Secret']
];
$verifySsl = ($args['server']['variables']['plugin_adminbolt_Verify_SSL_Certificate'] ?? '1') == '1';
$attempt = 0;
$this->lastStatus = null;
$this->lastResponse = [];
while (true) {
$retryAfter = 0;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 15,
CURLOPT_TIMEOUT => 180,
CURLOPT_HEADERFUNCTION => function ($ch, string $header) use (&$retryAfter): int {
if (preg_match('/^Retry-After:\s*(\d+)/iu', $header, $matches)) {
$retryAfter = (int) $matches[1];
}
return mb_strlen($header, '8bit');
}
]);
if (in_array($method, ['POST', 'PUT'], true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, empty($data) ? '{}' : json_encode($data));
}
if ($verifySsl) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, CaBundle::getSystemCaRootBundlePath());
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
}
$body = curl_exec($ch);
if ($body === false) {
throw new CE_Exception(sprintf('Unable to connect to AdminBolt: %s', curl_error($ch)));
}
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
// Never log bodies here: create responses can contain the account password
CE_Lib::log(4, 'AdminBolt ' . $method . ' /' . $endpoint . ' returned HTTP ' . $status);
if ($status === 429 && $attempt < self::MAX_RETRIES) {
$attempt++;
sleep(min(max($retryAfter, 1), self::MAX_RETRY_WAIT));
continue;
}
break;
}
$decoded = json_decode((string) $body, true);
$this->lastStatus = $status;
$this->lastResponse = is_array($decoded) ? $decoded : [];
if (in_array($status, $passStatuses, true)) {
return null;
}
if ($status >= 200 && $status < 300) {
return $this->lastResponse;
}
throw new CE_Exception($this->buildErrorMessage($status, $this->lastResponse));
}
private function buildErrorMessage(int $status, array $decoded): string
{
$message = (string) ($decoded['message'] ?? ($decoded['error'] ?? ''));
if (!empty($decoded['errors']) && is_array($decoded['errors'])) {
$details = [];
foreach ($decoded['errors'] as $fieldErrors) {
foreach ((array) $fieldErrors as $fieldError) {
$details[] = (string) $fieldError;
}
}
if (!empty($details)) {
$message = implode(' ', array_unique(array_merge([$message], $details)));
}
}
$message = trim($message);
if ($status >= 300 && $status < 400) {
return sprintf('AdminBolt redirected the request (HTTP %d). Check the hostname and port.', $status);
}
if ($status === 401 || $status === 403) {
return sprintf('AdminBolt rejected the API credentials (HTTP %d): %s', $status, $message);
}
if ($status === 404) {
return 'The account was not found on AdminBolt (HTTP 404). It may have been removed directly in the panel.';
}
if ($status === 429) {
return 'AdminBolt rate limit reached. Please try again in a minute.';
}
if ($message === '') {
return sprintf('AdminBolt returned HTTP %d with no error message.', $status);
}
return sprintf('AdminBolt returned HTTP %d: %s', $status, $message);
}
}