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: queue import cleanup and scope DNS record updates
Andras Bacsai7109a11826ac
diff --git a/app/Events/DatabaseImportFinished.php b/app/Events/DatabaseImportFinished.phpindex 549cef3178..ec861f704e 100644--- a/app/Events/DatabaseImportFinished.php+++ b/app/Events/DatabaseImportFinished.php@@ -2,7 +2,6 @@namespace App\Events;-use App\Models\Server;use Illuminate\Foundation\Events\Dispatchable;use Illuminate\Queue\SerializesModels;@@ -10,25 +9,5 @@ class DatabaseImportFinished{use Dispatchable, SerializesModels;- public function __construct(array $data)- {- $commands = [];- if (filled($data['containerName'] ?? null)) {- $commands[] = 'docker rm -f '.escapeshellarg($data['containerName']).' 2>/dev/null || true';- }- if (isSafeTmpPath($data['serverTmpPath'] ?? null)) {- $commands[] = 'rm -f '.escapeshellarg($data['serverTmpPath']).' 2>/dev/null || true';- }- if (filled($data['container'] ?? null)) {- foreach (['containerTmpPath', 'scriptPath'] as $key) {- if (isSafeTmpPath($data[$key] ?? null)) {- $commands[] = 'docker exec '.escapeshellarg($data['container']).' rm -f '.escapeshellarg($data[$key]).' 2>/dev/null || true';- }- }- }- $server = Server::find($data['serverId'] ?? null);- if ($server && $commands !== []) {- instant_remote_process($commands, $server, throwError: false);- }- }+ public function __construct(public readonly array $data) {}}diff --git a/app/Http/Controllers/Api/OpenApi.php b/app/Http/Controllers/Api/OpenApi.phpindex c63204a688..43ce742168 100644--- a/app/Http/Controllers/Api/OpenApi.php+++ b/app/Http/Controllers/Api/OpenApi.php@@ -16,12 +16,11 @@ use OpenApi\Attributes as OA;new OA\Schema(schema: 'DatabaseImportRequest',oneOf: [- new OA\Schema(required: ['source', 'upload_id'], properties: [new OA\Property(property: 'source', type: 'string', enum: ['upload']), new OA\Property(property: 'upload_id', type: 'string', format: 'uuid'), new OA\Property(property: 'dump_all', type: 'boolean', default: false), new OA\Property(property: 'replace_existing', description: 'Drop matching PostgreSQL objects before restoring a single-database archive.', type: 'boolean', default: false)]),- new OA\Schema(required: ['source', 's3_storage_uuid', 'path'], properties: [new OA\Property(property: 'source', type: 'string', enum: ['s3']), new OA\Property(property: 's3_storage_uuid', type: 'string'), new OA\Property(property: 'path', type: 'string'), new OA\Property(property: 'dump_all', type: 'boolean', default: false), new OA\Property(property: 'replace_existing', description: 'Drop matching PostgreSQL objects before restoring a single-database archive.', type: 'boolean', default: false)]),- new OA\Schema(required: ['source', 'path'], properties: [new OA\Property(property: 'source', type: 'string', enum: ['server']), new OA\Property(property: 'path', type: 'string', example: '/var/backups/database.sql.gz'), new OA\Property(property: 'dump_all', type: 'boolean', default: false), new OA\Property(property: 'replace_existing', description: 'Drop matching PostgreSQL objects before restoring a single-database archive.', type: 'boolean', default: false)]),+ new OA\Schema(required: ['source', 'upload_id'], additionalProperties: false, properties: [new OA\Property(property: 'source', type: 'string', enum: ['upload']), new OA\Property(property: 'upload_id', type: 'string', format: 'uuid'), new OA\Property(property: 'dump_all', type: 'boolean', default: false), new OA\Property(property: 'replace_existing', description: 'Drop matching PostgreSQL objects before restoring a single-database archive.', type: 'boolean', default: false)]),+ new OA\Schema(required: ['source', 's3_storage_uuid', 'path'], additionalProperties: false, properties: [new OA\Property(property: 'source', type: 'string', enum: ['s3']), new OA\Property(property: 's3_storage_uuid', type: 'string'), new OA\Property(property: 'path', type: 'string'), new OA\Property(property: 'dump_all', type: 'boolean', default: false), new OA\Property(property: 'replace_existing', description: 'Drop matching PostgreSQL objects before restoring a single-database archive.', type: 'boolean', default: false)]),+ new OA\Schema(required: ['source', 'path'], additionalProperties: false, properties: [new OA\Property(property: 'source', type: 'string', enum: ['server']), new OA\Property(property: 'path', type: 'string', example: '/var/backups/database.sql.gz'), new OA\Property(property: 'dump_all', type: 'boolean', default: false), new OA\Property(property: 'replace_existing', description: 'Drop matching PostgreSQL objects before restoring a single-database archive.', type: 'boolean', default: false)]),],type: 'object',- additionalProperties: false,),new OA\Schema(schema: 'DatabaseImportStatus',diff --git a/app/Jobs/ConfigureDnsRecordJob.php b/app/Jobs/ConfigureDnsRecordJob.phpindex 638f0a5b0b..4e0ea64718 100644--- a/app/Jobs/ConfigureDnsRecordJob.php+++ b/app/Jobs/ConfigureDnsRecordJob.php@@ -62,6 +62,19 @@ class ConfigureDnsRecordJob implements ShouldQueue}}+ public function failed(?Throwable $exception): void+ {+ DnsRecordConfigurationFinished::dispatch(+ $this->teamId,+ $this->resourceType,+ $this->resourceId,+ $this->hostname,+ false,+ '',+ 'The DNS zone is no longer available.',+ );+ }+private function resource(): ?Model{$resourceClass = $this->resourceType === null ? null : (Relation::getMorphedModel($this->resourceType) ?? $this->resourceType);diff --git a/app/Listeners/CleanupDatabaseImport.php b/app/Listeners/CleanupDatabaseImport.phpnew file mode 100644index 0000000000..958b5793ee--- /dev/null+++ b/app/Listeners/CleanupDatabaseImport.php@@ -0,0 +1,63 @@+<?php++namespace App\Listeners;++use App\Events\DatabaseImportFinished;+use App\Models\Server;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Support\Facades\Log;+use Throwable;++class CleanupDatabaseImport implements ShouldQueue+{+ public int $tries = 3;++ /** @var array<int, int> */+ public array $backoff = [5, 15, 30];++ public function handle(DatabaseImportFinished $event): void+ {+ $commands = $this->commands($event->data);+ $server = Server::query()->find($event->data['serverId'] ?? null);++ if ($server && $commands !== []) {+ instant_remote_process($commands, $server);+ }+ }++ /**+ * @param array<string, mixed> $data+ * @return list<string>+ */+ public function commands(array $data): array+ {+ $commands = [];++ if (filled($data['containerName'] ?? null)) {+ $commands[] = 'docker rm -f '.escapeshellarg($data['containerName']).' 2>/dev/null || true';+ }++ if (isSafeTmpPath($data['serverTmpPath'] ?? null)) {+ $commands[] = 'rm -f '.escapeshellarg($data['serverTmpPath']).' 2>/dev/null || true';+ }++ if (filled($data['container'] ?? null)) {+ foreach (['containerTmpPath', 'scriptPath'] as $key) {+ if (isSafeTmpPath($data[$key] ?? null)) {+ $commands[] = 'docker exec '.escapeshellarg($data['container']).' rm -f '.escapeshellarg($data[$key]).' 2>/dev/null || true';+ }+ }+ }++ return $commands;+ }++ public function failed(DatabaseImportFinished $event, Throwable $exception): void+ {+ Log::error('Database import cleanup failed', [+ 'serverId' => $event->data['serverId'] ?? null,+ 'containerName' => $event->data['containerName'] ?? null,+ 'error' => $exception->getMessage(),+ ]);+ }+}diff --git a/app/Livewire/Concerns/InteractsWithDnsProviders.php b/app/Livewire/Concerns/InteractsWithDnsProviders.phpindex 59cb352f9e..692445c3c0 100644--- a/app/Livewire/Concerns/InteractsWithDnsProviders.php+++ b/app/Livewire/Concerns/InteractsWithDnsProviders.php@@ -139,19 +139,26 @@ trait InteractsWithDnsProviders$key = $hostname.'|'.$zoneId;$conflict = $this->dnsProviderConflicts[$key] ?? null;$zone = $this->findTeamZone($zoneId);- if ($conflict === null || $zone === null) {+ $content = $this->serverIp;+ if ($conflict === null || $zone === null || blank($content) || filter_var($content, FILTER_VALIDATE_IP) === false) {$this->dispatch('error', 'The DNS conflict is no longer available. Check the record again.');return;}try {app(CloudflareDnsProvider::class)->replaceRecord(- $zone, $conflict['record_id'], $hostname, $conflict['proposed'], $this->dnsResourceForHostname($hostname),+ $zone,+ (string) ($conflict['record_id'] ?? ''),+ $hostname,+ $content,+ $this->dnsResourceForHostname($hostname),+ (string) ($conflict['current'] ?? ''),);unset($this->dnsProviderConflicts[$key]);$this->dispatch('success', "DNS record replaced for {$hostname}.");$this->loadDnsProviderProposals();} catch (\Throwable $e) {+ unset($this->dnsProviderConflicts[$key]);$this->dispatch('error', $e->getMessage());}}@@ -219,7 +226,19 @@ trait InteractsWithDnsProvidersif (! is_string($hostname)) {return;}- $record = ManagedDnsRecord::query()->where('team_id', currentTeam()->id)->where('name', strtolower($hostname))->first();++ $resource = $this->dnsResourceForHostname($hostname);+ if ($resource === null) {+ return;+ }++ $record = ManagedDnsRecord::query()+ ->where('team_id', currentTeam()->id)+ ->where('name', strtolower($hostname))+ ->where('resource_type', $resource->getMorphClass())+ ->where('resource_id', $resource->getKey())+ ->first();+if ($record !== null && ! app(CloudflareDnsProvider::class)->deleteRecord($record)) {$this->dispatch('warning', 'The domain was removed, but its DNS record changed externally and was left untouched.');}@@ -236,5 +255,7 @@ trait InteractsWithDnsProviders->whereHas('integrationToken', fn ($query) => $query->where('team_id', currentTeam()->id))->first();}+ abstract protected function persistDomainDnsStatuses(): void;+abstract protected function dnsResourceForHostname(string $hostname): ?Model;}diff --git a/app/Livewire/Project/Application/Domains.php b/app/Livewire/Project/Application/Domains.phpindex 222a632c8f..a4b621a689 100644--- a/app/Livewire/Project/Application/Domains.php+++ b/app/Livewire/Project/Application/Domains.php@@ -1535,7 +1535,7 @@ class Domains extends Component}}- public function removeDomainByKey(string $domainKey): void+ public function removeDomainByKey(string $domainKey, string $password = '', array $selectedActions = []): void{$index = collect($this->domainRows)->search(fn (array $row): bool => ! ($row['is_suggested'] ?? false)@@ -1546,7 +1546,7 @@ class Domains extends Componentreturn;}- $this->removeDomain((int) $index);+ $this->removeDomain((int) $index, $password, $selectedActions);}/**diff --git a/app/Livewire/Project/Database/ImportForm.php b/app/Livewire/Project/Database/ImportForm.phpindex 8e0a665cbb..e006f18bd4 100644--- a/app/Livewire/Project/Database/ImportForm.php+++ b/app/Livewire/Project/Database/ImportForm.php@@ -476,8 +476,10 @@ EOD;'replace_existing' => $this->replaceExisting,]);} catch (DatabaseImportException $e) {+ $this->importRunning = false;$this->dispatch('error', $e->getMessage());} catch (\Throwable $e) {+ $this->importRunning = false;handleError($e, $this);return true;@@ -635,6 +637,7 @@ EOD;]);$this->dispatch('info', 'Restoring database from S3. Progress will be shown in the activity monitor...');} catch (DatabaseImportException $e) {+ $this->importRunning = false;$this->dispatch('error', $e->getMessage());} catch (\Throwable $e) {$this->importRunning = false;@@ -646,86 +649,6 @@ EOD;return true;}- public function buildRestoreSafetyCheckCommand(string $tmpPath): ?string- {- return app(DatabaseImportCommandBuilder::class)->buildPostgresSafetyCommand($this->resource, $this->container, $tmpPath);- }-- /**- * Build the POSIX shell snippet that aborts (exit 1) when a PostgreSQL- * backup contains directives leading to OS command execution.- *- * Hardened against bypasses:- * - decompresses gzip backups before scanning,- * - converts custom-format (PGDMP) archives to SQL with pg_restore- * before scanning, and rejects archives that cannot be inspected,- * - strips `--` line comments and flattens newlines so multi-line and- * comment-separated payloads (e.g. `FROM/**/PROGRAM`) are caught,- * - matches a literal `\!` shell escape and `\o|`/`\g|` pipe redirects.- */- public function buildPostgresRestoreScanScript(string $tmpPath): ?string- {- if (! $this->isPostgresqlRestore()) {- return null;- }-- $escapedTmpPath = escapeshellarg($tmpPath);-- // Token separator PostgreSQL treats as whitespace: real whitespace or a- // /* ... */ block comment (used to split keywords like FROM/**/PROGRAM).- $sep = '([[:space:]]|/\\*[^*]*\\*/)';-- $sqlPattern = "(^|;){$sep}*copy{$sep}+[^;]*(from|to){$sep}+program";- $psqlPattern = "^{$sep}*\\\\(!|copy{$sep}+[^[:space:]]+.*{$sep}+program|(o|g){$sep}*\\|)";- $escapedSqlPattern = escapeshellarg($sqlPattern);- $escapedPsqlPattern = escapeshellarg($psqlPattern);- $contents = "{ gunzip -cf {$escapedTmpPath} 2>/dev/null || cat {$escapedTmpPath}; }";- $scan = static fn (string $source): string => "{$source} | sed 's/--.*//' | grep -Eiq {$escapedPsqlPattern} || {$source} | sed 's/--.*//' | tr '\\n\\r\\t' ' ' | grep -Eiq {$escapedSqlPattern}";- $customScan = $scan('pg_restore -f - "$inspect" 2>/dev/null');- $sqlScan = $scan($contents);- $blockedProgram = 'echo \'Blocked PostgreSQL restore: COPY ... PROGRAM and psql shell commands are not allowed.\'; exit 1';- $blockedInspect = 'echo \'Blocked PostgreSQL restore: unable to inspect custom archive.\'; exit 1';-- return <<<SH-header=\$({$contents} | head -c 5)-if [ "\$header" = 'PGDMP' ]; then- inspect=\$(mktemp)- trap 'rm -f "\$inspect"' EXIT- if ! {$contents} > "\$inspect"; then- {$blockedInspect}- fi- if ! pg_restore -l "\$inspect" >/dev/null 2>&1; then- {$blockedInspect}- fi- if {$customScan}; then- {$blockedProgram}- fi-elif {$sqlScan}; then- {$blockedProgram}-fi-SH;- }-- private function addRestoreSafetyCheckCommand(array &$commands, string $tmpPath): void- {- $command = $this->buildRestoreSafetyCheckCommand($tmpPath);-- if ($command !== null) {- $commands[] = $command;- }- }-- private function isPostgresqlRestore(): bool- {- $morphClass = $this->resource->getMorphClass();-- if ($morphClass === ServiceDatabase::class) {- return str_contains($this->resource->databaseType(), 'postgres');- }-- return $morphClass === StandalonePostgresql::class || $morphClass === 'postgresql';- }-public function buildRestoreCommand(string $tmpPath): string{return app(DatabaseImportCommandBuilder::class)->buildRestoreCommand($this->resource, $tmpPath, $this->dumpAll, $this->replaceExisting);diff --git a/app/Livewire/Project/Service/Domains.php b/app/Livewire/Project/Service/Domains.phpindex 4ef70e9cc9..df02c20a89 100644--- a/app/Livewire/Project/Service/Domains.php+++ b/app/Livewire/Project/Service/Domains.php@@ -592,6 +592,11 @@ class Domains extends Component$this->domainRows[$index]['suggestion_role'] = $meta['role'];}+ protected function persistDomainDnsStatuses(): void+ {+ $this->persistAllDomainDnsStatuses();+ }+protected function persistAllDomainDnsStatuses(): void{$byApp = [];@@ -1348,7 +1353,7 @@ class Domains extends Component}}- public function removeDomainByKey(string $domainKey): void+ public function removeDomainByKey(string $domainKey, string $password = '', array $selectedActions = []): void{$index = collect($this->domainRows)->search(fn (array $row): bool => ! ($row['is_suggested'] ?? false)@@ -1359,7 +1364,7 @@ class Domains extends Componentreturn;}- $this->removeDomain((int) $index);+ $this->removeDomain((int) $index, $password, $selectedActions);}/**diff --git a/app/Services/Dns/CloudflareDnsProvider.php b/app/Services/Dns/CloudflareDnsProvider.phpindex cf191c9717..04470b3350 100644--- a/app/Services/Dns/CloudflareDnsProvider.php+++ b/app/Services/Dns/CloudflareDnsProvider.php@@ -15,8 +15,12 @@ use RuntimeException;class CloudflareDnsProvider{+ /** @var array<int, Collection<int, DnsProviderZone>> */+ private array $zoneCache = [];+public function syncZones(IntegrationToken $token): int{+ unset($this->zoneCache[$token->team_id]);$zones = [];$page = 1;do {@@ -51,34 +55,65 @@ class CloudflareDnsProviderpublic function findZones(int $teamId, string $hostname): Collection{$hostname = strtolower(rtrim($hostname, '.'));- $matches = DnsProviderZone::query()- ->whereHas('integrationToken', fn ($query) => $query->where('team_id', $teamId)->where('provider', 'cloudflare'))- ->with('integrationToken')->get()- ->filter(fn (DnsProviderZone $zone) => $hostname === $zone->name || str_ends_with($hostname, '.'.$zone->name));+ $matches = $this->zonesForTeam($teamId)->filter(+ fn (DnsProviderZone $zone) => $hostname === $zone->name || str_ends_with($hostname, '.'.$zone->name)+ );$longest = $matches->max(fn (DnsProviderZone $zone) => strlen($zone->name));return $matches->filter(fn (DnsProviderZone $zone) => strlen($zone->name) === $longest)->values();}- public function createRecord(DnsProviderZone $zone, string $hostname, string $content, ?Model $resource = null): ManagedDnsRecord+ /** @return Collection<int, DnsProviderZone> */+ private function zonesForTeam(int $teamId): Collection+ {+ return $this->zoneCache[$teamId] ??= DnsProviderZone::query()+ ->whereHas('integrationToken', fn ($query) => $query->where('team_id', $teamId)->where('provider', 'cloudflare'))+ ->with('integrationToken')+ ->get();+ }++ /**+ * @return array{id: string, type: string, name: string, content: string}|null+ */+ public function findRecord(DnsProviderZone $zone, string $hostname, string $type): ?array{$hostname = strtolower(rtrim($hostname, '.'));- $type = filter_var($content, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? 'AAAA' : 'A';- $token = $zone->integrationToken;- $existing = $this->client($token)->get("https://api.cloudflare.com/client/v4/zones/{$zone->provider_zone_id}/dns_records", [- 'type' => $type, 'name' => $hostname, 'per_page' => 100,- ]);- if (! $existing->successful()) {+ $response = $this->client($zone->integrationToken)->get(+ "https://api.cloudflare.com/client/v4/zones/{$zone->provider_zone_id}/dns_records",+ ['type' => $type, 'name' => $hostname, 'per_page' => 100],+ );+ if (! $response->successful()) {throw new RuntimeException('Cloudflare DNS records could not be checked.');}- $remote = collect($existing->json('result', []))->first();+ $remote = collect($response->json('result', []))->first();+ if ($remote === null) {+ return null;+ }++ return [+ 'id' => (string) ($remote['id'] ?? ''),+ 'type' => (string) ($remote['type'] ?? $type),+ 'name' => strtolower((string) ($remote['name'] ?? $hostname)),+ 'content' => (string) ($remote['content'] ?? ''),+ ];+ }++ public function createRecord(DnsProviderZone $zone, string $hostname, string $content, ?Model $resource = null): ManagedDnsRecord+ {+ $hostname = strtolower(rtrim($hostname, '.'));+ $type = filter_var($content, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? 'AAAA' : 'A';+ $remote = $this->findRecord($zone, $hostname, $type);if ($remote !== null) {- if (($remote['content'] ?? null) === $content) {- throw new RuntimeException('DNS is already configured. Coolify left the existing record unchanged.');+ if ($remote['content'] === $content) {+ if ($remote['id'] === '') {+ throw new RuntimeException('Cloudflare DNS records could not be checked.');+ }++ return $this->trackRecord($zone, $remote['id'], $type, $hostname, $content, $resource);}- throw new DnsRecordConflictException((string) ($remote['id'] ?? ''), (string) ($remote['content'] ?? ''), $content);+ throw new DnsRecordConflictException($remote['id'], $remote['content'], $content);}- $response = $this->client($token)->post("https://api.cloudflare.com/client/v4/zones/{$zone->provider_zone_id}/dns_records", [+ $response = $this->client($zone->integrationToken)->post("https://api.cloudflare.com/client/v4/zones/{$zone->provider_zone_id}/dns_records", ['type' => $type, 'name' => $hostname, 'content' => $content, 'ttl' => 1, 'proxied' => false,]);if (! $response->successful() || ! is_string($response->json('result.id'))) {@@ -88,18 +123,34 @@ class CloudflareDnsProviderreturn $this->trackRecord($zone, $response->json('result.id'), $type, $hostname, $content, $resource);}- public function replaceRecord(DnsProviderZone $zone, string $recordId, string $hostname, string $content, ?Model $resource = null): ManagedDnsRecord- {+ public function replaceRecord(+ DnsProviderZone $zone,+ string $recordId,+ string $hostname,+ string $content,+ ?Model $resource = null,+ ?string $expectedCurrent = null,+ ): ManagedDnsRecord {+ $hostname = strtolower(rtrim($hostname, '.'));$type = filter_var($content, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? 'AAAA' : 'A';+ $remote = $this->findRecord($zone, $hostname, $type);+ if ($remote === null+ || $remote['id'] === ''+ || $remote['id'] !== $recordId+ || ($expectedCurrent !== null && $remote['content'] !== $expectedCurrent)+ || $remote['name'] !== $hostname) {+ throw new RuntimeException('The DNS conflict is no longer available. Check the record again.');+ }+$response = $this->client($zone->integrationToken)->put(- "https://api.cloudflare.com/client/v4/zones/{$zone->provider_zone_id}/dns_records/{$recordId}",+ "https://api.cloudflare.com/client/v4/zones/{$zone->provider_zone_id}/dns_records/{$remote['id']}",['type' => $type, 'name' => $hostname, 'content' => $content, 'ttl' => 1, 'proxied' => false],);if (! $response->successful()) {throw new RuntimeException('Cloudflare could not replace the conflicting DNS record.');}- return $this->trackRecord($zone, $recordId, $type, strtolower($hostname), $content, $resource);+ return $this->trackRecord($zone, $remote['id'], $type, $hostname, $content, $resource);}public function deleteRecord(ManagedDnsRecord $record): booldiff --git a/app/Support/DatabaseImport/DatabaseImportCommandBuilder.php b/app/Support/DatabaseImport/DatabaseImportCommandBuilder.phpindex 7dcbb7e216..311a4634a5 100644--- a/app/Support/DatabaseImport/DatabaseImportCommandBuilder.php+++ b/app/Support/DatabaseImport/DatabaseImportCommandBuilder.php@@ -26,15 +26,56 @@ class DatabaseImportCommandBuilder};}- public function buildPostgresSafetyCommand(object $resource, string $container, string $path): ?string+ public function buildPostgresRestoreScanScript(object $resource, string $path): ?string{if ($this->databaseType($resource) !== 'postgresql') {return null;}- $path = escapeshellarg($path);- $contents = "{ gunzip -cf {$path} 2>/dev/null || cat {$path}; }";- $script = "header=\$({$contents} | head -c 5); if [ \"\$header\" = 'PGDMP' ]; then exit 0; fi; if {$contents} | sed 's/--.*//' | grep -Eiq '(^|;)[[:space:]]*copy[[:space:]]+[^;]*(from|to)[[:space:]]+program|^[[:space:]]*\\\\(!|copy.*program|(o|g)[[:space:]]*\\|)'; then echo 'Blocked PostgreSQL restore: COPY ... PROGRAM and psql shell commands are not allowed.'; exit 1; fi";+ $escapedPath = escapeshellarg($path);++ // Token separator PostgreSQL treats as whitespace: real whitespace or a+ // /* ... */ block comment (used to split keywords like FROM/**/PROGRAM).+ $sep = '([[:space:]]|/\\*[^*]*\\*/)';++ $sqlPattern = "(^|;){$sep}*copy{$sep}+[^;]*(from|to){$sep}+program";+ $psqlPattern = "^{$sep}*\\\\(!|copy{$sep}+[^[:space:]]+.*{$sep}+program|(o|g){$sep}*\\|)";+ $escapedSqlPattern = escapeshellarg($sqlPattern);+ $escapedPsqlPattern = escapeshellarg($psqlPattern);+ $contents = "{ gunzip -cf {$escapedPath} 2>/dev/null || cat {$escapedPath}; }";+ $scan = static fn (string $source): string => "{$source} | sed 's/--.*//' | grep -Eiq {$escapedPsqlPattern} || {$source} | sed 's/--.*//' | tr '\\n\\r\\t' ' ' | grep -Eiq {$escapedSqlPattern}";+ $customScan = $scan('pg_restore -f - "$inspect" 2>/dev/null');+ $sqlScan = $scan($contents);+ $blockedProgram = 'echo \'Blocked PostgreSQL restore: COPY ... PROGRAM and psql shell commands are not allowed.\'; exit 1';+ $blockedInspect = 'echo \'Blocked PostgreSQL restore: unable to inspect custom archive.\'; exit 1';++ return <<<SH+header=\$({$contents} | head -c 5)+if [ "\$header" = 'PGDMP' ]; then+ inspect=\$(mktemp)+ trap 'rm -f "\$inspect"' EXIT+ if ! {$contents} > "\$inspect"; then+ {$blockedInspect}+ fi+ if ! pg_restore -l "\$inspect" >/dev/null 2>&1; then+ {$blockedInspect}+ fi+ if {$customScan}; then+ {$blockedProgram}+ fi+elif {$sqlScan}; then+ {$blockedProgram}+fi+SH;+ }++ public function buildPostgresSafetyCommand(object $resource, string $container, string $path): ?string+ {+ $script = $this->buildPostgresRestoreScanScript($resource, $path);++ if ($script === null) {+ return null;+ }return 'docker exec '.$container.' sh -c '.escapeshellarg($script);}diff --git a/openapi.json b/openapi.jsonindex 415cca180c..1e10d2ff88 100644--- a/openapi.json+++ b/openapi.json@@ -3568,6 +3568,175 @@]}},+ "\/applications\/{uuid}\/previews\/{pull_request_id}": {+ "delete": {+ "tags": [+ "Applications"+ ],+ "summary": "Delete Preview Deployment",+ "description": "Delete a preview deployment for a pull request. Cancels active deployments, stops containers, removes volumes\/networks, and deletes the preview record.",+ "operationId": "delete-preview-deployment-by-pull-request-id",+ "parameters": [+ {+ "name": "uuid",+ "in": "path",+ "description": "UUID of the application.",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "pull_request_id",+ "in": "path",+ "description": "Pull request ID of the preview to delete.",+ "required": true,+ "schema": {+ "type": "integer"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Preview deletion queued.",+ "content": {+ "application\/json": {+ "schema": {+ "properties": {+ "message": {+ "type": "string"+ }+ },+ "type": "object"+ }+ }+ }+ },+ "401": {+ "$ref": "#\/components\/responses\/401"+ },+ "400": {+ "$ref": "#\/components\/responses\/400"+ },+ "404": {+ "$ref": "#\/components\/responses\/404"+ },+ "422": {+ "$ref": "#\/components\/responses\/422"+ }+ },+ "security": [+ {+ "bearerAuth": []+ }+ ]+ },+ "patch": {+ "tags": [+ "Applications"+ ],+ "summary": "Update Preview Domains",+ "description": "Replace domains for a preview deployment. Use domains for regular applications or docker_compose_domains for Docker Compose applications. Ports are stored as internal overrides while public domains remain portless.",+ "operationId": "update-preview-domains-by-pull-request-id",+ "parameters": [+ {+ "name": "uuid",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "pull_request_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "integer"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application\/json": {+ "schema": {+ "properties": {+ "domains": {+ "type": [+ "string",+ "null"+ ],+ "example": "https:\/\/pr.example.com:3000"+ },+ "docker_compose_domains": {+ "type": [+ "array",+ "null"+ ],+ "items": {+ "properties": {+ "name": {+ "type": "string"+ },+ "domain": {+ "type": [+ "string",+ "null"+ ]+ },+ "redirect": {+ "type": [+ "string",+ "null"+ ],+ "enum": [+ "www",+ "non-www",+ "both"+ ]+ }+ },+ "type": "object"+ }+ },+ "force_domain_override": {+ "type": "boolean",+ "default": false+ }+ },+ "type": "object"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Preview domains updated."+ },+ "401": {+ "$ref": "#\/components\/responses\/401"+ },+ "403": {+ "$ref": "#\/components\/responses\/403"+ },+ "404": {+ "$ref": "#\/components\/responses\/404"+ },+ "409": {+ "description": "Domain conflict."+ },+ "422": {+ "$ref": "#\/components\/responses\/422"+ }+ },+ "security": [+ {+ "bearerAuth": []+ }+ ]+ }+ },"\/applications\/{uuid}\/envs": {"get": {"tags": [@@ -4628,70 +4797,6 @@]}},- "\/applications\/{uuid}\/previews\/{pull_request_id}": {- "delete": {- "tags": [- "Applications"- ],- "summary": "Delete Preview Deployment",- "description": "Delete a preview deployment for a pull request. Cancels active deployments, stops containers, removes volumes\/networks, and deletes the preview record.",- "operationId": "delete-preview-deployment-by-pull-request-id",- "parameters": [- {- "name": "uuid",- "in": "path",- "description": "UUID of the application.",- "required": true,- "schema": {- "type": "string"- }- },- {- "name": "pull_request_id",- "in": "path",- "description": "Pull request ID of the preview to delete.",- "required": true,- "schema": {- "type": "integer"- }- }- ],- "responses": {- "200": {- "description": "Preview deletion queued.",- "content": {- "application\/json": {- "schema": {- "properties": {- "message": {- "type": "string"- }- },- "type": "object"- }- }- }- },- "401": {- "$ref": "#\/components\/responses\/401"- },- "400": {- "$ref": "#\/components\/responses\/400"- },- "404": {- "$ref": "#\/components\/responses\/404"- },- "422": {- "$ref": "#\/components\/responses\/422"- }- },- "security": [- {- "bearerAuth": []- }- ]- }- },"\/applications\/{uuid}\/tags": {"get": {"tags": [@@ -5845,6 +5950,17 @@],"summary": "Upload database import","operationId": "upload-database-import",+ "parameters": [+ {+ "name": "uuid",+ "in": "path",+ "description": "UUID of the database.",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],"responses": {"201": {"description": "Upload completed"@@ -5867,6 +5983,17 @@],"summary": "Import database backup","operationId": "create-database-import",+ "parameters": [+ {+ "name": "uuid",+ "in": "path",+ "description": "UUID of the database.",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],"requestBody": {"required": true,"content": {@@ -5902,9 +6029,36 @@],"summary": "Get database import status","operationId": "get-database-import",+ "parameters": [+ {+ "name": "uuid",+ "in": "path",+ "description": "UUID of the database.",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "activity_id",+ "in": "path",+ "description": "Import activity ID.",+ "required": true,+ "schema": {+ "type": "integer"+ }+ }+ ],"responses": {"200": {- "description": "Import status"+ "description": "Import status",+ "content": {+ "application\/json": {+ "schema": {+ "$ref": "#\/components\/schemas\/DatabaseImportStatus"+ }+ }+ }},"404": {"$ref": "#\/components\/responses\/404"@@ -6085,6 +6239,13 @@"type": "integer","description": "Backup job timeout in seconds (min: 60, max: 36000)","default": 3600+ },+ "missing_backup_notification_days": {+ "type": "integer",+ "description": "Alert after this many days without an execution; 0 disables alerts",+ "minimum": 0,+ "maximum": 365,+ "default": 0}},"type": "object"@@ -6684,6 +6845,12 @@"type": "integer","description": "Backup job timeout in seconds (min: 60, max: 36000)","default": 3600+ },+ "missing_backup_notification_days": {+ "type": "integer",+ "description": "Alert after this many days without an execution; 0 disables alerts",+ "minimum": 0,+ "maximum": 365}},"type": "object"@@ -15818,6 +15985,28 @@"string","null"]+ },+ "traffic_topn": {+ "type": "integer"+ },+ "traffic_sample_threshold": {+ "type": "integer"+ },+ "traffic_retention_1h_days": {+ "type": "integer"+ },+ "traffic_retention_1d_days": {+ "type": "integer"+ },+ "is_geoip_enabled": {+ "type": "boolean"+ },+ "geoip_refresh_days": {+ "type": "integer"+ },+ "geoip_maxmind_license_key": {+ "description": "Only present with read:sensitive.",+ "type": "string"}},"type": "object"@@ -15894,6 +16083,35 @@"string","null"]+ },+ "traffic_topn": {+ "type": "integer",+ "minimum": 1+ },+ "traffic_sample_threshold": {+ "type": "integer",+ "minimum": 0+ },+ "traffic_retention_1h_days": {+ "type": "integer",+ "minimum": 1+ },+ "traffic_retention_1d_days": {+ "type": "integer",+ "minimum": 1+ },+ "is_geoip_enabled": {+ "type": "boolean"+ },+ "geoip_refresh_days": {+ "type": "integer",+ "minimum": 1+ },+ "geoip_maxmind_license_key": {+ "type": [+ "string",+ "null"+ ]}},"type": "object"@@ -17471,6 +17689,26 @@],"summary": "Upload service database import","operationId": "upload-service-database-import",+ "parameters": [+ {+ "name": "uuid",+ "in": "path",+ "description": "Service UUID.",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "database_uuid",+ "in": "path",+ "description": "Service database UUID.",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],"responses": {"201": {"description": "Upload completed"@@ -17493,6 +17731,26 @@],"summary": "Import service database backup","operationId": "create-service-database-import",+ "parameters": [+ {+ "name": "uuid",+ "in": "path",+ "description": "Service UUID.",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "database_uuid",+ "in": "path",+ "description": "Service database UUID.",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],"requestBody": {"required": true,"content": {@@ -17528,9 +17786,45 @@],"summary": "Get service database import status","operationId": "get-service-database-import",+ "parameters": [+ {+ "name": "uuid",+ "in": "path",+ "description": "Service UUID.",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "database_uuid",+ "in": "path",+ "description": "Service database UUID.",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "activity_id",+ "in": "path",+ "description": "Import activity ID.",+ "required": true,+ "schema": {+ "type": "integer"+ }+ }+ ],"responses": {"200": {- "description": "Import status"+ "description": "Import status",+ "content": {+ "application\/json": {+ "schema": {+ "$ref": "#\/components\/schemas\/DatabaseImportStatus"+ }+ }+ }},"404": {"$ref": "#\/components\/responses\/404"@@ -21771,7 +22065,8 @@"default": false}},- "type": "object"+ "type": "object",+ "additionalProperties": false},{"required": [@@ -21802,7 +22097,8 @@"default": false}},- "type": "object"+ "type": "object",+ "additionalProperties": false},{"required": [@@ -21830,10 +22126,10 @@"default": false}},- "type": "object"+ "type": "object",+ "additionalProperties": false}- ],- "additionalProperties": false+ ]},"DatabaseImportStatus": {"properties": {@@ -23033,6 +23329,27 @@"is_metrics_enabled": {"type": "boolean"},+ "is_traffic_analytics_enabled": {+ "type": "boolean"+ },+ "traffic_topn": {+ "type": "integer"+ },+ "traffic_sample_threshold": {+ "type": "integer"+ },+ "traffic_retention_1h_days": {+ "type": "integer"+ },+ "traffic_retention_1d_days": {+ "type": "integer"+ },+ "is_geoip_enabled": {+ "type": "boolean"+ },+ "geoip_refresh_days": {+ "type": "integer"+ },"is_reachable": {"type": "boolean"},diff --git a/openapi.yaml b/openapi.yamlindex f4f906b37c..8ca49738cc 100644--- a/openapi.yaml+++ b/openapi.yaml@@ -2346,6 +2346,99 @@ paths:security:-bearerAuth: []+ '/applications/{uuid}/previews/{pull_request_id}':+ delete:+ tags:+ - Applications+ summary: 'Delete Preview Deployment'+ description: 'Delete a preview deployment for a pull request. Cancels active deployments, stops containers, removes volumes/networks, and deletes the preview record.'+ operationId: delete-preview-deployment-by-pull-request-id+ parameters:+ -+ name: uuid+ in: path+ description: 'UUID of the application.'+ required: true+ schema:+ type: string+ -+ name: pull_request_id+ in: path+ description: 'Pull request ID of the preview to delete.'+ required: true+ schema:+ type: integer+ responses:+ '200':+ description: 'Preview deletion queued.'+ content:+ application/json:+ schema:+ properties:+ message: { type: string }+ type: object+ '401':+ $ref: '#/components/responses/401'+ '400':+ $ref: '#/components/responses/400'+ '404':+ $ref: '#/components/responses/404'+ '422':+ $ref: '#/components/responses/422'+ security:+ -+ bearerAuth: []+ patch:+ tags:+ - Applications+ summary: 'Update Preview Domains'+ description: 'Replace domains for a preview deployment. Use domains for regular applications or docker_compose_domains for Docker Compose applications. Ports are stored as internal overrides while public domains remain portless.'+ operationId: update-preview-domains-by-pull-request-id+ parameters:+ -+ name: uuid+ in: path+ required: true+ schema:+ type: string+ -+ name: pull_request_id+ in: path+ required: true+ schema:+ type: integer+ requestBody:+ required: true+ content:+ application/json:+ schema:+ properties:+ domains:+ type: [string, 'null']+ example: 'https://pr.example.com:3000'+ docker_compose_domains:+ type: [array, 'null']+ items: { properties: { name: { type: string }, domain: { type: [string, 'null'] }, redirect: { type: [string, 'null'], enum: [www, non-www, both] } }, type: object }+ force_domain_override:+ type: boolean+ default: false+ type: object+ responses:+ '200':+ description: 'Preview domains updated.'+ '401':+ $ref: '#/components/responses/401'+ '403':+ $ref: '#/components/responses/403'+ '404':+ $ref: '#/components/responses/404'+ '409':+ description: 'Domain conflict.'+ '422':+ $ref: '#/components/responses/422'+ security:+ -+ bearerAuth: []'/applications/{uuid}/envs':get:tags:@@ -3013,48 +3106,6 @@ paths:security:-bearerAuth: []- '/applications/{uuid}/previews/{pull_request_id}':- delete:- tags:- - Applications- summary: 'Delete Preview Deployment'- description: 'Delete a preview deployment for a pull request. Cancels active deployments, stops containers, removes volumes/networks, and deletes the preview record.'- operationId: delete-preview-deployment-by-pull-request-id- parameters:- -- name: uuid- in: path- description: 'UUID of the application.'- required: true- schema:- type: string- -- name: pull_request_id- in: path- description: 'Pull request ID of the preview to delete.'- required: true- schema:- type: integer- responses:- '200':- description: 'Preview deletion queued.'- content:- application/json:- schema:- properties:- message: { type: string }- type: object- '401':- $ref: '#/components/responses/401'- '400':- $ref: '#/components/responses/400'- '404':- $ref: '#/components/responses/404'- '422':- $ref: '#/components/responses/422'- security:- -- bearerAuth: []'/applications/{uuid}/tags':get:tags:@@ -3765,6 +3816,14 @@ paths:- Databasessummary: 'Upload database import'operationId: upload-database-import+ parameters:+ -+ name: uuid+ in: path+ description: 'UUID of the database.'+ required: true+ schema:+ type: stringresponses:'201':description: 'Upload completed'@@ -3779,6 +3838,14 @@ paths:- Databasessummary: 'Import database backup'operationId: create-database-import+ parameters:+ -+ name: uuid+ in: path+ description: 'UUID of the database.'+ required: true+ schema:+ type: stringrequestBody:required: truecontent:@@ -3801,9 +3868,28 @@ paths:- Databasessummary: 'Get database import status'operationId: get-database-import+ parameters:+ -+ name: uuid+ in: path+ description: 'UUID of the database.'+ required: true+ schema:+ type: string+ -+ name: activity_id+ in: path+ description: 'Import activity ID.'+ required: true+ schema:+ type: integerresponses:'200':description: 'Import status'+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/DatabaseImportStatus''404':$ref: '#/components/responses/404'security:@@ -3932,6 +4018,12 @@ paths:type: integerdescription: 'Backup job timeout in seconds (min: 60, max: 36000)'default: 3600+ missing_backup_notification_days:+ type: integer+ description: 'Alert after this many days without an execution; 0 disables alerts'+ minimum: 0+ maximum: 365+ default: 0type: objectresponses:'201':@@ -4351,6 +4443,11 @@ paths:type: integerdescription: 'Backup job timeout in seconds (min: 60, max: 36000)'default: 3600+ missing_backup_notification_days:+ type: integer+ description: 'Alert after this many days without an execution; 0 disables alerts'+ minimum: 0+ maximum: 365type: objectresponses:'200':@@ -10035,6 +10132,13 @@ paths:sentinel_push_interval_seconds: { type: integer }sentinel_custom_url: { description: 'Only present with read:sensitive.', type: string }sentinel_updated_at: { type: [string, 'null'] }+ traffic_topn: { type: integer }+ traffic_sample_threshold: { type: integer }+ traffic_retention_1h_days: { type: integer }+ traffic_retention_1d_days: { type: integer }+ is_geoip_enabled: { type: boolean }+ geoip_refresh_days: { type: integer }+ geoip_maxmind_license_key: { description: 'Only present with read:sensitive.', type: string }type: object'401':$ref: '#/components/responses/401'@@ -10084,6 +10188,25 @@ paths:minimum: 10sentinel_custom_url:type: [string, 'null']+ traffic_topn:+ type: integer+ minimum: 1+ traffic_sample_threshold:+ type: integer+ minimum: 0+ traffic_retention_1h_days:+ type: integer+ minimum: 1+ traffic_retention_1d_days:+ type: integer+ minimum: 1+ is_geoip_enabled:+ type: boolean+ geoip_refresh_days:+ type: integer+ minimum: 1+ geoip_maxmind_license_key:+ type: [string, 'null']type: objectresponses:'200':@@ -11080,6 +11203,21 @@ paths:- 'Service databases'summary: 'Upload service database import'operationId: upload-service-database-import+ parameters:+ -+ name: uuid+ in: path+ description: 'Service UUID.'+ required: true+ schema:+ type: string+ -+ name: database_uuid+ in: path+ description: 'Service database UUID.'+ required: true+ schema:+ type: stringresponses:'201':description: 'Upload completed'@@ -11094,6 +11232,21 @@ paths:- 'Service databases'summary: 'Import service database backup'operationId: create-service-database-import+ parameters:+ -+ name: uuid+ in: path+ description: 'Service UUID.'+ required: true+ schema:+ type: string+ -+ name: database_uuid+ in: path+ description: 'Service database UUID.'+ required: true+ schema:+ type: stringrequestBody:required: truecontent:@@ -11116,9 +11269,35 @@ paths:- 'Service databases'summary: 'Get service database import status'operationId: get-service-database-import+ parameters:+ -+ name: uuid+ in: path+ description: 'Service UUID.'+ required: true+ schema:+ type: string+ -+ name: database_uuid+ in: path+ description: 'Service database UUID.'+ required: true+ schema:+ type: string+ -+ name: activity_id+ in: path+ description: 'Import activity ID.'+ required: true+ schema:+ type: integerresponses:'200':description: 'Import status'+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/DatabaseImportStatus''404':$ref: '#/components/responses/404'security:@@ -13839,6 +14018,7 @@ components:type: booleandefault: falsetype: object+ additionalProperties: false-required:- source@@ -13861,6 +14041,7 @@ components:type: booleandefault: falsetype: object+ additionalProperties: false-required:- source@@ -13881,7 +14062,7 @@ components:type: booleandefault: falsetype: object- additionalProperties: false+ additionalProperties: falseDatabaseImportStatus:properties:id:@@ -14766,6 +14947,20 @@ components:type: booleanis_metrics_enabled:type: boolean+ is_traffic_analytics_enabled:+ type: boolean+ traffic_topn:+ type: integer+ traffic_sample_threshold:+ type: integer+ traffic_retention_1h_days:+ type: integer+ traffic_retention_1d_days:+ type: integer+ is_geoip_enabled:+ type: boolean+ geoip_refresh_days:+ type: integeris_reachable:type: booleanis_sentinel_enabled:diff --git a/resources/css/app.css b/resources/css/app.cssindex 252293b5fd..7b192d71a3 100644--- a/resources/css/app.css+++ b/resources/css/app.css@@ -98,7 +98,7 @@.button.button-highlighted:not(:disabled),.button[isHighlighted]:not(:disabled) {- --button-depth-color: color-mix(in oklab, var(--color-coollabs) 52%, black);+ --button-depth-color: var(--color-coollabs-300);}.dark .button:not(.button-highlighted):not(.button-error):not([isHighlighted]):not(:disabled) {diff --git a/resources/views/livewire/project/application/partials/domain-row.blade.php b/resources/views/livewire/project/application/partials/domain-row.blade.phpindex 9ee05c7c02..28fe07f2ef 100644--- a/resources/views/livewire/project/application/partials/domain-row.blade.php+++ b/resources/views/livewire/project/application/partials/domain-row.blade.php@@ -153,7 +153,8 @@<x-reicon name="settings" class="size-3.5" /></button><x-modal-confirmation class="!w-auto shrink-0" title="Remove domain?" buttonTitle="Remove"- isErrorButton submitAction="removeDomainByKey({{ $domainKey }})" :actions="[+ isErrorButton canGate="update" :canResource="$application"+ submitAction="removeDomainByKey({{ $domainKey }})" :actions="['This domain will be removed from the application.','Redeploy or restart may be required for proxy changes.',]" :checkboxes="[['id' => 'deleteManagedDns', 'label' => 'Also delete the DNS record created by Coolify, if present.']]"diff --git a/resources/views/livewire/project/database/import-form.blade.php b/resources/views/livewire/project/database/import-form.blade.phpindex 03cc780e52..9d70a41780 100644--- a/resources/views/livewire/project/database/import-form.blade.php+++ b/resources/views/livewire/project/database/import-form.blade.php@@ -98,7 +98,8 @@@if (in_array($resourceDbType, ['standalone-postgresql', 'postgresql'], true) && ! $dumpAll)<div class="max-w-sm"><x-forms.checkbox id="replaceExisting" label="Replace objects that already exist"- helper="Drops matching tables, functions, types, and other PostgreSQL objects from the archive before restoring them." />+ helper="Drops matching tables, functions, types, and other PostgreSQL objects from the archive before restoring them."+ canGate="update" :canResource="$this->resource" /></div>@endif</div>diff --git a/resources/views/livewire/project/service/partials/domain-table.blade.php b/resources/views/livewire/project/service/partials/domain-table.blade.phpindex 7ba519dec2..e277ccce94 100644--- a/resources/views/livewire/project/service/partials/domain-table.blade.php+++ b/resources/views/livewire/project/service/partials/domain-table.blade.php@@ -189,6 +189,7 @@</button><x-modal-confirmation class="!w-auto shrink-0" title="Remove domain?"buttonTitle="Remove" isErrorButton+ canGate="update" :canResource="$service"submitAction="removeDomainByKey({{ $domainKey }})" :actions="['This domain will be removed from the service application.','Redeploy or restart may be required for proxy changes.',diff --git a/resources/views/livewire/project/shared/cloudflare-autoconfigure.blade.php b/resources/views/livewire/project/shared/cloudflare-autoconfigure.blade.phpindex 23ebfff37d..46ab71e14f 100644--- a/resources/views/livewire/project/shared/cloudflare-autoconfigure.blade.php+++ b/resources/views/livewire/project/shared/cloudflare-autoconfigure.blade.php@@ -1,6 +1,7 @@{{-- DNS entries: Domain Connect (Cloud only + key) and/or generic Type/Name/Value records. --}}@php$domainConnectAvailable = $this->domainConnectAvailable();+ $dnsAuthResource = property_exists($this, 'application') ? $this->application : $this->service;@endphp<div x-data="{ dnsEntriesOpen: false }" class="relative" @click.outside="dnsEntriesOpen = false">@@ -204,7 +205,8 @@@foreach ($recordProviders as $provider)<x-forms.button type="button"wire:click="createManagedDnsRecord({{ \Illuminate\Support\Js::from($record['name']) }}, {{ $provider['zone_id'] }}, {{ \Illuminate\Support\Js::from($record['value']) }})"- wire:target="createManagedDnsRecord">+ wire:target="createManagedDnsRecord"+ canGate="update" :canResource="$dnsAuthResource">Add with {{ $provider['credential'] }}</x-forms.button>@endforeachdiff --git a/resources/views/livewire/project/shared/dns-provider-management.blade.php b/resources/views/livewire/project/shared/dns-provider-management.blade.phpindex fb75d8e625..b33d073e13 100644--- a/resources/views/livewire/project/shared/dns-provider-management.blade.php+++ b/resources/views/livewire/project/shared/dns-provider-management.blade.php@@ -1,4 +1,8 @@-@if ($showDnsProviderModal)+<div class="contents">+ @php+ $dnsAuthResource = property_exists($this, 'application') ? $this->application : $this->service;+ @endphp+ @if ($showDnsProviderModal)<div x-data="{ modalOpen: @entangle('showDnsProviderModal') }" class="relative h-auto w-auto":class="{ 'z-40': modalOpen }" @keydown.escape.window="modalOpen = false; $wire.closeDnsProviderModal()"><template x-teleport="body">@@ -26,12 +30,14 @@<x-modal-confirmation title="Replace conflicting DNS record?" isErrorButton buttonTitle="Replace record"submitAction="replaceManagedDnsRecord({{ \Illuminate\Support\Js::from($proposal['hostname']) }}, {{ $proposal['zone_id'] }})":actions="['Replace '.$proposal['hostname'].' value '.$conflict['current'].' with '.$conflict['proposed'], 'Coolify will manage the replaced record.']"- :confirmWithPassword="false" :confirmWithText="false" step2ButtonText="Replace record" />+ :confirmWithPassword="false" :confirmWithText="false" step2ButtonText="Replace record"+ canGate="update" :canResource="$dnsAuthResource" /></div>@else<x-forms.button type="button"wire:click="createManagedDnsRecord({{ \Illuminate\Support\Js::from($proposal['hostname']) }}, {{ $proposal['zone_id'] }})"- wire:target="createManagedDnsRecord" isHighlighted>Create DNS record</x-forms.button>+ wire:target="createManagedDnsRecord" isHighlighted+ canGate="update" :canResource="$dnsAuthResource">Create DNS record</x-forms.button>@endif</div>@endforeach@@ -41,4 +47,5 @@</div></template></div>-@endif+ @endif+</div>diff --git a/resources/views/livewire/security/integration-token-editor.blade.php b/resources/views/livewire/security/integration-token-editor.blade.phpindex 04c6eb8b56..e99106418f 100644--- a/resources/views/livewire/security/integration-token-editor.blade.php+++ b/resources/views/livewire/security/integration-token-editor.blade.php@@ -41,7 +41,7 @@</fieldset><div class="rounded-lg border border-neutral-200 p-1 dark:border-white/[0.08]"><x-forms.checkbox id="edit-automatic-dns" label="Automatically configure DNS" fullWidth- wire:model.live="automaticDns" />+ wire:model.live="automaticDns" canGate="update" :canResource="$integrationToken" /><p class="px-2.5 pb-2 text-[11px] text-neutral-500 dark:text-fg-dim">Create DNS records automatically when a new domain has one unambiguous matching credential.</p>@@ -76,7 +76,8 @@<div>Last refreshed {{ \Carbon\Carbon::parse(data_get($integrationToken->metadata, 'zones_synced_at'))->diffForHumans() }}</div>@endif</div>- <x-forms.button type="button" wire:click="refreshZones" wire:target="refreshZones">Refresh zones</x-forms.button>+ <x-forms.button type="button" wire:click="refreshZones" wire:target="refreshZones"+ canGate="update" :canResource="$integrationToken">Refresh zones</x-forms.button></div>@if ($zones !== [])<div class="max-h-48 overflow-y-auto border-t border-neutral-200 dark:border-white/[0.08]">diff --git a/resources/views/livewire/security/integration-token-form.blade.php b/resources/views/livewire/security/integration-token-form.blade.phpindex 63ca61ae80..fce54f1929 100644--- a/resources/views/livewire/security/integration-token-form.blade.php+++ b/resources/views/livewire/security/integration-token-form.blade.php@@ -53,7 +53,7 @@</fieldset><div class="rounded-lg border border-neutral-200 p-1 dark:border-white/[0.08]"><x-forms.checkbox id="automatic-dns" label="Automatically configure DNS" fullWidth- wire:model.live="automaticDns" />+ wire:model.live="automaticDns" canGate="create" :canResource="\App\Models\IntegrationToken::class" /><p class="px-2.5 pb-2 text-[11px] text-neutral-500 dark:text-fg-dim">Create DNS records automatically when a new domain has one unambiguous matching credential.</p>diff --git a/tests/Feature/ApplicationDomainsTest.php b/tests/Feature/ApplicationDomainsTest.phpindex 5196baadef..b6a7b81f56 100644--- a/tests/Feature/ApplicationDomainsTest.php+++ b/tests/Feature/ApplicationDomainsTest.php@@ -11,6 +11,7 @@ use App\Models\DnsProviderZone;use App\Models\Environment;use App\Models\InstanceSettings;use App\Models\IntegrationToken;+use App\Models\ManagedDnsRecord;use App\Models\Project;use App\Models\Server;use App\Models\StandaloneDocker;@@ -19,6 +20,7 @@ use App\Models\User;use App\Support\ValidationPatterns;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Queue;use Illuminate\Support\Str;use Livewire\Livewire;@@ -824,29 +826,6 @@ it('adds a domain to the application', function () {->toBe(['https://app.example.com', 'https://www.app.example.com']);});-it('dispatches configure dns jobs when a matching automatic zone and valid server ip exist', function () {- Queue::fake();-- $token = IntegrationToken::factory()->for($this->team)->create([- 'provider' => 'cloudflare',- 'capabilities' => ['dns'],- ]);- DnsProviderZone::factory()->for($token)->create(['name' => 'example.com']);-- Livewire::test(Domains::class, ['application' => $this->application->fresh()])- ->set('newDomain', 'https://app.example.com')- ->call('addDomain')- ->assertHasNoErrors()- ->assertDispatched('success', 'Domain added.');-- Queue::assertPushed(ConfigureDnsRecordJob::class, 2);- Queue::assertPushed(ConfigureDnsRecordJob::class, fn (ConfigureDnsRecordJob $job): bool => $job->hostname === 'app.example.com'- && $job->content === '203.0.113.10'- && $job->teamId === $this->team->id);- Queue::assertPushed(ConfigureDnsRecordJob::class, fn (ConfigureDnsRecordJob $job): bool => $job->hostname === 'www.app.example.com'- && $job->content === '203.0.113.10');-});-it('does not dispatch configure dns jobs when the server ip is missing or invalid', function () {Queue::fake();@@ -1036,6 +1015,79 @@ it('removes consecutive domains by stable row identity after indexes change', fuexpect($this->application->fresh()->fqdn)->toBe('https://third.example.com');});+it('deletes the managed dns record when removing a domain by key with deleteManagedDns', function () {+ $this->application->update(['fqdn' => 'https://app.example.com']);++ $token = IntegrationToken::factory()->for($this->team)->create([+ 'provider' => 'cloudflare',+ 'token' => 'secret',+ ]);+ $zone = DnsProviderZone::factory()->for($token)->create([+ 'provider_zone_id' => 'zone-1',+ 'name' => 'example.com',+ ]);+ $record = ManagedDnsRecord::factory()->create([+ 'team_id' => $this->team->id,+ 'integration_token_id' => $token->id,+ 'dns_provider_zone_id' => $zone->id,+ 'resource_type' => $this->application->getMorphClass(),+ 'resource_id' => $this->application->getKey(),+ 'provider_record_id' => 'record-1',+ 'type' => 'A',+ 'name' => 'app.example.com',+ 'content' => '203.0.113.10',+ ]);++ Http::fake(['https://api.cloudflare.com/client/v4/zones/zone-1/dns_records/record-1' => Http::sequence()+ ->push(['success' => true, 'result' => [+ 'id' => 'record-1',+ 'type' => 'A',+ 'name' => 'app.example.com',+ 'content' => '203.0.113.10',+ ]])+ ->push(['success' => true, 'result' => ['id' => 'record-1']])]);++ $domainKey = hash('sha256', 'https://app.example.com|');++ Livewire::test(Domains::class, ['application' => $this->application->fresh()])+ ->call('removeDomainByKey', $domainKey, '', ['deleteManagedDns'])+ ->assertDispatched('success');++ expect($this->application->fresh()->fqdn)->toBeNull()+ ->and(ManagedDnsRecord::query()->find($record->id))->toBeNull();+});++it('leaves the managed dns record when removing a domain by key without deleteManagedDns', function () {+ $this->application->update(['fqdn' => 'https://app.example.com']);++ $token = IntegrationToken::factory()->for($this->team)->create([+ 'provider' => 'cloudflare',+ 'token' => 'secret',+ ]);+ $zone = DnsProviderZone::factory()->for($token)->create([+ 'provider_zone_id' => 'zone-1',+ 'name' => 'example.com',+ ]);+ $record = ManagedDnsRecord::factory()->create([+ 'team_id' => $this->team->id,+ 'integration_token_id' => $token->id,+ 'dns_provider_zone_id' => $zone->id,+ 'provider_record_id' => 'record-1',+ 'type' => 'A',+ 'name' => 'app.example.com',+ 'content' => '203.0.113.10',+ ]);++ $domainKey = hash('sha256', 'https://app.example.com|');++ Livewire::test(Domains::class, ['application' => $this->application->fresh()])+ ->call('removeDomainByKey', $domainKey, '')+ ->assertDispatched('success');++ expect($this->application->fresh()->fqdn)->toBeNull()+ ->and(ManagedDnsRecord::query()->find($record->id))->not->toBeNull();+});+it('does not revalidate dns on remaining domains when removing one', function () {$settings = InstanceSettings::get();$settings->is_dns_validation_enabled = true;@@ -1286,6 +1338,60 @@ it('hides dns check buttons from members', function () {->assertDontSee('Check DNS');});+it('disables create dns record for members and hides replace confirmation', function () {+ $this->team->members()->updateExistingPivot($this->user->id, ['role' => 'member']);+ $this->actingAs($this->user->fresh());++ $proposal = [+ 'hostname' => 'app.example.com',+ 'zone_id' => 1,+ 'zone' => 'example.com',+ 'credential' => 'Cloudflare',+ 'target' => '203.0.113.10',+ 'managed' => false,+ ];++ $createHtml = Livewire::test(Domains::class, ['application' => $this->application->fresh()])+ ->set('showDnsProviderModal', true)+ ->set('dnsProviderProposals', [$proposal])+ ->html();++ expect($createHtml)->toContain('Create DNS record')+ ->toMatch('/<button[^>]*\sdisabled(?:[=\s>])[^>]*>.*?Create DNS record/s');++ $replaceHtml = Livewire::test(Domains::class, ['application' => $this->application->fresh()])+ ->set('showDnsProviderModal', true)+ ->set('dnsProviderProposals', [$proposal])+ ->set('dnsProviderConflicts', [+ 'app.example.com|1' => [+ 'record_id' => 'rec-1',+ 'current' => '198.51.100.10',+ 'proposed' => '203.0.113.10',+ ],+ ])+ ->html();++ expect($replaceHtml)->toContain('Currently 198.51.100.10')+ ->toMatch('/<button[^>]*\sdisabled(?:[=\s>])[^>]*>.*?Replace record/s');+});++it('shows create dns record enabled for owners', function () {+ $html = Livewire::test(Domains::class, ['application' => $this->application->fresh()])+ ->set('showDnsProviderModal', true)+ ->set('dnsProviderProposals', [[+ 'hostname' => 'app.example.com',+ 'zone_id' => 1,+ 'zone' => 'example.com',+ 'credential' => 'Cloudflare',+ 'target' => '203.0.113.10',+ 'managed' => false,+ ]])+ ->html();++ expect($html)->toContain('Create DNS record')+ ->not->toMatch('/<button[^>]*\sdisabled(?:[=\s>])[^>]*>.*?Create DNS record/s');+});+it('loads persisted dns status on page load', function () {$this->application->update(['fqdn' => 'https://app.example.com',@@ -1485,7 +1591,7 @@ it('resolves hostname server addresses to a real ip for dns messages', function// Failed checks show required DNS record guidance; ok checks mention the hostname label.if ($component->get('domainRows.0.dns_status') === 'failed') {- expect($message)->toBe("{$recordType} record → {$resolvedIp}")+ expect($message)->toBe("Required DNS record type {$recordType} pointing to {$resolvedIp}")->and($message)->not->toContain('CNAME');} else {expect($message)->toContain($resolvedIp)diff --git a/tests/Feature/ButtonDepthInteractionTest.php b/tests/Feature/ButtonDepthInteractionTest.phpindex b2076f4fe4..9e1e435a84 100644--- a/tests/Feature/ButtonDepthInteractionTest.php+++ b/tests/Feature/ButtonDepthInteractionTest.php@@ -7,8 +7,7 @@ test('standard buttons use raised hover and pressed depth states', function () {->toContain('--button-depth-color: rgb(0 0 0 / 0.22);')->toContain('--button-depth: 0 2px 0 var(--button-depth-color);')->toContain('--button-depth-hover: 0 3px 0 var(--button-depth-color);')- ->toContain('.button-highlighted:not(:disabled)')- ->toContain('--button-depth-color: color-mix(in oklab, var(--color-coollabs) 52%, black);')+ ->toContain('--button-depth-color: var(--color-coollabs-300);')->toContain('.dark .button:not(.button-highlighted):not(.button-error):not([isHighlighted]):not(:disabled)')->not->toContain('.dark .button:not(.button-highlighted):not([isHighlighted]):not(:disabled)')->toContain('--button-depth-color: rgb(255 255 255 / 0.08);')diff --git a/tests/Feature/DatabaseBackupUploadValidationTest.php b/tests/Feature/DatabaseBackupUploadValidationTest.phpindex f8416fe6c7..82833747bc 100644--- a/tests/Feature/DatabaseBackupUploadValidationTest.php+++ b/tests/Feature/DatabaseBackupUploadValidationTest.php@@ -1,9 +1,9 @@<?phpuse App\Http\Controllers\UploadController;-use App\Livewire\Project\Database\ImportForm;use App\Models\StandalonePostgresql;use App\Support\DatabaseBackupFileValidator;+use App\Support\DatabaseImport\DatabaseImportCommandBuilder;use Illuminate\Http\UploadedFile;use Illuminate\Support\Facades\Process;@@ -67,18 +67,12 @@ function invokeHasAllowedExtension(string $name): boolreturn $method->invoke(null, $name);}-function backupValidationImportFormWithResource(string $modelClass): ImportForm+function postgresScanScript(string $path): ?string{- $component = new class extends ImportForm- {- public $resource;- };+ $database = Mockery::mock(StandalonePostgresql::class);+ $database->shouldReceive('getMorphClass')->andReturn(StandalonePostgresql::class);- $database = Mockery::mock($modelClass);- $database->shouldReceive('getMorphClass')->andReturn($modelClass);- $component->resource = $database;-- return $component;+ return (new DatabaseImportCommandBuilder)->buildPostgresRestoreScanScript($database, $path);}function makeTemporaryUpload(string $name, string $content): UploadedFile@@ -173,39 +167,21 @@ SQL;});test('postgresql restore commands include a safety check before execution', function () {- $component = new class extends ImportForm- {- public function __get($property)- {- if ($property === 'resource') {- return new class- {- public function getMorphClass(): string- {- return StandalonePostgresql::class;- }- };- }-- return parent::__get($property);- }- };- $component->container = 'postgres-test';+ $database = Mockery::mock(StandalonePostgresql::class);+ $database->shouldReceive('getMorphClass')->andReturn(StandalonePostgresql::class);- $command = $component->buildRestoreSafetyCheckCommand('/tmp/restore_test');+ $command = (new DatabaseImportCommandBuilder)->buildPostgresSafetyCommand(+ $database,+ 'postgres-test',+ '/tmp/restore_test',+ );expect($command)->toContain('docker exec postgres-test')->toContain('COPY ... PROGRAM')->toContain('/tmp/restore_test')- ->toContain('grep -Eiq');-});--test('non postgresql restore commands do not include a safety check', function () {- $component = backupValidationImportFormWithResource('App\Models\StandaloneMysql');- $component->container = 'mysql-test';-- expect($component->buildRestoreSafetyCheckCommand('/tmp/restore_test'))->toBeNull();+ ->toContain('grep -Eiq')+ ->toContain('pg_restore -l');});test('file scanner detects program execution payloads inside gzipped backups', function () {@@ -251,11 +227,8 @@ test('backup validator rejects plaintext .dump containing program execution', fu});test('remote postgresql scanner blocks bypass payloads', function (string $content, bool $gzip) {- $component = backupValidationImportFormWithResource(StandalonePostgresql::class);- $component->container = 'postgres-test';-$payload = writeScanPayload($content, $gzip);- $script = $component->buildPostgresRestoreScanScript($payload);+ $script = postgresScanScript($payload);expect(scannerBlocks($script))->toBeTrue();})->with([@@ -272,11 +245,8 @@ test('remote postgresql scanner blocks bypass payloads', function (string $conte]);test('remote postgresql scanner allows legitimate restores', function (string $content, bool $gzip) {- $component = backupValidationImportFormWithResource(StandalonePostgresql::class);- $component->container = 'postgres-test';-$payload = writeScanPayload($content, $gzip);- $script = $component->buildPostgresRestoreScanScript($payload);+ $script = postgresScanScript($payload);expect(scannerBlocks($script))->toBeFalse();})->with([@@ -288,7 +258,6 @@ test('remote postgresql scanner allows legitimate restores', function (string $c]);test('remote postgresql scanner inspects custom archives instead of skipping them', function () {- $component = backupValidationImportFormWithResource(StandalonePostgresql::class);$safeArchive = writeScanPayload("PGDMP\0binary archive");$maliciousSql = "COPY x FROM PROGRAM 'id';\n";$safeSql = "CREATE TABLE users (id integer);\nCOPY users FROM stdin;\n1\tTaylor\n\\.\n";@@ -298,10 +267,10 @@ test('remote postgresql scanner inspects custom archives instead of skipping the$unreadablePath = fakePgRestorePath($safeSql, listExitCode: 1);$path = getenv('PATH') ?: '/usr/bin:/bin';- expect(scannerBlocks($component->buildPostgresRestoreScanScript($safeArchive), ['PATH' => $maliciousPath.':'.$path]))->toBeTrue()- ->and(scannerBlocks($component->buildPostgresRestoreScanScript($safeArchive), ['PATH' => $safePath.':'.$path]))->toBeFalse()- ->and(scannerBlocks($component->buildPostgresRestoreScanScript($safeArchive), ['PATH' => $unreadablePath.':'.$path]))->toBeTrue()- ->and(scannerBlocks($component->buildPostgresRestoreScanScript($safeArchive)))->toBeTrue();+ expect(scannerBlocks(postgresScanScript($safeArchive), ['PATH' => $maliciousPath.':'.$path]))->toBeTrue()+ ->and(scannerBlocks(postgresScanScript($safeArchive), ['PATH' => $safePath.':'.$path]))->toBeFalse()+ ->and(scannerBlocks(postgresScanScript($safeArchive), ['PATH' => $unreadablePath.':'.$path]))->toBeTrue()+ ->and(scannerBlocks(postgresScanScript($safeArchive)))->toBeTrue();});test('MAX_BYTES constant is 10 GiB', function () {diff --git a/tests/Feature/DatabaseImportFormRunningStateTest.php b/tests/Feature/DatabaseImportFormRunningStateTest.phpnew file mode 100644index 0000000000..a355be7782--- /dev/null+++ b/tests/Feature/DatabaseImportFormRunningStateTest.php@@ -0,0 +1,132 @@+<?php++use App\Actions\Database\StartDatabaseImport;+use App\Livewire\Project\Database\ImportForm;+use App\Models\Environment;+use App\Models\InstanceSettings;+use App\Models\Project;+use App\Models\Server;+use App\Models\StandaloneDocker;+use App\Models\StandalonePostgresql;+use App\Models\Team;+use App\Models\User;+use App\Support\DatabaseImport\DatabaseImportException;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Str;+use Livewire\Features\SupportTesting\Testable;+use Livewire\Livewire;+use Spatie\Activitylog\Models\Activity;++uses(RefreshDatabase::class);++beforeEach(function () {+ InstanceSettings::forceCreate([+ 'id' => 0,+ 'disable_two_step_confirmation' => true,+ ]);++ $this->team = Team::factory()->create();+ $this->user = User::factory()->create();+ $this->team->members()->attach($this->user, ['role' => 'owner']);+ $this->actingAs($this->user);+ session(['currentTeam' => $this->team]);++ $this->server = Server::factory()->create(['team_id' => $this->team->id]);+ $this->destination = StandaloneDocker::firstOrCreate(+ ['server_id' => $this->server->id, 'network' => 'coolify'],+ ['uuid' => (string) Str::uuid(), 'name' => 'docker']+ );+ $this->project = Project::factory()->create(['team_id' => $this->team->id]);+ $this->environment = Environment::factory()->create(['project_id' => $this->project->id]);+ $this->database = StandalonePostgresql::create([+ 'uuid' => (string) Str::uuid(),+ 'name' => 'db',+ 'postgres_user' => 'postgres',+ 'postgres_password' => 'password',+ 'postgres_db' => 'db',+ 'image' => 'postgres:17',+ 'status' => 'running',+ 'environment_id' => $this->environment->id,+ 'destination_id' => $this->destination->id,+ 'destination_type' => $this->destination->getMorphClass(),+ ]);+});++class ImportFormRunningStateTestComponent extends ImportForm+{+ public function mount($database = null, $server = null): void+ {+ $this->resourceId = $database->id;+ $this->resourceType = $database::class;+ $this->serverId = $server->id;+ $this->container = $database->uuid;+ $this->resourceUuid = $database->uuid;+ $this->resourceStatus = $database->status ?? '';+ $this->resourceDbType = $database->type();+ $this->loadAvailableS3Storages();+ }++ public function render()+ {+ return view('livewire.project.database.import-form');+ }+}++function importForm(): Testable+{+ return Livewire::test(ImportFormRunningStateTestComponent::class, [+ 'database' => test()->database,+ 'server' => test()->server,+ ])+ ->set('filename', 'backup.dump')+ ->set('s3StorageId', 1)+ ->set('s3Path', '/backups/backup.dump')+ ->set('s3FileSize', 1024);+}++test('runImport resets importRunning when StartDatabaseImport rejects the import', function () {+ StartDatabaseImport::shouldRun()->once()->andThrow(+ new DatabaseImportException('The completed upload was not found.')+ );++ importForm()+ ->call('runImport')+ ->assertSet('importRunning', false)+ ->assertDispatched('error', 'The completed upload was not found.');+});++test('runImport resets importRunning when StartDatabaseImport throws a generic error', function () {+ StartDatabaseImport::shouldRun()->once()->andThrow(new RuntimeException('scp failed'));++ importForm()+ ->call('runImport')+ ->assertSet('importRunning', false)+ ->assertDispatched('error', 'scp failed');+});++test('restoreFromS3 resets importRunning when StartDatabaseImport rejects the import', function () {+ StartDatabaseImport::shouldRun()->once()->andThrow(+ new DatabaseImportException('The S3 backup was not found or exceeds the 10 GiB limit.')+ );++ importForm()+ ->call('restoreFromS3')+ ->assertSet('importRunning', false)+ ->assertDispatched('error', 'The S3 backup was not found or exceeds the 10 GiB limit.');+});++test('runImport keeps importRunning true after a successful start', function () {+ $activity = Activity::create([+ 'log_name' => 'default',+ 'description' => 'queued',+ 'properties' => ['status' => 'queued'],+ ]);+ StartDatabaseImport::shouldRun()->once()->andReturn($activity);++ importForm()+ ->call('runImport')+ ->assertSet('importRunning', true)+ ->assertSet('activityId', $activity->id)+ ->assertDispatched('activityMonitor', $activity->id)+ ->assertDispatched('databaserestore');+});diff --git a/tests/Feature/DnsProviderManagementTest.php b/tests/Feature/DnsProviderManagementTest.phpindex 82147ed476..1b1bfb0734 100644--- a/tests/Feature/DnsProviderManagementTest.php+++ b/tests/Feature/DnsProviderManagementTest.php@@ -1,15 +1,33 @@<?phpuse App\Events\DnsRecordConfigurationFinished;+use App\Exceptions\DnsRecordConflictException;+use App\Jobs\CheckDomainDnsJob;use App\Jobs\ConfigureDnsRecordJob;+use App\Livewire\Project\Application\Domains;+use App\Livewire\Project\Service\Domains as ServiceDomains;+use App\Models\Application;use App\Models\DnsProviderZone;+use App\Models\Environment;+use App\Models\InstanceSettings;use App\Models\IntegrationToken;use App\Models\ManagedDnsRecord;+use App\Models\Project;+use App\Models\Server;+use App\Models\Service;+use App\Models\ServiceApplication;+use App\Models\StandaloneDocker;use App\Models\Team;+use App\Models\User;use App\Services\Dns\CloudflareDnsProvider;+use Illuminate\Database\Eloquent\ModelNotFoundException;use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Event;use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;+use Livewire\Livewire;uses(RefreshDatabase::class);@@ -54,6 +72,32 @@ test('all credentials for the most specific zone are returned without suffix fal->and($provider->findZones($team->id, 'notexample.com'))->toBeEmpty();});+test('team cloudflare zones are queried once per provider instance', function () {+ $team = Team::factory()->create();+ $otherTeam = Team::factory()->create();+ $token = IntegrationToken::factory()->for($team)->create(['provider' => 'cloudflare']);+ $otherToken = IntegrationToken::factory()->for($otherTeam)->create(['provider' => 'cloudflare']);+ DnsProviderZone::factory()->for($token)->create(['name' => 'example.com']);+ DnsProviderZone::factory()->for($otherToken)->create(['name' => 'other.com']);++ $provider = app(CloudflareDnsProvider::class);++ DB::flushQueryLog();+ DB::enableQueryLog();+ expect($provider->findZones($team->id, 'app.example.com'))->toHaveCount(1);+ $firstCallQueries = count(DB::getQueryLog());++ expect($provider->findZones($team->id, 'api.example.com'))->toHaveCount(1)+ ->and($provider->findZones($team->id, 'www.example.com'))->toHaveCount(1)+ ->and(count(DB::getQueryLog()))->toBe($firstCallQueries)+ ->and($firstCallQueries)->toBeGreaterThan(0);++ $afterTeamQueries = count(DB::getQueryLog());+ expect($provider->findZones($otherTeam->id, 'app.other.com'))->toHaveCount(1)+ ->and(count(DB::getQueryLog()))->toBeGreaterThan($afterTeamQueries);+ DB::disableQueryLog();+});+test('a cloudflare record is created and tracked as managed by coolify', function () {$token = IntegrationToken::factory()->create(['provider' => 'cloudflare', 'token' => 'secret']);$zone = DnsProviderZone::factory()->for($token)->create(['provider_zone_id' => 'zone-1', 'name' => 'example.com']);@@ -95,6 +139,126 @@ test('queued dns configuration creates the record and broadcasts completion', fu&& $event->hostname === 'app.example.com');});+test('missing zone throws from handle without broadcasting completion', function () {+ Event::fake([DnsRecordConfigurationFinished::class]);+ $token = IntegrationToken::factory()->create(['provider' => 'cloudflare', 'token' => 'secret']);++ $job = new ConfigureDnsRecordJob(+ teamId: $token->team_id,+ zoneId: 999999,+ resourceType: null,+ resourceId: null,+ hostname: 'app.example.com',+ content: '203.0.113.10',+ );++ expect(fn () => $job->handle(app(CloudflareDnsProvider::class)))+ ->toThrow(ModelNotFoundException::class);++ Event::assertNotDispatched(DnsRecordConfigurationFinished::class);+});++test('job failure broadcasts a dns configuration finished event', function () {+ Event::fake([DnsRecordConfigurationFinished::class]);+ $token = IntegrationToken::factory()->create(['provider' => 'cloudflare', 'token' => 'secret']);++ $job = new ConfigureDnsRecordJob(+ teamId: $token->team_id,+ zoneId: 999999,+ resourceType: 'App\\Models\\Application',+ resourceId: 42,+ hostname: 'app.example.com',+ content: '203.0.113.10',+ );+ $job->failed(new ModelNotFoundException);++ Event::assertDispatched(DnsRecordConfigurationFinished::class, fn ($event) => $event->successful === false+ && $event->teamId === $token->team_id+ && $event->resourceType === 'App\\Models\\Application'+ && $event->resourceId === 42+ && $event->hostname === 'app.example.com'+ && $event->credential === ''+ && $event->message === 'The DNS zone is no longer available.');+});++test('an existing matching remote record is tracked without creating a new one', 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::response([+ 'success' => true,+ 'result' => [[+ 'id' => 'record-1',+ 'type' => 'A',+ 'name' => 'app.example.com',+ 'content' => '203.0.113.10',+ ]],+ ]),+ ]);++ $record = app(CloudflareDnsProvider::class)->createRecord($zone, 'app.example.com', '203.0.113.10');++ expect($record->provider_record_id)->toBe('record-1')+ ->and($record->content)->toBe('203.0.113.10')+ ->and(ManagedDnsRecord::query()->where('name', 'app.example.com')->exists())->toBeTrue();+ Http::assertNotSent(fn ($request) => $request->method() === 'POST');+});++test('queued dns configuration treats a matching existing record as success', function () {+ Event::fake([DnsRecordConfigurationFinished::class]);+ $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::response([+ 'success' => true,+ 'result' => [[+ 'id' => 'record-1',+ 'type' => 'A',+ 'name' => 'app.example.com',+ 'content' => '203.0.113.10',+ ]],+ ]),+ ]);++ $job = new ConfigureDnsRecordJob(+ teamId: $token->team_id,+ zoneId: $zone->id,+ resourceType: null,+ resourceId: null,+ hostname: 'app.example.com',+ content: '203.0.113.10',+ );+ $job->handle(app(CloudflareDnsProvider::class));++ expect(ManagedDnsRecord::query()->where('name', 'app.example.com')->exists())->toBeTrue();+ Event::assertDispatched(DnsRecordConfigurationFinished::class, fn ($event) => $event->successful+ && $event->hostname === 'app.example.com');+ Http::assertNotSent(fn ($request) => $request->method() === 'POST');+});++test('an existing remote record with different content remains a conflict', 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::response([+ 'success' => true,+ 'result' => [[+ 'id' => 'record-1',+ 'type' => 'A',+ 'name' => 'app.example.com',+ 'content' => '203.0.113.99',+ ]],+ ]),+ ]);++ expect(fn () => app(CloudflareDnsProvider::class)->createRecord($zone, 'app.example.com', '203.0.113.10'))+ ->toThrow(DnsRecordConflictException::class);+ expect(ManagedDnsRecord::query()->where('name', 'app.example.com')->exists())->toBeFalse();+ Http::assertNotSent(fn ($request) => $request->method() === 'POST');+});+test('a managed record changed outside coolify is not deleted', function () {$record = ManagedDnsRecord::factory()->create(['provider_record_id' => 'record-1', 'type' => 'A', 'name' => 'app.example.com', 'content' => '203.0.113.10',@@ -121,22 +285,400 @@ test('an unchanged managed record is deleted from cloudflare and coolify', funct->and(ManagedDnsRecord::query()->find($record->id))->toBeNull();});-test('domain dns ux prompts after add and keeps later provider actions with manual records', function () {- $applicationComponent = file_get_contents(app_path('Livewire/Project/Application/Domains.php'));- $serviceComponent = file_get_contents(app_path('Livewire/Project/Service/Domains.php'));- $dnsMenu = file_get_contents(resource_path('views/livewire/project/shared/cloudflare-autoconfigure.blade.php'));- $dnsProviderConcern = file_get_contents(app_path('Livewire/Concerns/InteractsWithDnsProviders.php'));+test('dns provider modal view always has a single root element', function () {+ $providerModal = file_get_contents(resource_path('views/livewire/project/shared/dns-provider-management.blade.php'));++ expect(ltrim($providerModal))->toStartWith('<div class="contents">')+ ->and($providerModal)->toContain('@if ($showDnsProviderModal)');+});++describe('domain DNS configuration after add', function () {+ beforeEach(function () {+ $this->withoutVite();+ config()->set('app.maintenance.store', 'array');+ Queue::fake();++ InstanceSettings::unguarded(fn () => InstanceSettings::updateOrCreate(+ ['id' => 0],+ ['id' => 0, 'is_dns_validation_enabled' => false],+ ));++ $this->team = Team::factory()->create();+ $this->user = User::factory()->create();+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);+ $this->actingAs($this->user);+ session(['currentTeam' => $this->team]);- expect($applicationComponent)->toContain('configureDnsAfterDomainAdd($addedUrls)')- ->and($serviceComponent)->toContain('configureDnsAfterDomainAdd($addedUrls)')- ->and($dnsMenu)->toContain('wire:click="openManualDnsRecords"')- ->and($dnsMenu)->toContain('Add with {{ $provider[\'credential\'] }}')- ->and($dnsMenu)->not->toContain('Connected provider')- ->and($dnsProviderConcern)->toContain('ConfigureDnsRecordJob::dispatch(')- ->and($dnsProviderConcern)->toContain('Adding DNS record for {$proposal[\'hostname\']}')- ->and($dnsProviderConcern)->toContain('dispatch(\'success\', $event[\'message\'])');+ $keyId = DB::table('private_keys')->insertGetId([+ 'uuid' => (string) Str::uuid(),+ 'name' => 'Test Key',+ 'private_key' => 'test-key',+ 'team_id' => $this->team->id,+ 'created_at' => now(),+ 'updated_at' => now(),+ ]);+ $this->server = Server::factory()->create([+ 'team_id' => $this->team->id,+ 'private_key_id' => $keyId,+ 'ip' => '203.0.113.10',+ ]);+ $this->server->settings()->update([+ 'is_reachable' => true,+ 'is_usable' => true,+ ]);++ StandaloneDocker::withoutEvents(function () {+ $this->destination = StandaloneDocker::firstOrCreate(+ ['server_id' => $this->server->id, 'network' => 'coolify'],+ ['uuid' => (string) Str::uuid(), 'name' => 'test-docker'],+ );+ });++ $this->project = Project::factory()->create(['team_id' => $this->team->id]);+ $this->environment = Environment::factory()->create(['project_id' => $this->project->id]);++ $this->token = IntegrationToken::factory()->for($this->team)->create([+ 'provider' => 'cloudflare',+ 'name' => 'Production DNS',+ 'token' => 'secret',+ 'capabilities' => ['dns'],+ ]);+ $this->zone = DnsProviderZone::factory()->for($this->token)->create([+ 'name' => 'example.com',+ 'provider_zone_id' => 'zone-1',+ ]);+ });++ test('application domains queues a dns record job and marks the row pending', function () {+ $application = Application::factory()->create([+ 'uuid' => (string) Str::uuid(),+ 'name' => 'DNS App',+ 'environment_id' => $this->environment->id,+ 'destination_id' => $this->destination->id,+ 'destination_type' => $this->destination->getMorphClass(),+ 'fqdn' => null,+ 'redirect' => 'both',+ 'build_pack' => 'nixpacks',+ ]);+ $application->settings()->update([+ 'is_container_label_readonly_enabled' => true,+ ]);++ Livewire::test(Domains::class, ['application' => $application->fresh()])+ ->set('newDomain', 'https://app.example.com')+ ->call('addDomain')+ ->assertHasNoErrors()+ ->assertDispatched('success', 'Domain added.')+ ->assertDispatched('info', 'Adding DNS record for app.example.com.')+ ->assertSet('showDnsProviderModal', false)+ ->assertSet('domainRows', fn (array $rows): bool => collect($rows)->contains(+ fn (array $row): bool => $row['url'] === 'https://app.example.com'+ && $row['dns_status'] === 'pending'+ ))+ ->assertSet('domainRows', fn (array $rows): bool => collect($rows)->contains(+ fn (array $row): bool => $row['url'] === 'https://www.app.example.com'+ && $row['dns_status'] === 'pending'+ ));++ Queue::assertPushed(ConfigureDnsRecordJob::class, 2);+ Queue::assertPushed(ConfigureDnsRecordJob::class, fn (ConfigureDnsRecordJob $job): bool => $job->hostname === 'app.example.com'+ && $job->content === '203.0.113.10'+ && $job->teamId === $this->team->id+ && $job->zoneId === $this->zone->id+ && $job->resourceType === $application->getMorphClass()+ && (string) $job->resourceId === (string) $application->id);+ Queue::assertPushed(ConfigureDnsRecordJob::class, fn (ConfigureDnsRecordJob $job): bool => $job->hostname === 'www.app.example.com'+ && $job->content === '203.0.113.10');+ Queue::assertNotPushed(CheckDomainDnsJob::class);+ });++ test('service domains queues a dns record job and marks the row pending', function () {+ $service = Service::factory()->create([+ 'server_id' => $this->server->id,+ 'destination_id' => $this->destination->id,+ 'destination_type' => $this->destination->getMorphClass(),+ 'environment_id' => $this->environment->id,+ 'docker_compose_raw' => "services:\n web:\n image: nginx:alpine\n",+ ]);+ $webApp = ServiceApplication::create([+ 'uuid' => (string) Str::uuid(),+ 'service_id' => $service->id,+ 'name' => 'web',+ 'human_name' => 'Web',+ 'image' => 'nginx:alpine',+ 'fqdn' => null,+ ]);++ Livewire::test(ServiceDomains::class, ['service' => $service->fresh(['applications', 'server'])])+ ->set('newServiceApplicationId', $webApp->id)+ ->set('newDomain', 'https://web.example.com')+ ->call('addDomain')+ ->assertHasNoErrors()+ ->assertDispatched('success', 'Domain added.')+ ->assertDispatched('info', 'Adding DNS record for web.example.com.')+ ->assertSet('showDnsProviderModal', false)+ ->assertSet('domainRows', fn (array $rows): bool => collect($rows)->contains(+ fn (array $row): bool => $row['url'] === 'https://web.example.com'+ && $row['dns_status'] === 'pending'+ ));++ Queue::assertPushed(ConfigureDnsRecordJob::class, 1);+ Queue::assertPushed(ConfigureDnsRecordJob::class, fn (ConfigureDnsRecordJob $job): bool => $job->hostname === 'web.example.com'+ && $job->content === '203.0.113.10'+ && $job->teamId === $this->team->id+ && $job->zoneId === $this->zone->id+ && $job->resourceType === $webApp->getMorphClass()+ && (string) $job->resourceId === (string) $webApp->id);+ Queue::assertNotPushed(CheckDomainDnsJob::class);+ });+});++test('dns provider action controls declare update authorization against the resource', function () {+ $dnsMenu = file_get_contents(resource_path('views/livewire/project/shared/cloudflare-autoconfigure.blade.php'));$providerModal = file_get_contents(resource_path('views/livewire/project/shared/dns-provider-management.blade.php'));- expect($providerModal)->toContain('Illuminate\\Support\\Js::from($proposal[\'hostname\'])')- ->and($providerModal)->not->toContain('createManagedDnsRecord(@js');++ expect($dnsMenu)+ ->toContain('$dnsAuthResource = property_exists($this, \'application\') ? $this->application : $this->service')+ ->toMatch('/<x-forms\.button(?=[^>]*wire:click="createManagedDnsRecord)(?=[^>]*canGate="update")(?=[^>]*:canResource="\$dnsAuthResource")[^>]*>/');++ expect($providerModal)+ ->toContain('$dnsAuthResource = property_exists($this, \'application\') ? $this->application : $this->service')+ ->toMatch('/<x-modal-confirmation(?=[^>]*submitAction="replaceManagedDnsRecord)(?=[^>]*canGate="update")(?=[^>]*:canResource="\$dnsAuthResource")[^>]*>/')+ ->toMatch('/<x-forms\.button(?=[^>]*wire:click="createManagedDnsRecord)(?=[^>]*canGate="update")(?=[^>]*:canResource="\$dnsAuthResource")[^>]*>/');+});++test('removing a domain deletes only the managed dns record for that resource', function () {+ $this->withoutVite();+ config(['app.maintenance.driver' => 'file']);+ InstanceSettings::unguarded(fn () => InstanceSettings::updateOrCreate(+ ['id' => 0],+ ['id' => 0, 'is_dns_validation_enabled' => false],+ ));++ $team = Team::factory()->create();+ $user = User::factory()->create();+ $team->members()->attach($user->id, ['role' => 'owner']);+ $this->actingAs($user);+ session(['currentTeam' => $team]);++ $server = Server::factory()->create(['team_id' => $team->id, 'ip' => '203.0.113.10']);+ $server->settings()->update(['is_reachable' => true, 'is_usable' => true]);+ $destination = StandaloneDocker::withoutEvents(fn () => StandaloneDocker::firstOrCreate(+ ['server_id' => $server->id, 'network' => 'coolify'],+ ['uuid' => (string) Str::uuid(), 'name' => 'test-docker'],+ ));+ $project = Project::factory()->create(['team_id' => $team->id]);+ $environment = Environment::factory()->create(['project_id' => $project->id]);++ $application = Application::factory()->create([+ 'environment_id' => $environment->id,+ 'destination_id' => $destination->id,+ 'destination_type' => $destination->getMorphClass(),+ 'fqdn' => 'https://app.example.com',+ 'build_pack' => 'nixpacks',+ ]);+ $application->settings()->update(['is_container_label_readonly_enabled' => true]);++ $otherApplication = Application::factory()->create([+ 'environment_id' => $environment->id,+ 'destination_id' => $destination->id,+ 'destination_type' => $destination->getMorphClass(),+ 'fqdn' => 'https://other.example.com',+ 'build_pack' => 'nixpacks',+ ]);++ $token = IntegrationToken::factory()->for($team)->create(['provider' => 'cloudflare', 'token' => 'secret']);+ $zone = DnsProviderZone::factory()->for($token)->create(['provider_zone_id' => 'zone-1', 'name' => 'example.com']);++ $otherRecord = ManagedDnsRecord::factory()->create([+ 'team_id' => $team->id,+ 'integration_token_id' => $token->id,+ 'dns_provider_zone_id' => $zone->id,+ 'resource_type' => $otherApplication->getMorphClass(),+ 'resource_id' => $otherApplication->getKey(),+ 'provider_record_id' => 'record-other',+ 'type' => 'A',+ 'name' => 'app.example.com',+ 'content' => '203.0.113.10',+ ]);+ $ownRecord = ManagedDnsRecord::factory()->create([+ 'team_id' => $team->id,+ 'integration_token_id' => $token->id,+ 'dns_provider_zone_id' => $zone->id,+ 'resource_type' => $application->getMorphClass(),+ 'resource_id' => $application->getKey(),+ 'provider_record_id' => 'record-own',+ 'type' => 'A',+ 'name' => 'app.example.com',+ 'content' => '203.0.113.10',+ ]);++ Http::fake([+ 'https://api.cloudflare.com/client/v4/zones/*/dns_records/record-own' => Http::sequence()+ ->push(['success' => true, 'result' => ['id' => 'record-own', 'type' => 'A', 'name' => 'app.example.com', 'content' => '203.0.113.10']])+ ->push(['success' => true, 'result' => ['id' => 'record-own']]),+ 'https://api.cloudflare.com/client/v4/zones/*/dns_records/record-other' => Http::response([+ 'success' => true,+ 'result' => ['id' => 'record-other', 'type' => 'A', 'name' => 'app.example.com', 'content' => '203.0.113.10'],+ ]),+ ]);++ Livewire::test(Domains::class, ['application' => $application->fresh()])+ ->call('removeDomain', 0, '', ['deleteManagedDns'])+ ->assertDispatched('success');++ expect(ManagedDnsRecord::query()->find($ownRecord->id))->toBeNull()+ ->and(ManagedDnsRecord::query()->find($otherRecord->id))->not->toBeNull();++ Http::assertSent(fn ($request) => str_contains($request->url(), 'record-own') && $request->method() === 'DELETE');+ Http::assertNotSent(fn ($request) => str_contains($request->url(), 'record-other'));});++test('replaceRecord updates the cloudflare record when the conflict still matches', 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/record-1' => Http::response([+ 'success' => true, 'result' => ['id' => 'record-1'],+ ]),+ 'https://api.cloudflare.com/client/v4/zones/zone-1/dns_records?*' => Http::response([+ 'success' => true,+ 'result' => [['id' => 'record-1', 'type' => 'A', 'name' => 'app.example.com', 'content' => '198.51.100.50']],+ ]),+ ]);++ $record = app(CloudflareDnsProvider::class)->replaceRecord(+ $zone, 'record-1', 'app.example.com', '203.0.113.10', expectedCurrent: '198.51.100.50',+ );++ expect($record->provider_record_id)->toBe('record-1')->and($record->content)->toBe('203.0.113.10');+ Http::assertSent(fn ($request) => $request->method() === 'PUT'+ && str_ends_with($request->url(), '/dns_records/record-1')+ && $request->data()['name'] === 'app.example.com'+ && $request->data()['content'] === '203.0.113.10');+});++test('replaceRecord rejects a stale or tampered conflict without updating dns', function (string $recordId, string $current) {+ $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::response([+ 'success' => true,+ 'result' => [['id' => 'record-1', 'type' => 'A', 'name' => 'app.example.com', 'content' => '198.51.100.50']],+ ]),+ 'https://api.cloudflare.com/client/v4/zones/zone-1/dns_records/*' => Http::response(['success' => true, 'result' => ['id' => 'record-other']]),+ ]);++ expect(fn () => app(CloudflareDnsProvider::class)->replaceRecord(+ $zone, $recordId, 'app.example.com', '203.0.113.10', expectedCurrent: $current,+ ))->toThrow(RuntimeException::class, 'The DNS conflict is no longer available. Check the record again.');++ Http::assertNotSent(fn ($request) => $request->method() === 'PUT');+})->with([+ 'wrong record id' => ['record-other', '198.51.100.50'],+ 'wrong current value' => ['record-1', '203.0.113.99'],+]);++test('replacing a managed dns record uses the server ip and live cloudflare record id', function () {+ ['application' => $application, 'zone' => $zone] = prepareManagedDnsApplication();++ Http::fake([+ 'https://api.cloudflare.com/client/v4/zones/zone-1/dns_records/record-1' => Http::response([+ 'success' => true, 'result' => ['id' => 'record-1'],+ ]),+ 'https://api.cloudflare.com/client/v4/zones/zone-1/dns_records?*' => Http::response([+ 'success' => true,+ 'result' => [['id' => 'record-1', 'type' => 'A', 'name' => 'app.example.com', 'content' => '198.51.100.50']],+ ]),+ ]);++ Livewire::test(Domains::class, ['application' => $application->fresh()])+ ->set('dnsProviderConflicts', [+ 'app.example.com|'.$zone->id => [+ 'record_id' => 'record-1',+ 'current' => '198.51.100.50',+ 'proposed' => '198.51.100.1',+ ],+ ])+ ->call('replaceManagedDnsRecord', 'app.example.com', $zone->id)+ ->assertDispatched('success', 'DNS record replaced for app.example.com.');++ Http::assertSent(fn ($request) => $request->method() === 'PUT'+ && str_ends_with($request->url(), '/dns_records/record-1')+ && $request->data()['content'] === '203.0.113.10');+ expect(ManagedDnsRecord::query()->where('name', 'app.example.com')->where('content', '203.0.113.10')->exists())->toBeTrue();+});++test('replacing a managed dns record ignores a tampered conflict record id', function () {+ ['application' => $application, 'zone' => $zone] = prepareManagedDnsApplication();++ Http::fake([+ 'https://api.cloudflare.com/client/v4/zones/zone-1/dns_records?*' => Http::response([+ 'success' => true,+ 'result' => [['id' => 'record-1', 'type' => 'A', 'name' => 'app.example.com', 'content' => '198.51.100.50']],+ ]),+ 'https://api.cloudflare.com/client/v4/zones/zone-1/dns_records/*' => Http::response([+ 'success' => true, 'result' => ['id' => 'record-other'],+ ]),+ ]);++ Livewire::test(Domains::class, ['application' => $application->fresh()])+ ->set('dnsProviderConflicts', [+ 'app.example.com|'.$zone->id => [+ 'record_id' => 'record-other',+ 'current' => '198.51.100.50',+ 'proposed' => '198.51.100.1',+ ],+ ])+ ->call('replaceManagedDnsRecord', 'app.example.com', $zone->id)+ ->assertDispatched('error', 'The DNS conflict is no longer available. Check the record again.')+ ->assertSet('dnsProviderConflicts', []);++ Http::assertNotSent(fn ($request) => $request->method() === 'PUT');+ expect(ManagedDnsRecord::query()->where('name', 'app.example.com')->exists())->toBeFalse();+});++/**+ * @return array{application: Application, zone: DnsProviderZone}+ */+function prepareManagedDnsApplication(): array+{+ test()->withoutVite();+ config(['app.maintenance.driver' => 'file']);+ InstanceSettings::unguarded(fn () => InstanceSettings::updateOrCreate(+ ['id' => 0],+ ['id' => 0, 'is_dns_validation_enabled' => false],+ ));++ $team = Team::factory()->create();+ $user = User::factory()->create();+ $team->members()->attach($user->id, ['role' => 'owner']);+ test()->actingAs($user);+ session(['currentTeam' => $team]);++ $server = Server::factory()->create(['team_id' => $team->id, 'ip' => '203.0.113.10']);+ $server->settings()->update(['is_reachable' => true, 'is_usable' => true]);+ $destination = StandaloneDocker::withoutEvents(fn () => StandaloneDocker::firstOrCreate(+ ['server_id' => $server->id, 'network' => 'coolify'],+ ['uuid' => (string) Str::uuid(), 'name' => 'test-docker'],+ ));+ $project = Project::factory()->create(['team_id' => $team->id]);+ $environment = Environment::factory()->create(['project_id' => $project->id]);++ $application = Application::factory()->create([+ 'environment_id' => $environment->id,+ 'destination_id' => $destination->id,+ 'destination_type' => $destination->getMorphClass(),+ 'fqdn' => 'https://app.example.com',+ 'build_pack' => 'nixpacks',+ ]);+ $application->settings()->update(['is_container_label_readonly_enabled' => true]);++ $token = IntegrationToken::factory()->for($team)->create(['provider' => 'cloudflare', 'token' => 'secret']);+ $zone = DnsProviderZone::factory()->for($token)->create(['provider_zone_id' => 'zone-1', 'name' => 'example.com']);++ return ['application' => $application, 'zone' => $zone];+}diff --git a/tests/Feature/MutableLivewireComponentsAuthorizationTest.php b/tests/Feature/MutableLivewireComponentsAuthorizationTest.phpindex 0e7bc1d0c7..510e8462aa 100644--- a/tests/Feature/MutableLivewireComponentsAuthorizationTest.php+++ b/tests/Feature/MutableLivewireComponentsAuthorizationTest.php@@ -19,6 +19,19 @@ it('auto-disables listboxes when the gate denies access', function () {expect($html)->toMatch('/<button[^>]*id="status-trigger"[^>]*\sdisabled(?:[=\s>])/');});+it('auto-disables checkboxes when the gate denies access', function () {+ Gate::define('update-checkbox-test', fn (): bool => false);++ $html = Blade::render(<<<'BLADE'+ <x-forms.checkbox id="replaceExisting" label="Replace objects that already exist"+ canGate="update-checkbox-test" :canResource="new stdClass" />+ BLADE);++ expect($html)+ ->toMatch('/<input[^>]*type="checkbox"[^>]*\sdisabled(?:[=\s>])/')+ ->not->toContain('canGate');+});+it('declares gate attributes on form controls with update permission checks', function () {$controlPattern = '/<x-forms\.(?:listbox|input|select|checkbox|textarea|button|toggle)\b.*?(?:\/>|<\/x-forms\.[^>]+>)/s';@@ -69,6 +82,19 @@ it('declares deploy authorization on the service container removal confirmation');});+it('declares update authorization on application and service domain removal confirmations', function () {+ $applicationRow = file_get_contents(resource_path('views/livewire/project/application/partials/domain-row.blade.php'));+ $serviceTable = file_get_contents(resource_path('views/livewire/project/service/partials/domain-table.blade.php'));++ expect($applicationRow)->toMatch(+ '/<x-modal-confirmation(?=[^>]*title="Remove domain\?")(?=[^>]*canGate="update")(?=[^>]*:canResource="\$application")[^>]*>/'+ );++ expect($serviceTable)->toMatch(+ '/<x-modal-confirmation(?=[^>]*title="Remove domain\?")(?=[^>]*canGate="update")(?=[^>]*:canResource="\$service")[^>]*>/'+ );+});+it('declares update authorization on service backup mutation controls', function () {$importBackupView = file_get_contents(resource_path('views/livewire/project/service/import-backup.blade.php'));$volumeBackupView = file_get_contents(resource_path('views/livewire/project/service/volume-backup/index.blade.php'));diff --git a/tests/Feature/Security/IntegrationTokenFormTest.php b/tests/Feature/Security/IntegrationTokenFormTest.phpindex 8aa6346e0d..ac43e9077c 100644--- a/tests/Feature/Security/IntegrationTokenFormTest.php+++ b/tests/Feature/Security/IntegrationTokenFormTest.php@@ -336,3 +336,15 @@ test('editor updates its row without rerendering the teleported parent modal', f->toContain("'integration-token-deleted'")->not->toContain('integrationTokenChanged');});++test('new integration token form controls declare authorization matching server-side actions', function () {+ $editor = file_get_contents(resource_path('views/livewire/security/integration-token-editor.blade.php'));+ $form = file_get_contents(resource_path('views/livewire/security/integration-token-form.blade.php'));++ expect($editor)+ ->toMatch('/<x-forms\.checkbox(?=[^>]*id="edit-automatic-dns")(?=[^>]*canGate="update")(?=[^>]*:canResource="\$integrationToken")[^>]*>/')+ ->toMatch('/<x-forms\.button(?=[^>]*wire:click="refreshZones")(?=[^>]*canGate="update")(?=[^>]*:canResource="\$integrationToken")[^>]*>/');++ expect($form)+ ->toMatch('/<x-forms\.checkbox(?=[^>]*id="automatic-dns")(?=[^>]*canGate="create")(?=[^>]*:canResource="\\\\App\\\\Models\\\\IntegrationToken::class")[^>]*>/');+});diff --git a/tests/Feature/ServiceDomainsTest.php b/tests/Feature/ServiceDomainsTest.phpindex da6701656f..5cba3ab241 100644--- a/tests/Feature/ServiceDomainsTest.php+++ b/tests/Feature/ServiceDomainsTest.php@@ -2,8 +2,11 @@use App\Jobs\CheckDomainDnsJob;use App\Livewire\Project\Service\Domains;+use App\Models\DnsProviderZone;use App\Models\Environment;use App\Models\InstanceSettings;+use App\Models\IntegrationToken;+use App\Models\ManagedDnsRecord;use App\Models\Project;use App\Models\Server;use App\Models\Service;@@ -13,6 +16,7 @@ use App\Models\Team;use App\Models\User;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Queue;use Illuminate\Support\Str;use Livewire\Livewire;@@ -176,6 +180,75 @@ it('removes consecutive service domains by stable row identity after indexes chaexpect($this->apiApp->fresh()->fqdn)->toBe('https://third.example.com');});+it('deletes the managed dns record when removing a service domain by key with deleteManagedDns', function () {+ $token = IntegrationToken::factory()->for($this->team)->create([+ 'provider' => 'cloudflare',+ 'token' => 'secret',+ ]);+ $zone = DnsProviderZone::factory()->for($token)->create([+ 'provider_zone_id' => 'zone-1',+ 'name' => 'example.com',+ ]);+ $record = ManagedDnsRecord::factory()->create([+ 'team_id' => $this->team->id,+ 'integration_token_id' => $token->id,+ 'dns_provider_zone_id' => $zone->id,+ 'resource_type' => $this->apiApp->getMorphClass(),+ 'resource_id' => $this->apiApp->getKey(),+ 'provider_record_id' => 'record-1',+ 'type' => 'A',+ 'name' => 'api.example.com',+ 'content' => '203.0.113.10',+ ]);++ Http::fake(['https://api.cloudflare.com/client/v4/zones/zone-1/dns_records/record-1' => Http::sequence()+ ->push(['success' => true, 'result' => [+ 'id' => 'record-1',+ 'type' => 'A',+ 'name' => 'api.example.com',+ 'content' => '203.0.113.10',+ ]])+ ->push(['success' => true, 'result' => ['id' => 'record-1']])]);++ $domainKey = hash('sha256', 'https://api.example.com|'.$this->apiApp->id);++ Livewire::test(Domains::class, ['service' => $this->service->fresh(['applications', 'server'])])+ ->call('removeDomainByKey', $domainKey, '', ['deleteManagedDns'])+ ->assertDispatched('success');++ expect($this->apiApp->fresh()->fqdn)->toBeNull()+ ->and(ManagedDnsRecord::query()->find($record->id))->toBeNull();+});++it('leaves the managed dns record when removing a service domain by key without deleteManagedDns', function () {+ $token = IntegrationToken::factory()->for($this->team)->create([+ 'provider' => 'cloudflare',+ 'token' => 'secret',+ ]);+ $zone = DnsProviderZone::factory()->for($token)->create([+ 'provider_zone_id' => 'zone-1',+ 'name' => 'example.com',+ ]);+ $record = ManagedDnsRecord::factory()->create([+ 'team_id' => $this->team->id,+ 'integration_token_id' => $token->id,+ 'dns_provider_zone_id' => $zone->id,+ 'provider_record_id' => 'record-1',+ 'type' => 'A',+ 'name' => 'api.example.com',+ 'content' => '203.0.113.10',+ ]);++ $domainKey = hash('sha256', 'https://api.example.com|'.$this->apiApp->id);++ Livewire::test(Domains::class, ['service' => $this->service->fresh(['applications', 'server'])])+ ->call('removeDomainByKey', $domainKey, '')+ ->assertDispatched('success');++ expect($this->apiApp->fresh()->fqdn)->toBeNull()+ ->and(ManagedDnsRecord::query()->find($record->id))->not->toBeNull();+});+it('shows and persists the HTTP redirect control for HTTPS service applications', function () {Livewire::test(Domains::class, ['service' => $this->service->fresh(['applications', 'server'])])->assertSee('Redirect HTTP to HTTPS')diff --git a/tests/Unit/DatabaseImport/CleanupDatabaseImportTest.php b/tests/Unit/DatabaseImport/CleanupDatabaseImportTest.phpnew file mode 100644index 0000000000..f48177d53e--- /dev/null+++ b/tests/Unit/DatabaseImport/CleanupDatabaseImportTest.php@@ -0,0 +1,100 @@+<?php++use App\Events\DatabaseImportFinished;+use App\Listeners\CleanupDatabaseImport;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\Event;+use Tests\TestCase;++uses(TestCase::class, RefreshDatabase::class);++function importCleanupPayload(array $overrides = []): array+{+ return array_merge([+ 'container' => 'postgres-abc',+ 'containerTmpPath' => '/tmp/restore_op',+ 'scriptPath' => '/tmp/restore_op.sh',+ 'serverId' => 1,+ ], $overrides);+}++test('the finished event keeps the payload and does not import Server', function () {+ $data = importCleanupPayload(['serverTmpPath' => '/tmp/database-import-op']);+ $event = new DatabaseImportFinished($data);++ expect($event->data)->toBe($data)+ ->and(file_get_contents(app_path('Events/DatabaseImportFinished.php')))+ ->not->toContain('instant_remote_process')+ ->not->toContain('use App\Models\Server');+});++test('the cleanup listener is queued and discovered', function () {+ expect(class_implements(CleanupDatabaseImport::class))->toContain(ShouldQueue::class);++ $listener = new CleanupDatabaseImport;+ expect($listener->tries)->toBe(3)+ ->and($listener->backoff)->toBe([5, 15, 30]);++ Event::fake();+ Event::assertListening(DatabaseImportFinished::class, CleanupDatabaseImport::class);+});++test('builds S3, upload, and server-path cleanup commands', function () {+ $listener = new CleanupDatabaseImport;++ expect($listener->commands(importCleanupPayload([+ 'containerName' => 's3-restore-op',+ 'serverTmpPath' => '/tmp/s3-restore-op',+ ])))->toBe([+ 'docker rm -f '.escapeshellarg('s3-restore-op').' 2>/dev/null || true',+ 'rm -f '.escapeshellarg('/tmp/s3-restore-op').' 2>/dev/null || true',+ 'docker exec '.escapeshellarg('postgres-abc').' rm -f '.escapeshellarg('/tmp/restore_op').' 2>/dev/null || true',+ 'docker exec '.escapeshellarg('postgres-abc').' rm -f '.escapeshellarg('/tmp/restore_op.sh').' 2>/dev/null || true',+ ]);++ expect($listener->commands(importCleanupPayload([+ 'serverTmpPath' => '/tmp/database-import-op',+ ])))->toBe([+ 'rm -f '.escapeshellarg('/tmp/database-import-op').' 2>/dev/null || true',+ 'docker exec '.escapeshellarg('postgres-abc').' rm -f '.escapeshellarg('/tmp/restore_op').' 2>/dev/null || true',+ 'docker exec '.escapeshellarg('postgres-abc').' rm -f '.escapeshellarg('/tmp/restore_op.sh').' 2>/dev/null || true',+ ]);++ expect($listener->commands(importCleanupPayload()))->toBe([+ 'docker exec '.escapeshellarg('postgres-abc').' rm -f '.escapeshellarg('/tmp/restore_op').' 2>/dev/null || true',+ 'docker exec '.escapeshellarg('postgres-abc').' rm -f '.escapeshellarg('/tmp/restore_op.sh').' 2>/dev/null || true',+ ]);+});++test('omits unsafe paths, missing container execs, and empty payloads', function () {+ $listener = new CleanupDatabaseImport;++ expect($listener->commands(importCleanupPayload([+ 'containerName' => 's3-restore-op',+ 'serverTmpPath' => '/tmp/../etc/passwd',+ 'containerTmpPath' => '/etc/shadow',+ 'scriptPath' => '/tmp/../../etc/shadow',+ ])))->toBe([+ 'docker rm -f '.escapeshellarg('s3-restore-op').' 2>/dev/null || true',+ ]);++ expect($listener->commands([+ 'serverTmpPath' => '/tmp/database-import-op',+ 'containerTmpPath' => '/tmp/restore_op',+ 'scriptPath' => '/tmp/restore_op.sh',+ ]))->toBe([+ 'rm -f '.escapeshellarg('/tmp/database-import-op').' 2>/dev/null || true',+ ]);++ expect($listener->commands([]))->toBe([]);+});++test('handle skips remote process when the server is missing', function () {+ $event = new DatabaseImportFinished(importCleanupPayload([+ 'serverId' => 999999,+ 'containerName' => 's3-restore-op',+ ]));++ expect(fn () => (new CleanupDatabaseImport)->handle($event))->not->toThrow(Throwable::class);+});diff --git a/tests/Unit/DatabaseImport/DatabaseImportCommandBuilderTest.php b/tests/Unit/DatabaseImport/DatabaseImportCommandBuilderTest.phpindex 77d882895b..87b37b6668 100644--- a/tests/Unit/DatabaseImport/DatabaseImportCommandBuilderTest.php+++ b/tests/Unit/DatabaseImport/DatabaseImportCommandBuilderTest.php@@ -55,12 +55,28 @@ test('builds dump-all commands and postgres safety scan', function () {$builder = new DatabaseImportCommandBuilder;$postgres = importResource(StandalonePostgresql::class);+ $safety = $builder->buildPostgresSafetyCommand($postgres, 'postgres-safe', '/tmp/dump.sql.gz');+ $script = $builder->buildPostgresRestoreScanScript($postgres, '/tmp/dump.sql.gz');+expect($builder->buildRestoreCommand($postgres, '/tmp/dump.sql.gz', true))->toContain('pg_terminate_backend')->toContain("gunzip -cf '/tmp/dump.sql.gz'")- ->and($builder->buildPostgresSafetyCommand($postgres, 'postgres-safe', '/tmp/dump.sql.gz'))+ ->and($safety)->toContain('COPY ... PROGRAM')- ->toContain('docker exec postgres-safe');+ ->toContain('docker exec postgres-safe')+ ->toContain('pg_restore -l')+ ->toContain('pg_restore -f -')+ ->toContain('unable to inspect custom archive')+ ->not->toContain('then exit 0')+ ->and($script)+ ->toContain("tr '\\n\\r\\t'");+});++test('postgres safety command is null for non-postgres databases', function () {+ $builder = new DatabaseImportCommandBuilder;++ expect($builder->buildPostgresSafetyCommand(importResource(StandaloneMysql::class), 'mysql-test', '/tmp/restore_test'))+ ->toBeNull();});test('dump-all mysql and mariadb commands use valid shell parameter expansions', function (string $class, string $binary, string $prefix) {diff --git a/tests/Unit/DatabaseImportOpenApiTest.php b/tests/Unit/DatabaseImportOpenApiTest.phpindex d8276f8ca0..94aa6f81d7 100644--- a/tests/Unit/DatabaseImportOpenApiTest.php+++ b/tests/Unit/DatabaseImportOpenApiTest.php@@ -1,7 +1,7 @@<?phptest('documents standalone and service database import endpoints', function () {- $document = json_decode(file_get_contents(__DIR__.'/../../openapi.json'), true, flags: JSON_THROW_ON_ERROR);+ $document = json_decode((string) file_get_contents(__DIR__.'/../../openapi.json'), true, flags: JSON_THROW_ON_ERROR);expect($document['paths'])->toHaveKey('/databases/{uuid}/imports/uploads')@@ -15,4 +15,68 @@ test('documents standalone and service database import endpoints', function () {expect($source['properties']['replace_existing'])->toMatchArray(['type' => 'boolean', 'default' => false]);}++ $statusRef = [+ 'description' => 'Import status',+ 'content' => [+ 'application/json' => [+ 'schema' => [+ '$ref' => '#/components/schemas/DatabaseImportStatus',+ ],+ ],+ ],+ ];++ expect($document['paths']['/databases/{uuid}/imports/{activity_id}']['get']['responses']['200'])+ ->toMatchArray($statusRef)+ ->and($document['paths']['/services/{uuid}/databases/{database_uuid}/imports/{activity_id}']['get']['responses']['200'])+ ->toMatchArray($statusRef)+ ->and($document['components']['schemas'])+ ->toHaveKey('DatabaseImportStatus');+});++test('documents path parameters for database import endpoints', function () {+ $document = json_decode((string) file_get_contents(__DIR__.'/../../openapi.json'), true, flags: JSON_THROW_ON_ERROR);++ $operations = [+ ['/databases/{uuid}/imports/uploads', 'post', ['uuid']],+ ['/databases/{uuid}/imports', 'post', ['uuid']],+ ['/databases/{uuid}/imports/{activity_id}', 'get', ['uuid', 'activity_id']],+ ['/services/{uuid}/databases/{database_uuid}/imports/uploads', 'post', ['uuid', 'database_uuid']],+ ['/services/{uuid}/databases/{database_uuid}/imports', 'post', ['uuid', 'database_uuid']],+ ['/services/{uuid}/databases/{database_uuid}/imports/{activity_id}', 'get', ['uuid', 'database_uuid', 'activity_id']],+ ];++ foreach ($operations as [$path, $method, $expectedNames]) {+ $parameters = $document['paths'][$path][$method]['parameters'] ?? [];+ $pathParameters = collect($parameters)+ ->filter(fn (array $parameter): bool => ($parameter['in'] ?? null) === 'path')+ ->map(fn (array $parameter): string => $parameter['name'])+ ->values()+ ->all();++ expect($pathParameters)->toEqual($expectedNames);+ }+});++test('constrains additional properties on each database import source branch', function () {+ $document = json_decode((string) file_get_contents(__DIR__.'/../../openapi.json'), true, flags: JSON_THROW_ON_ERROR);+ $schema = $document['components']['schemas']['DatabaseImportRequest'];++ expect($schema)->not->toHaveKey('additionalProperties');++ $expectedProperties = [+ ['source', 'upload_id', 'dump_all', 'replace_existing'],+ ['source', 's3_storage_uuid', 'path', 'dump_all', 'replace_existing'],+ ['source', 'path', 'dump_all', 'replace_existing'],+ ];++ expect($schema['oneOf'])->toHaveCount(count($expectedProperties));++ foreach ($schema['oneOf'] as $index => $source) {+ expect($source['additionalProperties'])->toBeFalse()+ ->and($source['properties'])->toHaveKeys($expectedProperties[$index])+ ->and($source['properties']['replace_existing'])+ ->toMatchArray(['type' => 'boolean', 'default' => false]);+ }});