From e6b8e55890178b9f94624be3503fb37cfb342ef5 Mon Sep 17 00:00:00 2001 From: Grzegorz Date: Sun, 29 Nov 2026 20:01:54 +0100 Subject: [PATCH 1/4] feat(panelica): fulfil dedicated IPv4 add-ons --- docs/developer/addon-executor.md | 26 + lang/de/panelica.php | 22 + lang/en/panelica.php | 22 + lang/pl/panelica.php | 22 + lang/tr/panelica.php | 22 + lang/zh/panelica.php | 22 + modules/Servers/Panelica/PanelicaModule.php | 512 +++++++++++++++++++- tests/Feature/PanelicaDedicatedIpv4Test.php | 268 ++++++++++ 8 files changed, 907 insertions(+), 9 deletions(-) create mode 100644 tests/Feature/PanelicaDedicatedIpv4Test.php diff --git a/docs/developer/addon-executor.md b/docs/developer/addon-executor.md index 0a3408ca1..8c492ff2a 100644 --- a/docs/developer/addon-executor.md +++ b/docs/developer/addon-executor.md @@ -233,6 +233,32 @@ guarded by both the environment and `ADDONS_TEST_MODULE_ENABLED`. Outside that guard it throws `AddonModuleUnavailableException`, which the executor records as `unsupported` rather than retrying. +## Panelica dedicated IPv4 + +The Panelica hosting module implements `ServiceAddonModuleInterface` for one +add-on: a single dedicated IPv4 address. Configure the product add-on as: + +```text +fulfillment_module = panelica +operation = increment +parameter = dedicated_ipv4 +value = 1 +unit = (empty) +auto_fulfill = on +``` + +On apply the module reads `GET /v1/ip-addresses/available`, skips IPv6, primary +and already assigned addresses, and patches the service account with +`PATCH /v1/accounts/{id}` and `ip_address_ids` (the existing ids plus the new +one). It records the chosen id under +`service.module_data['dedicated_ipv4']['executions'][execution_id]` before the +remote write, so a retry reuses the same address instead of allocating another. + +On removal the module only unassigns the address recorded for the applied +execution. It refuses to remove the primary address or an address assigned to +another account, leaving those for manual review. It never deletes the IP +resource itself. + ## Example executor use ```php diff --git a/lang/de/panelica.php b/lang/de/panelica.php index 6953bf134..167b37dc0 100644 --- a/lang/de/panelica.php +++ b/lang/de/panelica.php @@ -96,4 +96,26 @@ 'unsupported_action' => 'Nicht unterstützte Aktion.', 'unsupported_record_type' => 'Nicht unterstützter Eintragstyp.', 'upload_unavailable' => 'Auf diesem Server ist das Hochladen von Dateien noch nicht verfügbar.', + 'ip_addon_absent' => 'Für dieses Add-on ist keine dedizierte IPv4-Adresse gespeichert.', + 'ip_addon_status' => 'Status des dedizierten IPv4-Add-ons geladen.', + 'ip_addon_valid' => 'Das dedizierte IPv4-Add-on kann angewendet werden.', + 'ip_addon_invalid_parameter' => 'Nicht unterstützte Konfiguration des dedizierten IPv4-Add-ons.', + 'ip_addon_no_user' => 'Für diesen Dienst wurde keine Panelica-Benutzer-ID gefunden.', + 'ip_addon_account_failed' => 'Die IP-Adressen des Panelica-Kontos konnten nicht gelesen werden.', + 'ip_addon_already_removed_apply' => 'Die dedizierte IPv4-Adresse wurde bereits entfernt und kann nicht erneut hinzugefügt werden.', + 'ip_addon_selection_failed' => 'Die verfügbaren IPv4-Adressen konnten nicht vom Panel gelesen werden.', + 'ip_addon_in_use' => 'Die gespeicherte IPv4-Adresse ist einem anderen Konto zugewiesen; manuelle Prüfung erforderlich.', + 'ip_addon_primary' => 'Die primäre IPv4-Adresse wird nicht entfernt.', + 'ip_addon_no_capacity' => 'Im Panel ist keine dedizierte IPv4-Adresse verfügbar.', + 'ip_addon_assign_failed' => 'Die IPv4-Adresse konnte nicht zugewiesen werden: :error', + 'ip_addon_verify_failed' => 'Das Panel hat die IPv4-Zuweisung nicht bestätigt.', + 'ip_addon_applied' => 'Dedizierte IPv4-Adresse :ip hinzugefügt.', + 'ip_addon_already_applied' => 'Die dedizierte IPv4-Adresse :ip ist bereits zugewiesen.', + 'ip_addon_missing_record' => 'Für dieses Add-on ist keine Zuweisung einer dedizierten IPv4-Adresse gespeichert; manuelle Prüfung erforderlich.', + 'ip_addon_release_failed' => 'Die IPv4-Adresse konnte nicht entfernt werden: :error', + 'ip_addon_release_verify_failed' => 'Das Panel hat das Entfernen der IPv4-Adresse nicht bestätigt.', + 'ip_addon_removed' => 'Dedizierte IPv4-Adresse :ip entfernt.', + 'ip_addon_already_removed' => 'Die dedizierte IPv4-Adresse :ip ist nicht zugewiesen.', + 'ip_addon_locked' => 'Für diesen Dienst läuft eine andere IPv4-Änderung; bitte später erneut versuchen.', + ]; diff --git a/lang/en/panelica.php b/lang/en/panelica.php index 14c81069f..44f5fbd4e 100644 --- a/lang/en/panelica.php +++ b/lang/en/panelica.php @@ -96,4 +96,26 @@ 'unsupported_action' => 'Unsupported action.', 'unsupported_record_type' => 'Unsupported record type.', 'upload_unavailable' => 'File upload is not available on this server yet.', + 'ip_addon_absent' => 'No dedicated IPv4 address is recorded for this add-on.', + 'ip_addon_status' => 'Dedicated IPv4 add-on status loaded.', + 'ip_addon_valid' => 'The dedicated IPv4 add-on can be applied.', + 'ip_addon_invalid_parameter' => 'Unsupported dedicated IPv4 add-on configuration.', + 'ip_addon_no_user' => 'Panelica user ID was not found for this service.', + 'ip_addon_account_failed' => 'Could not read the Panelica account IP addresses.', + 'ip_addon_already_removed_apply' => 'The dedicated IPv4 address was already removed and cannot be added again.', + 'ip_addon_selection_failed' => 'Could not read the available IPv4 addresses from the panel.', + 'ip_addon_in_use' => 'The recorded IPv4 address is assigned to another account; manual review is required.', + 'ip_addon_primary' => 'Refusing to remove the primary IPv4 address.', + 'ip_addon_no_capacity' => 'No dedicated IPv4 address is available on the panel.', + 'ip_addon_assign_failed' => 'Could not assign the IPv4 address: :error', + 'ip_addon_verify_failed' => 'The panel did not confirm the IPv4 assignment.', + 'ip_addon_applied' => 'Dedicated IPv4 address :ip added.', + 'ip_addon_already_applied' => 'Dedicated IPv4 address :ip is already assigned.', + 'ip_addon_missing_record' => 'No dedicated IPv4 assignment is recorded for this add-on; manual review is required.', + 'ip_addon_release_failed' => 'Could not remove the IPv4 address: :error', + 'ip_addon_release_verify_failed' => 'The panel did not confirm the IPv4 removal.', + 'ip_addon_removed' => 'Dedicated IPv4 address :ip removed.', + 'ip_addon_already_removed' => 'Dedicated IPv4 address :ip is not assigned.', + 'ip_addon_locked' => 'Another IPv4 change is in progress for this service; retry later.', + ]; diff --git a/lang/pl/panelica.php b/lang/pl/panelica.php index 79e6a8106..93ccedd2e 100644 --- a/lang/pl/panelica.php +++ b/lang/pl/panelica.php @@ -96,4 +96,26 @@ 'unsupported_action' => 'Nieobsługiwana operacja.', 'unsupported_record_type' => 'Nieobsługiwany typ rekordu.', 'upload_unavailable' => 'Przesyłanie plików nie jest jeszcze dostępne na tym serwerze.', + 'ip_addon_absent' => 'Dla tego dodatku nie zapisano dedykowanego adresu IPv4.', + 'ip_addon_status' => 'Odczytano status dodatku dedykowanego IPv4.', + 'ip_addon_valid' => 'Dodatek dedykowanego IPv4 można zastosować.', + 'ip_addon_invalid_parameter' => 'Nieobsługiwana konfiguracja dodatku dedykowanego IPv4.', + 'ip_addon_no_user' => 'Nie znaleziono identyfikatora użytkownika Panelica dla tej usługi.', + 'ip_addon_account_failed' => 'Nie udało się odczytać adresów IP konta Panelica.', + 'ip_addon_already_removed_apply' => 'Dedykowany adres IPv4 został już usunięty i nie można go dodać ponownie.', + 'ip_addon_selection_failed' => 'Nie udało się odczytać dostępnych adresów IPv4 z panelu.', + 'ip_addon_in_use' => 'Zapisany adres IPv4 jest przypisany do innego konta; wymagana jest ręczna weryfikacja.', + 'ip_addon_primary' => 'Odmowa usunięcia głównego adresu IPv4.', + 'ip_addon_no_capacity' => 'W panelu nie ma dostępnego dedykowanego adresu IPv4.', + 'ip_addon_assign_failed' => 'Nie udało się przypisać adresu IPv4: :error', + 'ip_addon_verify_failed' => 'Panel nie potwierdził przypisania adresu IPv4.', + 'ip_addon_applied' => 'Dodano dedykowany adres IPv4 :ip.', + 'ip_addon_already_applied' => 'Dedykowany adres IPv4 :ip jest już przypisany.', + 'ip_addon_missing_record' => 'Dla tego dodatku nie zapisano przypisania dedykowanego adresu IPv4; wymagana jest ręczna weryfikacja.', + 'ip_addon_release_failed' => 'Nie udało się usunąć adresu IPv4: :error', + 'ip_addon_release_verify_failed' => 'Panel nie potwierdził usunięcia adresu IPv4.', + 'ip_addon_removed' => 'Usunięto dedykowany adres IPv4 :ip.', + 'ip_addon_already_removed' => 'Dedykowany adres IPv4 :ip nie jest przypisany.', + 'ip_addon_locked' => 'Dla tej usługi trwa inna zmiana adresu IPv4; spróbuj ponownie później.', + ]; diff --git a/lang/tr/panelica.php b/lang/tr/panelica.php index 4a7da74dc..93c0630de 100644 --- a/lang/tr/panelica.php +++ b/lang/tr/panelica.php @@ -96,4 +96,26 @@ 'unsupported_action' => 'Desteklenmeyen işlem.', 'unsupported_record_type' => 'Desteklenmeyen kayıt türü.', 'upload_unavailable' => 'Bu sunucuda henüz dosya yüklenemiyor.', + 'ip_addon_absent' => 'Bu eklenti için kayıtlı özel bir IPv4 adresi yok.', + 'ip_addon_status' => 'Özel IPv4 eklentisinin durumu yüklendi.', + 'ip_addon_valid' => 'Özel IPv4 eklentisi uygulanabilir.', + 'ip_addon_invalid_parameter' => 'Desteklenmeyen özel IPv4 eklentisi yapılandırması.', + 'ip_addon_no_user' => 'Bu hizmet için Panelica kullanıcı kimliği bulunamadı.', + 'ip_addon_account_failed' => 'Panelica hesabının IP adresleri okunamadı.', + 'ip_addon_already_removed_apply' => 'Özel IPv4 adresi zaten kaldırılmış; yeniden eklenemez.', + 'ip_addon_selection_failed' => 'Panelden kullanılabilir IPv4 adresleri okunamadı.', + 'ip_addon_in_use' => 'Kayıtlı IPv4 adresi başka bir hesaba atanmış; elle inceleme gerekli.', + 'ip_addon_primary' => 'Birincil IPv4 adresini kaldırma reddedildi.', + 'ip_addon_no_capacity' => 'Panelde kullanılabilir özel IPv4 adresi yok.', + 'ip_addon_assign_failed' => 'IPv4 adresi atanamadı: :error', + 'ip_addon_verify_failed' => 'Panel IPv4 atamasını doğrulamadı.', + 'ip_addon_applied' => 'Özel IPv4 adresi :ip eklendi.', + 'ip_addon_already_applied' => 'Özel IPv4 adresi :ip zaten atanmış.', + 'ip_addon_missing_record' => 'Bu eklenti için özel IPv4 atama kaydı yok; elle inceleme gerekli.', + 'ip_addon_release_failed' => 'IPv4 adresi kaldırılamadı: :error', + 'ip_addon_release_verify_failed' => 'Panel IPv4 adresinin kaldırıldığını doğrulamadı.', + 'ip_addon_removed' => 'Özel IPv4 adresi :ip kaldırıldı.', + 'ip_addon_already_removed' => 'Özel IPv4 adresi :ip atanmamış.', + 'ip_addon_locked' => 'Bu hizmet için başka bir IPv4 değişikliği sürüyor; daha sonra tekrar deneyin.', + ]; diff --git a/lang/zh/panelica.php b/lang/zh/panelica.php index 4435fafd0..d515b5e2f 100644 --- a/lang/zh/panelica.php +++ b/lang/zh/panelica.php @@ -96,4 +96,26 @@ 'unsupported_action' => '不支持的操作。', 'unsupported_record_type' => '不支持的记录类型。', 'upload_unavailable' => '此服务器暂不支持上传文件。', + 'ip_addon_absent' => '此附加组件未记录专用 IPv4 地址。', + 'ip_addon_status' => '专用 IPv4 附加组件状态已加载。', + 'ip_addon_valid' => '可以应用专用 IPv4 附加组件。', + 'ip_addon_invalid_parameter' => '不受支持的专用 IPv4 附加组件配置。', + 'ip_addon_no_user' => '未找到此服务的 Panelica 用户 ID。', + 'ip_addon_account_failed' => '无法读取 Panelica 账户的 IP 地址。', + 'ip_addon_already_removed_apply' => '专用 IPv4 地址已被移除,无法重新添加。', + 'ip_addon_selection_failed' => '无法从面板读取可用的 IPv4 地址。', + 'ip_addon_in_use' => '已记录的 IPv4 地址已分配给其他账户;需要人工检查。', + 'ip_addon_primary' => '拒绝移除主 IPv4 地址。', + 'ip_addon_no_capacity' => '面板上没有可用的专用 IPv4 地址。', + 'ip_addon_assign_failed' => '无法分配 IPv4 地址::error', + 'ip_addon_verify_failed' => '面板未确认 IPv4 分配。', + 'ip_addon_applied' => '已添加专用 IPv4 地址 :ip。', + 'ip_addon_already_applied' => '专用 IPv4 地址 :ip 已分配。', + 'ip_addon_missing_record' => '此附加组件没有专用 IPv4 分配记录;需要人工检查。', + 'ip_addon_release_failed' => '无法移除 IPv4 地址::error', + 'ip_addon_release_verify_failed' => '面板未确认 IPv4 移除。', + 'ip_addon_removed' => '已移除专用 IPv4 地址 :ip。', + 'ip_addon_already_removed' => '专用 IPv4 地址 :ip 未分配。', + 'ip_addon_locked' => '此服务正在进行另一项 IPv4 更改;请稍后重试。', + ]; diff --git a/modules/Servers/Panelica/PanelicaModule.php b/modules/Servers/Panelica/PanelicaModule.php index 52120d5f0..e34902772 100644 --- a/modules/Servers/Panelica/PanelicaModule.php +++ b/modules/Servers/Panelica/PanelicaModule.php @@ -2,15 +2,22 @@ namespace Modules\Servers\Panelica; +use App\Contracts\HostsAccountDomains; +use App\Contracts\ServiceAddonModuleInterface; use App\Enums\ServiceStatus; +use App\Models\DockerAppCredential; +use App\Models\Product; use App\Models\Server; use App\Models\Service; +use App\Support\Addons\AddonInstruction; +use Illuminate\Http\Client\ConnectionException; use Illuminate\Http\Client\Response; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Modules\Servers\AbstractServerModule; -class PanelicaModule extends AbstractServerModule implements \App\Contracts\HostsAccountDomains +class PanelicaModule extends AbstractServerModule implements HostsAccountDomains, ServiceAddonModuleInterface { /** * Seconds to wait for the panel to accept a connection. A customer's page @@ -404,7 +411,6 @@ private function productConfigFor(Service $service): array return is_array($config) ? $config : []; } - /** * A per-service address for a customer who already has an account here. * @@ -1913,7 +1919,7 @@ public function deployContainer(Service $service, string $slug, string $name = ' // the panel carried on building it. try { $resp = $this->post($server, '/v1/docker/templates/'.rawurlencode($slug).'/deploy', $payload, timeout: self::DEPLOY_TIMEOUT); - } catch (\Illuminate\Http\Client\ConnectionException $e) { + } catch (ConnectionException $e) { return $this->buildResult(false, __('panelica.install_still_running')); } if ($resp->status() === 403) { @@ -2028,7 +2034,6 @@ private function ownsDomain(Service $service, string $domainId): bool return $domainId !== '' && array_key_exists($domainId, $this->accountDomains($service)); } - /** * Keep what the panel said about reaching a freshly installed app. * @@ -2055,7 +2060,7 @@ private function rememberAppAccess(Service $service, string $slug, array $data): } try { - \App\Models\DockerAppCredential::updateOrCreate( + DockerAppCredential::updateOrCreate( ['service_id' => $service->id, 'container_id' => $containerId], [ 'container_name' => (string) ($data['container_name'] ?? $slug), @@ -2073,11 +2078,11 @@ private function rememberAppAccess(Service $service, string $slug, array $data): /** * Access details for the apps on this service, keyed by container id. * - * @return array + * @return array */ public function containerAccessDetails(Service $service): array { - return \App\Models\DockerAppCredential::forService((int) $service->id); + return DockerAppCredential::forService((int) $service->id); } /** @@ -2307,7 +2312,7 @@ public function deleteContainer(Service $service, string $id): array // Measured after removing a container: the row stayed behind, so every // install-and-remove left an encrypted credential for something that no // longer exists. - \App\Models\DockerAppCredential::where('service_id', $service->id) + DockerAppCredential::where('service_id', $service->id) ->whereIn('container_id', $removed)->delete(); return $this->buildResult(true, __('panelica.app_removed')); @@ -2841,7 +2846,7 @@ private function fitUsage(Service $service, Server $server, string $accountId, s * * @return array{problems: list, warnings: list} */ - public function packageChangeProblems(Service $service, \App\Models\Product $newProduct): array + public function packageChangeProblems(Service $service, Product $newProduct): array { $out = ['problems' => [], 'warnings' => []]; // The account first: getServer() picks and records a server for a @@ -4319,6 +4324,495 @@ private function fileContext(Service $service): array return ($server && $accountId) ? [$server, $accountId] : [null, null]; } + // ------------------------------------------------------------------------- + // Dedicated IPv4 add-on + // ------------------------------------------------------------------------- + + /** + * The only technical add-on Panelica fulfils itself is one extra IPv4 + * address. The executor validates these capabilities before it calls the + * module, so a misconfigured product add-on is refused instead of being + * sent to the panel as an unknown instruction. + */ + public function addonCapabilities(): array + { + return [ + 'operations' => ['increment'], + 'parameters' => [ + 'dedicated_ipv4' => ['unit' => null, 'min' => 1, 'max' => 1], + ], + ]; + } + + public function validateAddon(Service $service, AddonInstruction $instruction): array + { + if ($instruction->operation !== 'increment' + || $instruction->parameter !== 'dedicated_ipv4' + || (float) $instruction->value !== 1.0) { + return $this->buildResult(false, __('panelica.ip_addon_invalid_parameter')); + } + + if (! $this->getServer($service)) { + return $this->buildResult(false, __('panelica.no_server')); + } + + if (trim((string) ($this->getModuleData($service)['panelica_user_id'] ?? '')) === '') { + return $this->buildResult(false, __('panelica.ip_addon_no_user')); + } + + return $this->buildResult(true, __('panelica.ip_addon_valid')); + } + + public function applyAddon(Service $service, AddonInstruction $instruction): array + { + if ($instruction->operation !== 'increment' || $instruction->parameter !== 'dedicated_ipv4') { + return $this->buildResult(false, __('panelica.ip_addon_invalid_parameter')); + } + + try { + return Cache::lock('panelica:ip-addon:'.$service->id, 60) + ->block(10, fn () => $this->applyDedicatedIpv4($service, $instruction)); + } catch (LockTimeoutException) { + return $this->buildResult(false, __('panelica.ip_addon_locked'), ['retryable' => true]); + } + } + + public function removeAddon(Service $service, AddonInstruction $instruction): array + { + try { + return Cache::lock('panelica:ip-addon:'.$service->id, 60) + ->block(10, fn () => $this->removeDedicatedIpv4($service, $instruction)); + } catch (LockTimeoutException) { + return $this->buildResult(false, __('panelica.ip_addon_locked'), ['retryable' => true]); + } + } + + public function getAddonStatus(Service $service, AddonInstruction $instruction): array + { + $state = $this->dedicatedIpv4State($service); + $key = $this->ipRecordKey($state, $instruction); + + if ($key === null) { + return $this->buildResult(true, __('panelica.ip_addon_absent'), ['applied' => false]); + } + + $record = $state['executions'][$key]; + + return $this->buildResult(true, __('panelica.ip_addon_status'), [ + 'applied' => ($record['status'] ?? '') === 'applied', + 'ip_id' => $record['ip_id'] ?? null, + 'ip_address' => $record['ip_address'] ?? null, + ]); + } + + private function applyDedicatedIpv4(Service $service, AddonInstruction $instruction): array + { + $server = $this->getServer($service); + if (! $server) { + return $this->buildResult(false, __('panelica.no_server'), ['retryable' => false]); + } + + $userId = trim((string) ($this->getModuleData($service)['panelica_user_id'] ?? '')); + if ($userId === '') { + return $this->buildResult(false, __('panelica.ip_addon_no_user'), ['retryable' => false]); + } + + $account = $this->accountIpIds($server, $userId); + if (! $account['success']) { + return $this->buildResult(false, __('panelica.ip_addon_account_failed'), [ + 'retryable' => $this->panelRetryable($account['status']), + ]); + } + + $state = $this->dedicatedIpv4State($service); + $key = $this->ipRecordKey($state, $instruction); + $record = $key !== null ? $state['executions'][$key] : null; + + if ($record !== null && ($record['status'] ?? '') === 'removed') { + return $this->buildResult(false, __('panelica.ip_addon_already_removed_apply'), ['retryable' => false]); + } + + if ($record !== null && ! empty($record['ip_id']) && in_array((string) $record['ip_id'], $account['ids'], true)) { + $this->markIpRecord($service, $state, $key, 'applied', []); + + return $this->buildResult(true, __('panelica.ip_addon_already_applied', [ + 'ip' => (string) ($record['ip_address'] ?? $record['ip_id']), + ]), ['idempotent' => true]); + } + + $ipId = $record !== null ? (string) ($record['ip_id'] ?? '') : ''; + $ip = null; + + if ($ipId !== '') { + $lookup = $this->ipAddress($server, $ipId); + + if (! $lookup['success']) { + return $this->buildResult(false, __('panelica.ip_addon_selection_failed'), [ + 'retryable' => $this->panelRetryable($lookup['status']), + ]); + } + + if ($lookup['ip'] !== null) { + $ip = $lookup['ip']; + $assigned = trim((string) ($ip['assigned_to_user_id'] ?? '')); + if ($assigned !== '' && $assigned !== $userId) { + return $this->buildResult(false, __('panelica.ip_addon_in_use'), ['retryable' => false]); + } + if (! empty($ip['is_primary'])) { + return $this->buildResult(false, __('panelica.ip_addon_primary'), ['retryable' => false]); + } + } + } + + if ($ip === null) { + $available = $this->availableIpv4($server); + + if (! $available['success']) { + return $this->buildResult(false, __('panelica.ip_addon_selection_failed'), [ + 'retryable' => $this->panelRetryable($available['status']), + ]); + } + + if ($available['ip'] === null) { + return $this->buildResult(false, __('panelica.ip_addon_no_capacity'), ['retryable' => true]); + } + + $ip = $available['ip']; + $ipId = (string) $ip['id']; + $key = (string) $instruction->executionId; + $record = [ + 'execution_id' => $instruction->executionId, + 'service_addon_id' => $instruction->serviceAddonId, + 'ip_id' => $ipId, + 'ip_address' => (string) ($ip['ip_address'] ?? ''), + 'status' => 'reserved', + 'reserved_at' => now()->toIso8601String(), + ]; + $state['executions'][$key] = $record; + $this->saveDedicatedIpv4State($service, $state); + } elseif (in_array($ipId, $account['ids'], true)) { + $this->markIpRecord($service, $state, $key, 'applied', []); + + return $this->buildResult(true, __('panelica.ip_addon_already_applied', [ + 'ip' => (string) ($record['ip_address'] ?? $ipId), + ]), ['idempotent' => true]); + } + + $ids = array_values(array_unique(array_merge($account['ids'], [$ipId]))); + $response = $this->patch($server, '/v1/accounts/'.rawurlencode($userId), ['ip_address_ids' => $ids]); + + if (! $response->successful()) { + $reason = (string) ($response->json('message') ?? $response->json('error') ?? $response->body()); + + return $this->buildResult(false, __('panelica.ip_addon_assign_failed', ['error' => $reason]), [ + 'retryable' => $this->panelRetryable($response->status()), + ]); + } + + $verified = $this->accountIpIds($server, $userId); + if (! $verified['success'] || ! in_array($ipId, $verified['ids'], true)) { + return $this->buildResult(false, __('panelica.ip_addon_verify_failed'), [ + 'retryable' => $verified['success'] ? true : $this->panelRetryable($verified['status']), + ]); + } + + $this->markIpRecord($service, $state, $key, 'applied', ['assigned_at' => now()->toIso8601String()]); + + return $this->buildResult(true, __('panelica.ip_addon_applied', [ + 'ip' => (string) ($ip['ip_address'] ?? $ipId), + ]), ['ip_id' => $ipId, 'ip_address' => (string) ($ip['ip_address'] ?? '')]); + } + + private function removeDedicatedIpv4(Service $service, AddonInstruction $instruction): array + { + $server = $this->getServer($service); + if (! $server) { + return $this->buildResult(false, __('panelica.no_server'), ['retryable' => false]); + } + + $userId = trim((string) ($this->getModuleData($service)['panelica_user_id'] ?? '')); + if ($userId === '') { + return $this->buildResult(false, __('panelica.ip_addon_no_user'), ['retryable' => false]); + } + + $state = $this->dedicatedIpv4State($service); + $key = $this->ipRecordKey($state, $instruction); + + if ($key === null) { + return $this->buildResult(false, __('panelica.ip_addon_missing_record'), ['manual_required' => true]); + } + + $record = $state['executions'][$key]; + if (($record['status'] ?? '') === 'removed') { + return $this->buildResult(true, __('panelica.ip_addon_already_removed', [ + 'ip' => (string) ($record['ip_address'] ?? $record['ip_id'] ?? ''), + ]), ['idempotent' => true]); + } + + $ipId = (string) ($record['ip_id'] ?? ''); + if ($ipId === '') { + return $this->buildResult(false, __('panelica.ip_addon_missing_record'), ['manual_required' => true]); + } + + $account = $this->accountIpIds($server, $userId); + if (! $account['success']) { + return $this->buildResult(false, __('panelica.ip_addon_account_failed'), [ + 'retryable' => $this->panelRetryable($account['status']), + ]); + } + + if (! in_array($ipId, $account['ids'], true)) { + $this->markIpRecord($service, $state, $key, 'removed', ['removed_at' => now()->toIso8601String()]); + + return $this->buildResult(true, __('panelica.ip_addon_already_removed', [ + 'ip' => (string) ($record['ip_address'] ?? $ipId), + ]), ['idempotent' => true]); + } + + $lookup = $this->ipAddress($server, $ipId); + if (! $lookup['success']) { + return $this->buildResult(false, __('panelica.ip_addon_release_failed', ['error' => $lookup['message']]), [ + 'retryable' => $this->panelRetryable($lookup['status']), + ]); + } + + if ($lookup['ip'] !== null) { + if (! empty($lookup['ip']['is_primary'])) { + return $this->buildResult(false, __('panelica.ip_addon_primary'), ['manual_required' => true]); + } + + $assigned = trim((string) ($lookup['ip']['assigned_to_user_id'] ?? '')); + if ($assigned !== '' && $assigned !== $userId) { + return $this->buildResult(false, __('panelica.ip_addon_in_use'), ['manual_required' => true]); + } + } + + $ids = array_values(array_filter($account['ids'], fn (string $id) => $id !== $ipId)); + $response = $this->patch($server, '/v1/accounts/'.rawurlencode($userId), ['ip_address_ids' => $ids]); + + if (! $response->successful()) { + $reason = (string) ($response->json('message') ?? $response->json('error') ?? $response->body()); + + return $this->buildResult(false, __('panelica.ip_addon_release_failed', ['error' => $reason]), [ + 'retryable' => $this->panelRetryable($response->status()), + ]); + } + + $verified = $this->accountIpIds($server, $userId); + if (! $verified['success'] || in_array($ipId, $verified['ids'], true)) { + return $this->buildResult(false, __('panelica.ip_addon_release_verify_failed'), [ + 'retryable' => $verified['success'] ? true : $this->panelRetryable($verified['status']), + ]); + } + + $this->markIpRecord($service, $state, $key, 'removed', ['removed_at' => now()->toIso8601String()]); + + return $this->buildResult(true, __('panelica.ip_addon_removed', [ + 'ip' => (string) ($record['ip_address'] ?? $ipId), + ]), ['ip_id' => $ipId]); + } + + /** @return array */ + private function dedicatedIpv4State(Service $service): array + { + $state = $this->getModuleData($service)['dedicated_ipv4'] ?? []; + if (! is_array($state)) { + return ['executions' => []]; + } + + if (! is_array($state['executions'] ?? null)) { + $state['executions'] = []; + } + + return $state; + } + + /** @param array $state */ + private function saveDedicatedIpv4State(Service $service, array $state): void + { + $this->setModuleData($service, ['dedicated_ipv4' => $state]); + } + + /** + * Find the record for this instruction, preferring the apply that a removal + * points at. The service-add-on id lets a retry of the same purchase find + * its reservation instead of allocating a second address. + * + * @param array $state + */ + private function ipRecordKey(array $state, AddonInstruction $instruction): ?string + { + $executions = $state['executions'] ?? []; + $candidates = array_filter([ + $instruction->appliedExecutionId !== null ? (string) $instruction->appliedExecutionId : null, + (string) $instruction->executionId, + ]); + + foreach ($candidates as $candidate) { + if (isset($executions[$candidate]) && is_array($executions[$candidate])) { + return $candidate; + } + } + + foreach ($executions as $key => $record) { + if (! is_array($record)) { + continue; + } + if ((int) ($record['service_addon_id'] ?? 0) === $instruction->serviceAddonId + && ($record['status'] ?? '') !== 'removed') { + return (string) $key; + } + } + + return null; + } + + /** @param array $state */ + private function markIpRecord(Service $service, array $state, string $key, string $status, array $extra): void + { + if (! isset($state['executions'][$key]) || ! is_array($state['executions'][$key])) { + return; + } + + $state['executions'][$key] = array_merge($state['executions'][$key], $extra, [ + 'status' => $status, + 'updated_at' => now()->toIso8601String(), + ]); + $this->saveDedicatedIpv4State($service, $state); + } + + /** + * The account's currently assigned address ids. A failed lookup is told + * apart from an account with no addresses, because only the first may be + * retried. + * + * @return array{success: bool, status: int, ids: array, message: string} + */ + private function accountIpIds(Server $server, string $userId): array + { + $response = $this->get($server, '/v1/accounts/'.rawurlencode($userId)); + + if (! $response->successful()) { + return [ + 'success' => false, + 'status' => $response->status(), + 'ids' => [], + 'message' => (string) ($response->json('message') ?? $response->json('error') ?? $response->body()), + ]; + } + + $account = $response->json('data') ?? $response->json(); + if (! is_array($account)) { + return ['success' => true, 'status' => $response->status(), 'ids' => [], 'message' => '']; + } + + $raw = $account['ip_addresses'] ?? $account['ip_address_ids'] ?? []; + + return [ + 'success' => true, + 'status' => $response->status(), + 'ids' => $this->normaliseIpIds($raw), + 'message' => '', + ]; + } + + private function normaliseIpIds(mixed $raw): array + { + if (! is_array($raw)) { + return []; + } + + $ids = []; + foreach ($raw as $entry) { + $id = is_array($entry) ? ($entry['id'] ?? null) : (is_string($entry) ? $entry : null); + $id = trim((string) $id); + if ($id !== '') { + $ids[] = $id; + } + } + + return array_values(array_unique($ids)); + } + + /** + * The first free IPv4 address on the panel. IPv6 and the server's primary + * address are never handed to a customer as an extra IPv4. + * + * @return array{success: bool, status: int, ip: array|null, message: string} + */ + private function availableIpv4(Server $server): array + { + $response = $this->get($server, '/v1/ip-addresses/available'); + + if (! $response->successful()) { + return [ + 'success' => false, + 'status' => $response->status(), + 'ip' => null, + 'message' => (string) ($response->json('message') ?? $response->json('error') ?? $response->body()), + ]; + } + + $rows = $response->json('data') ?? $response->json() ?? []; + if (! is_array($rows)) { + $rows = []; + } + + foreach ($rows as $row) { + if (! is_array($row)) { + continue; + } + + $type = strtolower(trim((string) ($row['ip_type'] ?? $row['type'] ?? 'ipv4'))); + $address = trim((string) ($row['ip_address'] ?? '')); + $id = trim((string) ($row['id'] ?? '')); + + if ($type !== 'ipv4' || $id === '' + || filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false + || ! empty($row['is_primary']) + || trim((string) ($row['assigned_to_user_id'] ?? '')) !== '') { + continue; + } + + return ['success' => true, 'status' => $response->status(), 'ip' => $row, 'message' => '']; + } + + return ['success' => true, 'status' => $response->status(), 'ip' => null, 'message' => '']; + } + + /** @return array{success: bool, status: int, ip: array|null, message: string} */ + private function ipAddress(Server $server, string $ipId): array + { + $response = $this->get($server, '/v1/ip-addresses/'.rawurlencode($ipId)); + + if ($response->status() === 404) { + return ['success' => true, 'status' => 404, 'ip' => null, 'message' => '']; + } + + if (! $response->successful()) { + return [ + 'success' => false, + 'status' => $response->status(), + 'ip' => null, + 'message' => (string) ($response->json('message') ?? $response->json('error') ?? $response->body()), + ]; + } + + $ip = $response->json('data') ?? $response->json(); + + return [ + 'success' => true, + 'status' => $response->status(), + 'ip' => is_array($ip) ? $ip : null, + 'message' => '', + ]; + } + + private function panelRetryable(int $status): bool + { + return $status === 0 || $status === 429 || $status >= 500; + } + public function testConnection(Server $server): bool { try { diff --git a/tests/Feature/PanelicaDedicatedIpv4Test.php b/tests/Feature/PanelicaDedicatedIpv4Test.php new file mode 100644 index 000000000..fa37fc96c --- /dev/null +++ b/tests/Feature/PanelicaDedicatedIpv4Test.php @@ -0,0 +1,268 @@ +set('addons.fulfillment.enabled', true); + Queue::fake(); +}); + +function panelicaIpv4Server(): Server +{ + return Server::factory()->create([ + 'type' => 'panelica', + 'hostname' => 'panel.ipv4.test', + 'ip_address' => '', + 'port' => 8443, + 'username' => 'admin', + 'password' => 'pk_live_key', + 'access_hash' => 'sk_live_secret', + 'active' => true, + 'disabled' => false, + ]); +} + +function panelicaIpv4Service(Server $server): Service +{ + return Service::factory()->create([ + 'client_id' => Client::factory()->create()->id, + 'product_id' => Product::factory()->create([ + 'group_id' => ProductGroup::factory()->create()->id, + 'server_type' => 'panelica', + ])->id, + 'server_id' => $server->id, + 'domain' => 'ipv4.test', + 'status' => 'active', + 'module_data' => ['panelica_user_id' => 'acct-1'], + ]); +} + +function panelicaIpv4Instruction( + int $executionId = 1, + int $serviceAddonId = 10, + ?int $appliedExecutionId = null +): AddonInstruction { + return new AddonInstruction( + executionId: $executionId, + serviceAddonId: $serviceAddonId, + operation: 'increment', + parameter: 'dedicated_ipv4', + value: 1, + unit: null, + options: [], + configurationHash: 'hash', + appliedExecutionId: $appliedExecutionId, + ); +} + +/** + * A panel with one IPv6 address, one IPv4 already assigned elsewhere and one + * free IPv4. The account already has its primary address. + * + * @param array $state + */ +function fakePanelicaIpv4Panel(array &$state): void +{ + $state = array_merge([ + 'assigned' => ['ip-primary'], + 'available' => [ + ['id' => 'ip-v6', 'ip_address' => '2001:db8::10', 'ip_type' => 'ipv6'], + ['id' => 'ip-taken', 'ip_address' => '198.51.100.9', 'ip_type' => 'ipv4', 'assigned_to_user_id' => 'acct-other'], + ['id' => 'ip-new', 'ip_address' => '198.51.100.10', 'ip_type' => 'ipv4'], + ], + 'patches' => [], + ], $state); + + Http::fake(function (Request $request) use (&$state) { + $url = $request->url(); + $method = $request->method(); + + if ($method === 'GET' && str_ends_with($url, '/v1/ip-addresses/available')) { + return Http::response(['data' => $state['available']], 200); + } + + if ($method === 'GET' && preg_match('#/v1/ip-addresses/([^/]+)$#', $url, $matches)) { + $id = rawurldecode($matches[1]); + $row = collect($state['available'])->firstWhere('id', $id) ?? [ + 'id' => $id, + 'ip_address' => $id === 'ip-primary' ? '198.51.100.1' : '198.51.100.10', + 'ip_type' => 'ipv4', + ]; + $row['is_primary'] = $id === 'ip-primary'; + $row['assigned_to_user_id'] = in_array($id, $state['assigned'], true) ? 'acct-1' : null; + + return Http::response(['data' => $row], 200); + } + + if ($method === 'GET' && str_ends_with($url, '/v1/accounts/acct-1')) { + return Http::response(['data' => [ + 'id' => 'acct-1', + 'ip_addresses' => array_map(fn (string $id) => ['id' => $id], $state['assigned']), + ]], 200); + } + + if ($method === 'PATCH' && str_ends_with($url, '/v1/accounts/acct-1')) { + $ids = $request->data()['ip_address_ids'] ?? []; + $state['assigned'] = array_values($ids); + $state['patches'][] = $ids; + + return Http::response(['data' => ['id' => 'acct-1']], 200); + } + + return Http::response(['message' => 'Unexpected request: '.$method.' '.$url], 404); + }); +} + +it('adds one free IPv4 address to the Panelica account', function () { + $state = []; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $result = (new PanelicaModule)->applyAddon($service, panelicaIpv4Instruction()); + + expect($result['success'])->toBeTrue() + ->and($state['assigned'])->toBe(['ip-primary', 'ip-new']) + ->and($state['patches'])->toBe([['ip-primary', 'ip-new']]) + ->and($service->fresh()->module_data['dedicated_ipv4']['executions']['1']['ip_id'])->toBe('ip-new') + ->and($service->fresh()->module_data['dedicated_ipv4']['executions']['1']['status'])->toBe('applied'); +}); + +it('does not allocate a second address when the same execution is applied again', function () { + $state = []; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $module = new PanelicaModule; + + expect($module->applyAddon($service, panelicaIpv4Instruction())['success'])->toBeTrue(); + + $patches = count($state['patches']); + $result = $module->applyAddon($service->fresh(), panelicaIpv4Instruction()); + + expect($result['success'])->toBeTrue() + ->and($result['data']['idempotent'])->toBeTrue() + ->and(count($state['patches']))->toBe($patches) + ->and($state['assigned'])->toBe(['ip-primary', 'ip-new']); +}); + +it('refuses cleanly when the panel has no free IPv4 address', function () { + $state = ['available' => [ + ['id' => 'ip-v6', 'ip_address' => '2001:db8::10', 'ip_type' => 'ipv6'], + ]]; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $result = (new PanelicaModule)->applyAddon($service, panelicaIpv4Instruction()); + + expect($result['success'])->toBeFalse() + ->and($result['data']['retryable'])->toBeTrue() + ->and($state['patches'])->toBe([]) + ->and($service->fresh()->module_data)->not->toHaveKey('dedicated_ipv4'); +}); + +it('releases only the address recorded for the applied add-on', function () { + $state = []; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $module = new PanelicaModule; + + expect($module->applyAddon($service, panelicaIpv4Instruction())['success'])->toBeTrue(); + + $result = $module->removeAddon($service->fresh(), panelicaIpv4Instruction(2, 10, 1)); + + expect($result['success'])->toBeTrue() + ->and($state['assigned'])->toBe(['ip-primary']) + ->and($state['patches'])->toHaveCount(2) + ->and($state['patches'][1])->toBe(['ip-primary']) + ->and($service->fresh()->module_data['dedicated_ipv4']['executions']['1']['status'])->toBe('removed'); +}); + +it('refuses to release a recorded address that became primary', function () { + $state = []; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $service->forceFill([ + 'module_data' => [ + 'panelica_user_id' => 'acct-1', + 'dedicated_ipv4' => ['executions' => [ + '1' => [ + 'execution_id' => 1, + 'service_addon_id' => 10, + 'ip_id' => 'ip-primary', + 'ip_address' => '198.51.100.1', + 'status' => 'applied', + ], + ]], + ], + ])->save(); + + $result = (new PanelicaModule)->removeAddon($service, panelicaIpv4Instruction(2, 10, 1)); + + expect($result['success'])->toBeFalse() + ->and($result['data']['manual_required'])->toBeTrue() + ->and($state['patches'])->toBe([]) + ->and($state['assigned'])->toBe(['ip-primary']); +}); + +it('completes apply and removal through the add-on executor', function () { + $state = []; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + + $definition = ProductAddon::create([ + 'name' => 'Dedicated IPv4', + 'hidden' => false, + 'retired' => false, + 'tax' => false, + 'fulfillment_module' => 'panelica', + 'operation' => 'increment', + 'parameter' => 'dedicated_ipv4', + 'value' => '1', + 'unit' => null, + 'options' => [], + 'auto_fulfill' => true, + ]); + + $serviceAddon = ServiceAddon::create([ + 'service_id' => $service->id, + 'addon_id' => $definition->id, + 'client_id' => $service->client_id, + 'qty' => 1, + 'amount' => 10, + 'billing_cycle' => 'Monthly', + 'status' => 'active', + 'fulfillment_config' => $definition->fulfillmentConfig(), + 'fulfillment_status' => AddonExecutionStatus::NotConfigured, + ]); + + $executor = app(AddonExecutionService::class); + + $apply = $executor->enqueueApply($serviceAddon); + expect($apply)->not->toBeNull() + ->and($executor->execute($apply))->toBeTrue() + ->and($apply->fresh()->status)->toBe(AddonExecutionStatus::Completed) + ->and($state['assigned'])->toBe(['ip-primary', 'ip-new']); + + $remove = $executor->enqueueRemoval($serviceAddon->fresh()); + expect($remove)->not->toBeNull() + ->and($executor->execute($remove))->toBeTrue() + ->and($remove->fresh()->status)->toBe(AddonExecutionStatus::Completed) + ->and($serviceAddon->fresh()->fulfillment_status)->toBe(AddonExecutionStatus::Cancelled) + ->and($state['assigned'])->toBe(['ip-primary']); +}); From 0c7de1b947109f514250dfa1dd16f4fc80ed5b0f Mon Sep 17 00:00:00 2001 From: Grzegorz Date: Sun, 29 Nov 2026 20:04:32 +0100 Subject: [PATCH 2/4] test(addons): keep the deferred dispatch out of the transaction --- tests/Feature/AddonExecutorTest.php | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/tests/Feature/AddonExecutorTest.php b/tests/Feature/AddonExecutorTest.php index 899d0ddde..f357763e7 100644 --- a/tests/Feature/AddonExecutorTest.php +++ b/tests/Feature/AddonExecutorTest.php @@ -612,12 +612,10 @@ function addonTestServiceAddon( ->and($again->status)->toBe(AddonExecutionStatus::Failed); /* - * One job, from the first call that created the pending execution. The - * assertion used to be assertNothingPushed(), which also forbids that - * first, correct dispatch: DB::afterCommit callbacks do run inside the - * test transaction here, so the job reaches the fake and the test failed - * on the behaviour it is meant to allow. What matters is that the second - * call, against an execution that has failed, adds nothing. + * The first call defers its job with DB::afterCommit, and this test's + * transaction ends only after the assertions, so no job reaches the fake + * yet. What matters is that the second call, against an execution that + * has failed, enqueues nothing. */ - Queue::assertPushed(ExecuteServiceAddonJob::class, 1); + Queue::assertNothingPushed(); }); From 73c86cde142e5629a1e1d563b7eda7be3786adf8 Mon Sep 17 00:00:00 2001 From: Grzegorz Date: Sun, 29 Nov 2026 20:33:31 +0100 Subject: [PATCH 3/4] fix(panelica): keep IPv4 reservations exclusive across retries --- lang/de/panelica.php | 1 + lang/en/panelica.php | 1 + lang/pl/panelica.php | 1 + lang/tr/panelica.php | 1 + lang/zh/panelica.php | 1 + modules/Servers/Panelica/PanelicaModule.php | 122 ++++++++++++++--- tests/Feature/PanelicaDedicatedIpv4Test.php | 137 ++++++++++++++++++++ 7 files changed, 244 insertions(+), 20 deletions(-) diff --git a/lang/de/panelica.php b/lang/de/panelica.php index 167b37dc0..e43882a49 100644 --- a/lang/de/panelica.php +++ b/lang/de/panelica.php @@ -104,6 +104,7 @@ 'ip_addon_account_failed' => 'Die IP-Adressen des Panelica-Kontos konnten nicht gelesen werden.', 'ip_addon_already_removed_apply' => 'Die dedizierte IPv4-Adresse wurde bereits entfernt und kann nicht erneut hinzugefügt werden.', 'ip_addon_selection_failed' => 'Die verfügbaren IPv4-Adressen konnten nicht vom Panel gelesen werden.', + 'ip_addon_claimed' => 'Die gespeicherte IPv4-Adresse wird noch von einem anderen Add-on beansprucht; manuelle Prüfung erforderlich.', 'ip_addon_in_use' => 'Die gespeicherte IPv4-Adresse ist einem anderen Konto zugewiesen; manuelle Prüfung erforderlich.', 'ip_addon_primary' => 'Die primäre IPv4-Adresse wird nicht entfernt.', 'ip_addon_no_capacity' => 'Im Panel ist keine dedizierte IPv4-Adresse verfügbar.', diff --git a/lang/en/panelica.php b/lang/en/panelica.php index 44f5fbd4e..a9f37c948 100644 --- a/lang/en/panelica.php +++ b/lang/en/panelica.php @@ -104,6 +104,7 @@ 'ip_addon_account_failed' => 'Could not read the Panelica account IP addresses.', 'ip_addon_already_removed_apply' => 'The dedicated IPv4 address was already removed and cannot be added again.', 'ip_addon_selection_failed' => 'Could not read the available IPv4 addresses from the panel.', + 'ip_addon_claimed' => 'The recorded IPv4 address is still claimed by another add-on; manual review is required.', 'ip_addon_in_use' => 'The recorded IPv4 address is assigned to another account; manual review is required.', 'ip_addon_primary' => 'Refusing to remove the primary IPv4 address.', 'ip_addon_no_capacity' => 'No dedicated IPv4 address is available on the panel.', diff --git a/lang/pl/panelica.php b/lang/pl/panelica.php index 93ccedd2e..a70524275 100644 --- a/lang/pl/panelica.php +++ b/lang/pl/panelica.php @@ -104,6 +104,7 @@ 'ip_addon_account_failed' => 'Nie udało się odczytać adresów IP konta Panelica.', 'ip_addon_already_removed_apply' => 'Dedykowany adres IPv4 został już usunięty i nie można go dodać ponownie.', 'ip_addon_selection_failed' => 'Nie udało się odczytać dostępnych adresów IPv4 z panelu.', + 'ip_addon_claimed' => 'Zapisany adres IPv4 jest nadal przypisany do innego dodatku; wymagana jest ręczna weryfikacja.', 'ip_addon_in_use' => 'Zapisany adres IPv4 jest przypisany do innego konta; wymagana jest ręczna weryfikacja.', 'ip_addon_primary' => 'Odmowa usunięcia głównego adresu IPv4.', 'ip_addon_no_capacity' => 'W panelu nie ma dostępnego dedykowanego adresu IPv4.', diff --git a/lang/tr/panelica.php b/lang/tr/panelica.php index 93c0630de..9bb019437 100644 --- a/lang/tr/panelica.php +++ b/lang/tr/panelica.php @@ -104,6 +104,7 @@ 'ip_addon_account_failed' => 'Panelica hesabının IP adresleri okunamadı.', 'ip_addon_already_removed_apply' => 'Özel IPv4 adresi zaten kaldırılmış; yeniden eklenemez.', 'ip_addon_selection_failed' => 'Panelden kullanılabilir IPv4 adresleri okunamadı.', + 'ip_addon_claimed' => 'Kayıtlı IPv4 adresi hâlâ başka bir eklenti tarafından talep ediliyor; elle inceleme gerekli.', 'ip_addon_in_use' => 'Kayıtlı IPv4 adresi başka bir hesaba atanmış; elle inceleme gerekli.', 'ip_addon_primary' => 'Birincil IPv4 adresini kaldırma reddedildi.', 'ip_addon_no_capacity' => 'Panelde kullanılabilir özel IPv4 adresi yok.', diff --git a/lang/zh/panelica.php b/lang/zh/panelica.php index d515b5e2f..2f0e251c3 100644 --- a/lang/zh/panelica.php +++ b/lang/zh/panelica.php @@ -104,6 +104,7 @@ 'ip_addon_account_failed' => '无法读取 Panelica 账户的 IP 地址。', 'ip_addon_already_removed_apply' => '专用 IPv4 地址已被移除,无法重新添加。', 'ip_addon_selection_failed' => '无法从面板读取可用的 IPv4 地址。', + 'ip_addon_claimed' => '已记录的 IPv4 地址仍被另一个附加组件占用;需要人工检查。', 'ip_addon_in_use' => '已记录的 IPv4 地址已分配给其他账户;需要人工检查。', 'ip_addon_primary' => '拒绝移除主 IPv4 地址。', 'ip_addon_no_capacity' => '面板上没有可用的专用 IPv4 地址。', diff --git a/modules/Servers/Panelica/PanelicaModule.php b/modules/Servers/Panelica/PanelicaModule.php index e34902772..09cdd1068 100644 --- a/modules/Servers/Panelica/PanelicaModule.php +++ b/modules/Servers/Panelica/PanelicaModule.php @@ -4369,9 +4369,14 @@ public function applyAddon(Service $service, AddonInstruction $instruction): arr return $this->buildResult(false, __('panelica.ip_addon_invalid_parameter')); } + $server = $this->getServer($service); + if (! $server) { + return $this->buildResult(false, __('panelica.no_server'), ['retryable' => false]); + } + try { - return Cache::lock('panelica:ip-addon:'.$service->id, 60) - ->block(10, fn () => $this->applyDedicatedIpv4($service, $instruction)); + return Cache::lock('panelica:ip-addon:server:'.$server->id, 60) + ->block(10, fn () => $this->applyDedicatedIpv4($service, $instruction, $server)); } catch (LockTimeoutException) { return $this->buildResult(false, __('panelica.ip_addon_locked'), ['retryable' => true]); } @@ -4379,9 +4384,14 @@ public function applyAddon(Service $service, AddonInstruction $instruction): arr public function removeAddon(Service $service, AddonInstruction $instruction): array { + $server = $this->getServer($service); + if (! $server) { + return $this->buildResult(false, __('panelica.no_server'), ['retryable' => false]); + } + try { - return Cache::lock('panelica:ip-addon:'.$service->id, 60) - ->block(10, fn () => $this->removeDedicatedIpv4($service, $instruction)); + return Cache::lock('panelica:ip-addon:server:'.$server->id, 60) + ->block(10, fn () => $this->removeDedicatedIpv4($service, $instruction, $server)); } catch (LockTimeoutException) { return $this->buildResult(false, __('panelica.ip_addon_locked'), ['retryable' => true]); } @@ -4405,13 +4415,8 @@ public function getAddonStatus(Service $service, AddonInstruction $instruction): ]); } - private function applyDedicatedIpv4(Service $service, AddonInstruction $instruction): array + private function applyDedicatedIpv4(Service $service, AddonInstruction $instruction, Server $server): array { - $server = $this->getServer($service); - if (! $server) { - return $this->buildResult(false, __('panelica.no_server'), ['retryable' => false]); - } - $userId = trim((string) ($this->getModuleData($service)['panelica_user_id'] ?? '')); if ($userId === '') { return $this->buildResult(false, __('panelica.ip_addon_no_user'), ['retryable' => false]); @@ -4465,7 +4470,7 @@ private function applyDedicatedIpv4(Service $service, AddonInstruction $instruct } if ($ip === null) { - $available = $this->availableIpv4($server); + $available = $this->availableIpv4($server, $this->reservedIpIds($service, $server)); if (! $available['success']) { return $this->buildResult(false, __('panelica.ip_addon_selection_failed'), [ @@ -4523,13 +4528,8 @@ private function applyDedicatedIpv4(Service $service, AddonInstruction $instruct ]), ['ip_id' => $ipId, 'ip_address' => (string) ($ip['ip_address'] ?? '')]); } - private function removeDedicatedIpv4(Service $service, AddonInstruction $instruction): array + private function removeDedicatedIpv4(Service $service, AddonInstruction $instruction, Server $server): array { - $server = $this->getServer($service); - if (! $server) { - return $this->buildResult(false, __('panelica.no_server'), ['retryable' => false]); - } - $userId = trim((string) ($this->getModuleData($service)['panelica_user_id'] ?? '')); if ($userId === '') { return $this->buildResult(false, __('panelica.ip_addon_no_user'), ['retryable' => false]); @@ -4554,6 +4554,10 @@ private function removeDedicatedIpv4(Service $service, AddonInstruction $instruc return $this->buildResult(false, __('panelica.ip_addon_missing_record'), ['manual_required' => true]); } + if ($this->ipClaimedByOtherAddon($service, $server, $ipId, $instruction->serviceAddonId)) { + return $this->buildResult(false, __('panelica.ip_addon_claimed'), ['manual_required' => true]); + } + $account = $this->accountIpIds($server, $userId); if (! $account['success']) { return $this->buildResult(false, __('panelica.ip_addon_account_failed'), [ @@ -4735,12 +4739,89 @@ private function normaliseIpIds(mixed $raw): array } /** - * The first free IPv4 address on the panel. IPv6 and the server's primary - * address are never handed to a customer as an extra IPv4. + * Addresses already promised to an add-on on this server but not yet + * confirmed by the panel. Another add-on must not take one while the first + * execution is between its local reservation and the account PATCH. + * + * @return array + */ + private function reservedIpIds(Service $service, Server $server): array + { + $ids = []; + + $collect = function (mixed $state) use (&$ids): void { + if (! is_array($state) || ! is_array($state['executions'] ?? null)) { + return; + } + + foreach ($state['executions'] as $record) { + if (is_array($record) + && ($record['status'] ?? '') !== 'removed' + && trim((string) ($record['ip_id'] ?? '')) !== '') { + $ids[] = (string) $record['ip_id']; + } + } + }; + + foreach ($this->dedicatedIpv4States($service, $server) as $state) { + $collect($state); + } + + return array_values(array_unique($ids)); + } + + /** + * @return array> + */ + private function dedicatedIpv4States(Service $service, Server $server): array + { + $states = [$this->dedicatedIpv4State($service)]; + + $others = Service::query() + ->where('server_id', $server->id) + ->whereKeyNot($service->id) + ->whereNotNull('module_data->dedicated_ipv4') + ->get(['id', 'module_data']); + + foreach ($others as $other) { + $state = $other->module_data['dedicated_ipv4'] ?? null; + if (is_array($state)) { + $states[] = $state; + } + } + + return $states; + } + + /** Whether another add-on still records the same address as active. */ + private function ipClaimedByOtherAddon(Service $service, Server $server, string $ipId, int $serviceAddonId): bool + { + foreach ($this->dedicatedIpv4States($service, $server) as $state) { + foreach (($state['executions'] ?? []) as $record) { + if (! is_array($record) + || ($record['status'] ?? '') === 'removed' + || (int) ($record['service_addon_id'] ?? 0) === $serviceAddonId) { + continue; + } + + if (trim((string) ($record['ip_id'] ?? '')) === $ipId) { + return true; + } + } + } + + return false; + } + + /** + * The first free IPv4 address on the panel. IPv6, the server's primary + * address, and addresses promised to another add-on are never handed to a + * customer as an extra IPv4. * + * @param array $excludeIds * @return array{success: bool, status: int, ip: array|null, message: string} */ - private function availableIpv4(Server $server): array + private function availableIpv4(Server $server, array $excludeIds = []): array { $response = $this->get($server, '/v1/ip-addresses/available'); @@ -4768,6 +4849,7 @@ private function availableIpv4(Server $server): array $id = trim((string) ($row['id'] ?? '')); if ($type !== 'ipv4' || $id === '' + || in_array($id, $excludeIds, true) || filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false || ! empty($row['is_primary']) || trim((string) ($row['assigned_to_user_id'] ?? '')) !== '') { diff --git a/tests/Feature/PanelicaDedicatedIpv4Test.php b/tests/Feature/PanelicaDedicatedIpv4Test.php index fa37fc96c..17cd26796 100644 --- a/tests/Feature/PanelicaDedicatedIpv4Test.php +++ b/tests/Feature/PanelicaDedicatedIpv4Test.php @@ -119,6 +119,12 @@ function fakePanelicaIpv4Panel(array &$state): void $state['assigned'] = array_values($ids); $state['patches'][] = $ids; + if (! empty($state['ambiguous_patch_once'])) { + $state['ambiguous_patch_once'] = false; + + return Http::response(['message' => 'gateway timeout'], 504); + } + return Http::response(['data' => ['id' => 'acct-1']], 200); } @@ -191,6 +197,134 @@ function fakePanelicaIpv4Panel(array &$state): void ->and($service->fresh()->module_data['dedicated_ipv4']['executions']['1']['status'])->toBe('removed'); }); +it('keeps one address when PATCH applied but the response was ambiguous', function () { + $state = ['ambiguous_patch_once' => true]; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $module = new PanelicaModule; + + $first = $module->applyAddon($service, panelicaIpv4Instruction()); + expect($first['success'])->toBeFalse() + ->and($first['data']['retryable'])->toBeTrue() + ->and($state['assigned'])->toBe(['ip-primary', 'ip-new']) + ->and($state['patches'])->toHaveCount(1) + ->and($service->fresh()->module_data['dedicated_ipv4']['executions']['1']['status'])->toBe('reserved'); + + $second = $module->applyAddon($service->fresh(), panelicaIpv4Instruction()); + expect($second['success'])->toBeTrue() + ->and($second['data']['idempotent'])->toBeTrue() + ->and($state['patches'])->toHaveCount(1) + ->and($state['assigned'])->toBe(['ip-primary', 'ip-new']) + ->and($service->fresh()->module_data['dedicated_ipv4']['executions']['1']['status'])->toBe('applied'); +}); + +it('does not give a reserved address to another add-on on the same service', function () { + $state = ['available' => [ + ['id' => 'ip-new', 'ip_address' => '198.51.100.10', 'ip_type' => 'ipv4'], + ['id' => 'ip-alt', 'ip_address' => '198.51.100.11', 'ip_type' => 'ipv4'], + ]]; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $service->forceFill(['module_data' => [ + 'panelica_user_id' => 'acct-1', + 'dedicated_ipv4' => ['executions' => [ + '99' => [ + 'execution_id' => 99, + 'service_addon_id' => 99, + 'ip_id' => 'ip-new', + 'ip_address' => '198.51.100.10', + 'status' => 'reserved', + ], + ]], + ]])->save(); + + $result = (new PanelicaModule)->applyAddon($service, panelicaIpv4Instruction()); + + expect($result['success'])->toBeTrue() + ->and($state['patches'])->toBe([['ip-primary', 'ip-alt']]) + ->and($service->fresh()->module_data['dedicated_ipv4']['executions']['1']['ip_id'])->toBe('ip-alt') + ->and($service->fresh()->module_data['dedicated_ipv4']['executions']['99']['status'])->toBe('reserved'); +}); + +it('does not give a reserved address to another add-on on the same server', function () { + $state = ['available' => [ + ['id' => 'ip-new', 'ip_address' => '198.51.100.10', 'ip_type' => 'ipv4'], + ['id' => 'ip-alt', 'ip_address' => '198.51.100.11', 'ip_type' => 'ipv4'], + ]]; + fakePanelicaIpv4Panel($state); + + $server = panelicaIpv4Server(); + $service = panelicaIpv4Service($server); + $other = panelicaIpv4Service($server); + $other->forceFill(['module_data' => [ + 'panelica_user_id' => 'acct-2', + 'dedicated_ipv4' => ['executions' => [ + '99' => [ + 'execution_id' => 99, + 'service_addon_id' => 99, + 'ip_id' => 'ip-new', + 'ip_address' => '198.51.100.10', + 'status' => 'reserved', + ], + ]], + ]])->save(); + + $result = (new PanelicaModule)->applyAddon($service, panelicaIpv4Instruction()); + + expect($result['success'])->toBeTrue() + ->and($state['patches'])->toBe([['ip-primary', 'ip-alt']]) + ->and($service->fresh()->module_data['dedicated_ipv4']['executions']['1']['ip_id'])->toBe('ip-alt'); +}); + +it('does not release an address when no assignment is recorded', function () { + $state = []; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $result = (new PanelicaModule)->removeAddon($service, panelicaIpv4Instruction(2, 10, 1)); + + expect($result['success'])->toBeFalse() + ->and($result['data']['manual_required'])->toBeTrue() + ->and($state['patches'])->toBe([]) + ->and($state['assigned'])->toBe(['ip-primary']); +}); + +it('refuses to release an address another add-on still claims', function () { + $state = []; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $service->forceFill(['module_data' => [ + 'panelica_user_id' => 'acct-1', + 'dedicated_ipv4' => ['executions' => [ + '1' => [ + 'execution_id' => 1, + 'service_addon_id' => 10, + 'ip_id' => 'ip-new', + 'ip_address' => '198.51.100.10', + 'status' => 'applied', + ], + '99' => [ + 'execution_id' => 99, + 'service_addon_id' => 99, + 'ip_id' => 'ip-new', + 'ip_address' => '198.51.100.10', + 'status' => 'reserved', + ], + ]], + ]])->save(); + $state['assigned'] = ['ip-primary', 'ip-new']; + + $result = (new PanelicaModule)->removeAddon($service, panelicaIpv4Instruction(2, 10, 1)); + + expect($result['success'])->toBeFalse() + ->and($result['data']['manual_required'])->toBeTrue() + ->and($state['patches'])->toBe([]) + ->and($state['assigned'])->toBe(['ip-primary', 'ip-new']); +}); + it('refuses to release a recorded address that became primary', function () { $state = []; fakePanelicaIpv4Panel($state); @@ -257,12 +391,15 @@ function fakePanelicaIpv4Panel(array &$state): void expect($apply)->not->toBeNull() ->and($executor->execute($apply))->toBeTrue() ->and($apply->fresh()->status)->toBe(AddonExecutionStatus::Completed) + ->and($serviceAddon->fresh()->status)->toBe('active') + ->and($serviceAddon->fresh()->fulfillment_status)->toBe(AddonExecutionStatus::Completed) ->and($state['assigned'])->toBe(['ip-primary', 'ip-new']); $remove = $executor->enqueueRemoval($serviceAddon->fresh()); expect($remove)->not->toBeNull() ->and($executor->execute($remove))->toBeTrue() ->and($remove->fresh()->status)->toBe(AddonExecutionStatus::Completed) + ->and($serviceAddon->fresh()->status)->toBe('active') ->and($serviceAddon->fresh()->fulfillment_status)->toBe(AddonExecutionStatus::Cancelled) ->and($state['assigned'])->toBe(['ip-primary']); }); From e53336142492d3234379150daa10ff08c382a7bb Mon Sep 17 00:00:00 2001 From: Grzegorz Date: Sun, 29 Nov 2026 20:37:15 +0100 Subject: [PATCH 4/4] fix(panelica): refuse ambiguous IP list responses --- modules/Servers/Panelica/PanelicaModule.php | 16 +++++-- tests/Feature/PanelicaDedicatedIpv4Test.php | 53 +++++++++++++++++++++ 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/modules/Servers/Panelica/PanelicaModule.php b/modules/Servers/Panelica/PanelicaModule.php index 09cdd1068..9619418ee 100644 --- a/modules/Servers/Panelica/PanelicaModule.php +++ b/modules/Servers/Panelica/PanelicaModule.php @@ -4706,11 +4706,15 @@ private function accountIpIds(Server $server, string $userId): array } $account = $response->json('data') ?? $response->json(); - if (! is_array($account)) { - return ['success' => true, 'status' => $response->status(), 'ids' => [], 'message' => '']; + if (! is_array($account) + || (! array_key_exists('ip_addresses', $account) && ! array_key_exists('ip_address_ids', $account))) { + return ['success' => false, 'status' => 0, 'ids' => [], 'message' => 'Account response has no IP list.']; } - $raw = $account['ip_addresses'] ?? $account['ip_address_ids'] ?? []; + $raw = $account['ip_addresses'] ?? $account['ip_address_ids']; + if (! is_array($raw)) { + return ['success' => false, 'status' => 0, 'ids' => [], 'message' => 'Account IP list is not an array.']; + } return [ 'success' => true, @@ -4882,10 +4886,14 @@ private function ipAddress(Server $server, string $ipId): array $ip = $response->json('data') ?? $response->json(); + if (! is_array($ip) || trim((string) ($ip['id'] ?? '')) === '') { + return ['success' => false, 'status' => 0, 'ip' => null, 'message' => 'IP response has no address.']; + } + return [ 'success' => true, 'status' => $response->status(), - 'ip' => is_array($ip) ? $ip : null, + 'ip' => $ip, 'message' => '', ]; } diff --git a/tests/Feature/PanelicaDedicatedIpv4Test.php b/tests/Feature/PanelicaDedicatedIpv4Test.php index 17cd26796..4ce34a736 100644 --- a/tests/Feature/PanelicaDedicatedIpv4Test.php +++ b/tests/Feature/PanelicaDedicatedIpv4Test.php @@ -95,6 +95,12 @@ function fakePanelicaIpv4Panel(array &$state): void } if ($method === 'GET' && preg_match('#/v1/ip-addresses/([^/]+)$#', $url, $matches)) { + if (! empty($state['omit_ip_lookup_once'])) { + $state['omit_ip_lookup_once'] = false; + + return Http::response(['data' => []], 200); + } + $id = rawurldecode($matches[1]); $row = collect($state['available'])->firstWhere('id', $id) ?? [ 'id' => $id, @@ -108,6 +114,12 @@ function fakePanelicaIpv4Panel(array &$state): void } if ($method === 'GET' && str_ends_with($url, '/v1/accounts/acct-1')) { + if (! empty($state['omit_account_ip_list_once'])) { + $state['omit_account_ip_list_once'] = false; + + return Http::response(['data' => ['id' => 'acct-1']], 200); + } + return Http::response(['data' => [ 'id' => 'acct-1', 'ip_addresses' => array_map(fn (string $id) => ['id' => $id], $state['assigned']), @@ -291,6 +303,47 @@ function fakePanelicaIpv4Panel(array &$state): void ->and($state['assigned'])->toBe(['ip-primary']); }); +it('does not patch the account when its IP list is missing', function () { + $state = ['omit_account_ip_list_once' => true]; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $result = (new PanelicaModule)->applyAddon($service, panelicaIpv4Instruction()); + + expect($result['success'])->toBeFalse() + ->and($result['data']['retryable'])->toBeTrue() + ->and($state['patches'])->toBe([]) + ->and($state['assigned'])->toBe(['ip-primary']) + ->and($service->fresh()->module_data)->not->toHaveKey('dedicated_ipv4'); +}); + +it('does not release an address when the IP lookup is unusable', function () { + $state = ['omit_ip_lookup_once' => true]; + fakePanelicaIpv4Panel($state); + + $service = panelicaIpv4Service(panelicaIpv4Server()); + $service->forceFill(['module_data' => [ + 'panelica_user_id' => 'acct-1', + 'dedicated_ipv4' => ['executions' => [ + '1' => [ + 'execution_id' => 1, + 'service_addon_id' => 10, + 'ip_id' => 'ip-new', + 'ip_address' => '198.51.100.10', + 'status' => 'applied', + ], + ]], + ]])->save(); + $state['assigned'] = ['ip-primary', 'ip-new']; + + $result = (new PanelicaModule)->removeAddon($service, panelicaIpv4Instruction(2, 10, 1)); + + expect($result['success'])->toBeFalse() + ->and($result['data']['retryable'])->toBeTrue() + ->and($state['patches'])->toBe([]) + ->and($state['assigned'])->toBe(['ip-primary', 'ip-new']); +}); + it('refuses to release an address another add-on still claims', function () { $state = []; fakePanelicaIpv4Panel($state);