An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.
PHP coolifydatabasesdeploymentdockerdocker-composeinertiajslaravelmariadbmysqlnextjsnodejsphppostgresredisself-hostedself-hostingserverstatic-sitesveltesvelte5
fix(cloudflare): retry Cloudflare API connection failures and show a clear error
Andras Bacsai6cda6f6dd7f9
diff --git a/app/Livewire/Security/IntegrationTokenEditor.php b/app/Livewire/Security/IntegrationTokenEditor.phpindex 811b7f7712..e39f661943 100644--- a/app/Livewire/Security/IntegrationTokenEditor.php+++ b/app/Livewire/Security/IntegrationTokenEditor.php@@ -6,6 +6,7 @@ use App\Models\IntegrationToken;use App\Services\Dns\CloudflareDnsProvider;use App\Services\IntegrationTokenValidator;use Illuminate\Foundation\Auth\Access\AuthorizesRequests;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Support\Facades\DB;use Livewire\Component;@@ -180,6 +181,8 @@ class IntegrationTokenEditor extends Componentcapabilities: $this->integrationToken->capabilities,);$this->dispatch('success', 'Integration token updated successfully.');+ } catch (ConnectionException) {+ $this->dispatch('error', $validator->connectionErrorMessage($provider));} catch (\Throwable $e) {handleError($e, $this);}diff --git a/app/Livewire/Security/IntegrationTokenForm.php b/app/Livewire/Security/IntegrationTokenForm.phpindex f05a5879f6..33f45d9765 100644--- a/app/Livewire/Security/IntegrationTokenForm.php+++ b/app/Livewire/Security/IntegrationTokenForm.php@@ -6,6 +6,7 @@ use App\Models\IntegrationToken;use App\Services\Dns\CloudflareDnsProvider;use App\Services\IntegrationTokenValidator;use Illuminate\Foundation\Auth\Access\AuthorizesRequests;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Support\Facades\DB;use Livewire\Component;@@ -150,6 +151,8 @@ class IntegrationTokenForm extends Component}$this->dispatch('success', 'Integration token added successfully.');+ } catch (ConnectionException) {+ $this->dispatch('error', $validator->connectionErrorMessage($validated['provider']));} catch (\Throwable $e) {handleError($e, $this);}diff --git a/app/Services/CloudflareHttp.php b/app/Services/CloudflareHttp.phpnew file mode 100644index 0000000000..7e301b37fe--- /dev/null+++ b/app/Services/CloudflareHttp.php@@ -0,0 +1,24 @@+<?php++namespace App\Services;++use Illuminate\Http\Client\ConnectionException;+use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++class CloudflareHttp+{+ /**+ * The connect timeout is longer than the 5 second DNS resolver retry, so one lost DNS query does not fail the request.+ * Only idempotent requests are retried after a connection failure; a POST can reach Cloudflare before the timeout.+ */+ public static function client(string $token): PendingRequest+ {+ return Http::withToken($token)+ ->acceptJson()+ ->connectTimeout(10)+ ->timeout(20)+ ->retry(2, 500, fn ($exception, $request, ?string $method) => $exception instanceof ConnectionException+ && in_array($method, ['GET', 'PUT', 'DELETE'], true), throw: false);+ }+}diff --git a/app/Services/CloudflareTokenValidator.php b/app/Services/CloudflareTokenValidator.phpindex a48efda741..baa622f14b 100644--- a/app/Services/CloudflareTokenValidator.php+++ b/app/Services/CloudflareTokenValidator.php@@ -2,14 +2,11 @@namespace App\Services;-use Illuminate\Http\Client\PendingRequest;-use Illuminate\Support\Facades\Http;-class CloudflareTokenValidator{public function validate(string $token, array $capabilities): bool{- $client = $this->client($token);+ $client = CloudflareHttp::client($token);$verification = $client->get('https://api.cloudflare.com/client/v4/user/tokens/verify');if (! $verification->successful() || $verification->json('result.status') !== 'active') {@@ -42,12 +39,4 @@ class CloudflareTokenValidatorreturn true;}-- private function client(string $token): PendingRequest- {- return Http::withToken($token)- ->acceptJson()- ->connectTimeout(5)- ->timeout(10);- }}diff --git a/app/Services/CloudflareTunnelService.php b/app/Services/CloudflareTunnelService.phpindex 09c2ab72bf..c55785e59d 100644--- a/app/Services/CloudflareTunnelService.php+++ b/app/Services/CloudflareTunnelService.php@@ -14,7 +14,6 @@ use App\Services\Dns\ManagedDnsRecordCleanup;use Illuminate\Contracts\Cache\LockTimeoutException;use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\Client\Response;-use Illuminate\Support\Facades\Http;use Illuminate\Support\Sleep;use RuntimeException;use Spatie\Activitylog\Models\Activity;@@ -283,6 +282,6 @@ class CloudflareTunnelServiceprivate function client(IntegrationToken $token): PendingRequest{- return Http::withToken($token->token)->acceptJson()->connectTimeout(5)->timeout(15);+ return CloudflareHttp::client($token->token);}}diff --git a/app/Services/Dns/CloudflareDnsProvider.php b/app/Services/Dns/CloudflareDnsProvider.phpindex 9c7748ff8b..e8d9c0ae71 100644--- a/app/Services/Dns/CloudflareDnsProvider.php+++ b/app/Services/Dns/CloudflareDnsProvider.php@@ -11,13 +11,13 @@ use App\Models\IntegrationToken;use App\Models\ManagedDnsRecord;use App\Models\Server;use App\Models\ServiceApplication;+use App\Services\CloudflareHttp;use App\Support\DnsRecordHints;use Illuminate\Contracts\Cache\LockTimeoutException;use Illuminate\Database\Eloquent\Model;use Illuminate\Http\Client\PendingRequest;use Illuminate\Support\Collection;use Illuminate\Support\Facades\DB;-use Illuminate\Support\Facades\Http;use RuntimeException;use Throwable;@@ -512,6 +512,6 @@ class CloudflareDnsProviderprivate function client(IntegrationToken $token): PendingRequest{- return Http::withToken($token->token)->acceptJson()->connectTimeout(5)->timeout(10);+ return CloudflareHttp::client($token->token);}}diff --git a/app/Services/IntegrationTokenValidator.php b/app/Services/IntegrationTokenValidator.phpindex 2872a83a91..1df5b5f16b 100644--- a/app/Services/IntegrationTokenValidator.php+++ b/app/Services/IntegrationTokenValidator.php@@ -40,4 +40,11 @@ class IntegrationTokenValidatordefault => 'The token could not be verified.',};}++ public function connectionErrorMessage(string $provider): string+ {+ $name = IntegrationToken::PROVIDER_NAMES[$provider] ?? ucfirst($provider);++ return "Could not connect to the {$name} API. Check the network connection of Coolify and try again.";+ }}diff --git a/tests/Feature/DnsProviderManagementTest.php b/tests/Feature/DnsProviderManagementTest.phpindex bf3fabb712..b3a6d8a382 100644--- a/tests/Feature/DnsProviderManagementTest.php+++ b/tests/Feature/DnsProviderManagementTest.php@@ -24,6 +24,7 @@ use App\Services\Dns\CloudflareDnsProvider;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\ModelNotFoundException;use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Http\Client\ConnectionException;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Event;use Illuminate\Support\Facades\Http;@@ -929,3 +930,22 @@ test('a team member cannot mark a service domain managed with a forged dns complexpect($webApp->fresh()->domain_dns_statuses)->toBeEmpty();});++test('cloudflare dns reads are retried after a connection failure but record creation is not', function () {+ $token = IntegrationToken::factory()->create(['provider' => 'cloudflare', 'token' => 'secret']);+ $zone = DnsProviderZone::factory()->for($token)->create(['provider_zone_id' => 'zone-1', 'name' => 'example.com']);++ Http::fake([+ 'https://api.cloudflare.com/client/v4/zones/zone-1/dns_records?*' => Http::sequence()+ ->pushFailedConnection()+ ->push(['success' => true, 'result' => []]),+ 'https://api.cloudflare.com/client/v4/zones/zone-1/dns_records' => Http::failedConnection(),+ ]);++ expect(fn () => app(CloudflareDnsProvider::class)->createRecord($zone, 'app.example.com', '203.0.113.10'))+ ->toThrow(ConnectionException::class);++ Http::assertSentCount(3);+ Http::assertSent(fn ($request) => $request->method() === 'POST');+ expect(ManagedDnsRecord::query()->count())->toBe(0);+});diff --git a/tests/Feature/Security/IntegrationTokenFormTest.php b/tests/Feature/Security/IntegrationTokenFormTest.phpindex 4d90de6173..6774b3ebe5 100644--- a/tests/Feature/Security/IntegrationTokenFormTest.php+++ b/tests/Feature/Security/IntegrationTokenFormTest.php@@ -520,3 +520,50 @@ test('the token list shows its empty state after the editor deletes the last tok$list->dispatch('integration-token-deleted', uuid: $token->uuid)->assertSee('No integration tokens');});++test('a cloudflare token is saved when one validation request has a connection failure', function () {+ Http::fake([+ 'https://api.cloudflare.com/client/v4/user/tokens/verify' => Http::response(['success' => true, 'result' => ['status' => 'active']]),+ 'https://api.cloudflare.com/client/v4/zones?per_page=1' => Http::response(['success' => true, 'result' => [['id' => 'zone-id']]]),+ 'https://api.cloudflare.com/client/v4/zones/zone-id/dns_records?per_page=1' => Http::sequence()+ ->pushFailedConnection('cURL error 28: Connection timed out after 5001 milliseconds')+ ->push(['success' => true, 'result' => []]),+ 'https://api.cloudflare.com/client/v4/zones?page=1&per_page=50' => Http::response([+ 'success' => true,+ 'result' => [['id' => 'zone-id', 'name' => 'example.com', 'account' => ['id' => 'account-id', 'name' => 'Production']]],+ 'result_info' => ['total_pages' => 1],+ ]),+ ]);++ Livewire::test(IntegrationTokenForm::class)+ ->set('provider', 'cloudflare')+ ->set('name', 'Production DNS')+ ->set('token', 'cloudflare-token')+ ->set('capabilities', ['dns'])+ ->call('addToken')+ ->assertDispatched('success');++ $this->assertDatabaseHas('integration_tokens', ['team_id' => $this->team->id, 'name' => 'Production DNS']);+});++test('a clear error is shown when the provider api cannot be reached', function () {+ Http::fake(['*' => Http::failedConnection('cURL error 28: Connection timed out after 10001 milliseconds')]);++ Livewire::test(IntegrationTokenForm::class)+ ->set('provider', 'cloudflare')+ ->set('name', 'Production DNS')+ ->set('token', 'cloudflare-token')+ ->set('capabilities', ['dns'])+ ->call('addToken')+ ->assertDispatched('error', 'Could not connect to the Cloudflare API. Check the network connection of Coolify and try again.');++ $token = IntegrationToken::factory()->create(['team_id' => $this->team->id, 'provider' => 'cloudflare', 'capabilities' => ['dns']]);++ Livewire::test(IntegrationTokenEditor::class, ['integration_token_uuid' => $token->uuid])+ ->set('newToken', 'new-cloudflare-token')+ ->call('save')+ ->assertDispatched('error', 'Could not connect to the Cloudflare API. Check the network connection of Coolify and try again.');++ $this->assertDatabaseMissing('integration_tokens', ['name' => 'Production DNS']);+ expect($token->refresh()->token)->not->toBe('new-cloudflare-token');+});