Skip to content

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.

fix(server-transfer): keep imported data exact and guard archived servers

Andras Bacsaic454f845455a
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 339fc7e60d..885025a087 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1,5 +1,9 @@
# Lessons
+## Keep imported data exact
+- The global `TrimStrings` and `ConvertEmptyStringsToNull` middleware change every string of a JSON request. An endpoint that receives stored records (for example the server transfer import) must skip them with `skipWhen()`; otherwise text loses its edge whitespace and an empty value becomes null.
+- Code that creates models from stored data with model events on also runs their `created` hooks and set-mutators (default destinations, settings, variables, parser versions, ports). Compare the result with the source record by record, and restore or remove what the hooks changed.
+
## Prove regressions before changing code
- Reproduce the reported failure on the unchanged baseline before adding a fix.
- When a symptom matches an earlier fix, inspect that fix and prove why it no longer works before adding another workaround.
diff --git a/app/Actions/Server/DeleteServer.php b/app/Actions/Server/DeleteServer.php
index bcffee2a50..92e66e6dfc 100644
--- a/app/Actions/Server/DeleteServer.php
+++ b/app/Actions/Server/DeleteServer.php
@@ -19,6 +19,10 @@ class DeleteServer
public function handle(int $serverId, bool $deleteFromHetzner = false, ?int $hetznerServerId = null, ?int $cloudProviderTokenId = null, ?int $teamId = null, bool $deleteFromVultr = false, ?string $vultrInstanceId = null, bool $deleteFromDigitalOcean = false, ?int $digitalOceanDropletId = null, bool $deleteFromHostinger = false, ?int $hostingerVirtualMachineId = null)
{
$server = Server::withTrashed()->find($serverId);
+ // Another Coolify instance manages the cloud server of a transferred server.
+ if ($server?->isTransferredAway()) {
+ $deleteFromHetzner = $deleteFromVultr = $deleteFromDigitalOcean = $deleteFromHostinger = false;
+ }
// Delete from Hetzner even if server is already gone from Coolify
if ($deleteFromHetzner && ($hetznerServerId || ($server && $server->hetzner_server_id))) {
diff --git a/app/Actions/Server/RebootServer.php b/app/Actions/Server/RebootServer.php
index 0ca6a25f6b..d2022012ee 100644
--- a/app/Actions/Server/RebootServer.php
+++ b/app/Actions/Server/RebootServer.php
@@ -20,9 +20,7 @@ SH;
public function handle(Server $server): void
{
- if ($server->isTransferredAway()) {
- throw new \RuntimeException('This server is managed by another Coolify instance.');
- }
+ $server->assertNotTransferredAway();
if (! $server->isFunctional()) {
throw new \RuntimeException('Server is not reachable or not ready.');
}
diff --git a/app/Helpers/SshMultiplexingHelper.php b/app/Helpers/SshMultiplexingHelper.php
index f29d97058e..2138c5d131 100644
--- a/app/Helpers/SshMultiplexingHelper.php
+++ b/app/Helpers/SshMultiplexingHelper.php
@@ -64,8 +64,19 @@ class SshMultiplexingHelper
}
}
+ /**
+ * A disabled server, such as the archive of a transferred server, gets no SSH or scp connection.
+ */
+ private static function assertNotDisabled(Server $server): void
+ {
+ if ($server->settings->force_disabled) {
+ throw new \RuntimeException('Server is disabled.');
+ }
+ }
+
public static function establishNewMultiplexedConnection(Server $server): bool
{
+ self::assertNotDisabled($server);
$sshConfig = self::serverSshConfiguration($server);
$sshKeyLocation = $sshConfig['sshKeyLocation'];
$muxSocket = $sshConfig['muxFilename'];
@@ -133,6 +144,7 @@ class SshMultiplexingHelper
public static function generateScpCommand(Server $server, string $source, string $dest): string
{
+ self::assertNotDisabled($server);
$sshConfig = self::serverSshConfiguration($server);
$sshKeyLocation = $sshConfig['sshKeyLocation'];
$scpCommand = 'timeout '.config('constants.ssh.command_timeout').' scp ';
@@ -173,6 +185,7 @@ class SshMultiplexingHelper
*/
public static function generateScpDownloadCommand(Server $server, string $remoteSource, string $localDest): string
{
+ self::assertNotDisabled($server);
$sshConfig = self::serverSshConfiguration($server);
$sshKeyLocation = $sshConfig['sshKeyLocation'];
$scpCommand = 'timeout '.config('constants.ssh.command_timeout').' scp ';
@@ -234,9 +247,7 @@ class SshMultiplexingHelper
private static function sshCommandPrefix(Server $server, bool $disableMultiplexing, ?int $commandTimeout): string
{
- if ($server->settings->force_disabled) {
- throw new \RuntimeException('Server is disabled.');
- }
+ self::assertNotDisabled($server);
$sshConfig = self::serverSshConfiguration($server);
$sshKeyLocation = $sshConfig['sshKeyLocation'];
diff --git a/app/Http/Controllers/Api/ServersController.php b/app/Http/Controllers/Api/ServersController.php
index fec376109b..6e1cc58c06 100644
--- a/app/Http/Controllers/Api/ServersController.php
+++ b/app/Http/Controllers/Api/ServersController.php
@@ -18,6 +18,7 @@ use App\Models\Project;
use App\Models\Server as ModelsServer;
use App\Models\Team;
use App\Rules\ValidServerIp;
+use App\Services\ServerTransfer\ServerTransferClaimer;
use App\Support\ValidationPatterns;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -967,6 +968,17 @@ class ServersController extends Controller
if (is_null($deleteFromProvider)) {
return response()->json(['message' => 'delete_from_provider must be a boolean.'], 422);
}
+ // Another Coolify instance manages a transferred server. This instance deletes only its own records:
+ // never the cloud server, the containers, or the DNS records that the other instance uses.
+ if ($server->isTransferredAway()) {
+ if ($deleteFromProvider) {
+ return response()->json(['message' => 'This server is managed by another Coolify instance. Delete its cloud server from that instance.'], 422);
+ }
+ app(ServerTransferClaimer::class)->deleteArchive($server);
+ auditLog('api.server.deleted', ['team_id' => $teamId, 'server_uuid' => $server->uuid, 'server_name' => $server->name, 'ip' => $server->ip, 'archive' => true]);
+
+ return response()->json(['message' => 'Server deleted.']);
+ }
if ($server->definedResources()->count() > 0 && ! $force) {
return response()->json(['message' => 'Server has resources. Use ?force=true to delete all resources and the server, or delete resources manually first.'], 400);
diff --git a/app/Jobs/CheckMissingDatabaseBackupsJob.php b/app/Jobs/CheckMissingDatabaseBackupsJob.php
index ca91156574..ae517c4591 100644
--- a/app/Jobs/CheckMissingDatabaseBackupsJob.php
+++ b/app/Jobs/CheckMissingDatabaseBackupsJob.php
@@ -58,6 +58,11 @@ class CheckMissingDatabaseBackupsJob implements ShouldBeEncrypted, ShouldBeUniqu
return;
}
+ // Another Coolify instance backs up the databases of a transferred server.
+ if ($backup->server()?->isTransferredAway()) {
+ return;
+ }
+
// Send once for each period without backup activity.
NotificationThrottle::sendOnce(
$backup,
diff --git a/app/Jobs/CheckMissingVolumeBackupsJob.php b/app/Jobs/CheckMissingVolumeBackupsJob.php
index 1f8ab30b4f..3c6dccfbf5 100644
--- a/app/Jobs/CheckMissingVolumeBackupsJob.php
+++ b/app/Jobs/CheckMissingVolumeBackupsJob.php
@@ -58,6 +58,11 @@ class CheckMissingVolumeBackupsJob implements ShouldBeEncrypted, ShouldBeUnique,
return;
}
+ // Another Coolify instance backs up the volumes of a transferred server.
+ if ($backup->server()?->isTransferredAway()) {
+ return;
+ }
+
// Send once for each period without backup activity.
NotificationThrottle::sendOnce(
$backup,
diff --git a/app/Jobs/ServerManagerJob.php b/app/Jobs/ServerManagerJob.php
index e1ab5f94ee..815bb09361 100644
--- a/app/Jobs/ServerManagerJob.php
+++ b/app/Jobs/ServerManagerJob.php
@@ -102,7 +102,7 @@ class ServerManagerJob implements ShouldBeEncrypted, ShouldQueue
|| $server->digitalocean_droplet_id
|| $server->hostinger_virtual_machine_id;
- if ($hasCloudResource && $server->cloudProviderToken) {
+ if ($hasCloudResource && $server->cloudProviderToken && ! $server->isTransferredAway()) {
ServerCloudProviderStatusCheckJob::dispatch($server);
}
});
diff --git a/app/Livewire/Server/CloudflareTunnel.php b/app/Livewire/Server/CloudflareTunnel.php
index 31bca417f6..b40b6b5628 100644
--- a/app/Livewire/Server/CloudflareTunnel.php
+++ b/app/Livewire/Server/CloudflareTunnel.php
@@ -88,6 +88,7 @@ class CloudflareTunnel extends Component
{
try {
$this->authorize('update', $this->server);
+ $this->server->assertNotTransferredAway();
if (filled($this->server->settings->cloudflare_tunnel_id)) {
foreach ($tunnels->tearDown($this->server) as $warning) {
$this->dispatch('warning', $warning);
diff --git a/app/Livewire/Server/Show.php b/app/Livewire/Server/Show.php
index ff5751ed2a..23363cd9d7 100644
--- a/app/Livewire/Server/Show.php
+++ b/app/Livewire/Server/Show.php
@@ -738,6 +738,7 @@ class Show extends Component
{
try {
$this->authorize('update', $this->server);
+ $this->server->assertNotTransferredAway();
if (! $this->server->hetzner_server_id || ! $this->server->cloudProviderToken) {
$this->dispatch('error', 'This server is not associated with a Hetzner Cloud server or token.');
@@ -760,6 +761,7 @@ class Show extends Component
{
try {
$this->authorize('update', $this->server);
+ $this->server->assertNotTransferredAway();
if (! $this->server->vultr_instance_id || ! $this->server->cloudProviderToken) {
$this->dispatch('error', 'This server is not associated with a Vultr instance or token.');
@@ -782,6 +784,7 @@ class Show extends Component
{
try {
$this->authorize('update', $this->server);
+ $this->server->assertNotTransferredAway();
if (! $this->server->digitalocean_droplet_id || ! $this->server->cloudProviderToken) {
$this->dispatch('error', 'This server is not associated with a DigitalOcean droplet or token.');
@@ -804,6 +807,7 @@ class Show extends Component
{
try {
$this->authorize('update', $this->server);
+ $this->server->assertNotTransferredAway();
if (! $this->server->hostinger_virtual_machine_id || ! $this->server->cloudProviderToken) {
$this->dispatch('error', 'This server is not associated with a Hostinger VPS or token.');
diff --git a/app/Models/Server.php b/app/Models/Server.php
index 178b180d22..ede3c00b8a 100644
--- a/app/Models/Server.php
+++ b/app/Models/Server.php
@@ -1386,6 +1386,19 @@ $siteAddress {
return data_get($this->server_metadata, 'transfer.status') === 'transferred';
}
+ /**
+ * Stops an action that changes the host, its cloud server, its Cloudflare tunnel, or its DNS records.
+ * Another Coolify instance manages a transferred server; this instance keeps only an archive of it.
+ *
+ * @throws \RuntimeException
+ */
+ public function assertNotTransferredAway(): void
+ {
+ if ($this->isTransferredAway()) {
+ throw new \RuntimeException('This server is managed by another Coolify instance.');
+ }
+ }
+
/**
* Whether this server may be validated / installed against from this instance.
*/
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index fb6d3ed150..8130a5400d 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -12,6 +12,9 @@ use App\Support\AtomicFilesystem;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Console\ConfigCacheCommand;
use Illuminate\Foundation\Console\RouteCacheCommand;
+use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
+use Illuminate\Foundation\Http\Middleware\TrimStrings;
+use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
@@ -44,6 +47,18 @@ class AppServiceProvider extends ServiceProvider
$this->configureGitLabHttp();
$this->configureOidcSocialite();
$this->configureQueue();
+ $this->configureServerTransferImport();
+ }
+
+ /**
+ * A server transfer bundle carries stored values (files, variables, keys, compose files) that must
+ * arrive unchanged, so the import request skips the global trimming and empty-string conversion.
+ */
+ private function configureServerTransferImport(): void
+ {
+ $isImport = fn (Request $request): bool => $request->is('api/v1/servers/import');
+ TrimStrings::skipWhen($isImport);
+ ConvertEmptyStringsToNull::skipWhen($isImport);
}
/**
diff --git a/app/Services/CloudflareTunnelService.php b/app/Services/CloudflareTunnelService.php
index 358b4075d4..09c2ab72bf 100644
--- a/app/Services/CloudflareTunnelService.php
+++ b/app/Services/CloudflareTunnelService.php
@@ -55,6 +55,7 @@ class CloudflareTunnelService
*/
public function setUp(Server $server, IntegrationToken $token, string $hostname, ?array $confirmedConflict = null): Activity
{
+ $server->assertNotTransferredAway();
$zone = $this->zoneFor($server, $token, $hostname);
$accountId = $zone->account_id;
if (blank($accountId)) {
@@ -109,6 +110,10 @@ class CloudflareTunnelService
if (blank($settings->cloudflare_tunnel_id)) {
return [];
}
+ // Another Coolify instance uses the tunnel of a transferred server.
+ if ($server->isTransferredAway()) {
+ return ['This server is managed by another Coolify instance.'];
+ }
$warnings = [];
$name = self::tunnelName($server);
diff --git a/app/Services/Dns/CloudflareDnsProvider.php b/app/Services/Dns/CloudflareDnsProvider.php
index 9cd21a4fbf..9c7748ff8b 100644
--- a/app/Services/Dns/CloudflareDnsProvider.php
+++ b/app/Services/Dns/CloudflareDnsProvider.php
@@ -4,9 +4,13 @@ namespace App\Services\Dns;
use App\Enums\ManagedDnsDeletionResult;
use App\Exceptions\DnsRecordConflictException;
+use App\Models\Application;
+use App\Models\ApplicationPreview;
use App\Models\DnsProviderZone;
use App\Models\IntegrationToken;
use App\Models\ManagedDnsRecord;
+use App\Models\Server;
+use App\Models\ServiceApplication;
use App\Support\DnsRecordHints;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Database\Eloquent\Model;
@@ -141,6 +145,7 @@ class CloudflareDnsProvider
*/
public function createRecord(DnsProviderZone $zone, string $hostname, string $content, ?Model $resource = null, array $additionalResources = [], ?bool $proxied = null): ManagedDnsRecord
{
+ $this->assertResourcesManagedHere([$resource, ...$additionalResources]);
$hostname = strtolower(rtrim($hostname, '.'));
return $this->hostnameLock->run(
@@ -224,6 +229,7 @@ class CloudflareDnsProvider
array $additionalResources = [],
bool $proxied = false,
): ManagedDnsRecord {
+ $this->assertResourcesManagedHere([$resource, ...$additionalResources]);
$hostname = strtolower(rtrim($hostname, '.'));
return $this->hostnameLock->run(
@@ -291,6 +297,27 @@ class CloudflareDnsProvider
* Deletes the provider record only when Coolify created it and it still carries Coolify's ownership comment and value.
* Removes the local row when the provider record is gone.
*/
+ /**
+ * Another Coolify instance manages the DNS records of the resources of a transferred server.
+ *
+ * @param array<int, Model|null> $resources
+ *
+ * @throws RuntimeException
+ */
+ private function assertResourcesManagedHere(array $resources): void
+ {
+ foreach ($resources as $resource) {
+ $server = match (true) {
+ $resource instanceof Server => $resource,
+ $resource instanceof Application => $resource->destination?->server,
+ $resource instanceof ApplicationPreview => $resource->application?->destination?->server,
+ $resource instanceof ServiceApplication => $resource->service?->server,
+ default => null,
+ };
+ $server?->assertNotTransferredAway();
+ }
+ }
+
public function deleteRecord(ManagedDnsRecord $record, ?Model $resource = null): ManagedDnsDeletionResult
{
if (! $record->owned) {
diff --git a/app/Services/ServerTransfer/ServerTransferClaimer.php b/app/Services/ServerTransfer/ServerTransferClaimer.php
index f479b1fb49..a2eca37bf6 100644
--- a/app/Services/ServerTransfer/ServerTransferClaimer.php
+++ b/app/Services/ServerTransfer/ServerTransferClaimer.php
@@ -187,7 +187,9 @@ class ServerTransferClaimer
*/
private function dnsResources(Server $server): Collection
{
- return $server->applications()
+ // The server itself owns the DNS record of its Cloudflare tunnel.
+ return collect([$server])
+ ->concat($server->applications())
->concat($server->services()->with('applications')->get()->flatMap->applications);
}
diff --git a/app/Services/ServerTransfer/ServerTransferExporter.php b/app/Services/ServerTransfer/ServerTransferExporter.php
index 4b1255f6e5..8b45a1fbdc 100644
--- a/app/Services/ServerTransfer/ServerTransferExporter.php
+++ b/app/Services/ServerTransfer/ServerTransferExporter.php
@@ -449,7 +449,8 @@ class ServerTransferExporter
private function collectManagedDnsRecords(Server $server, Collection $applications, Collection $services): array
{
// Keyed by "morph type:id". Soft-deleted previews are covered, but their references are not exported.
- $resourceKeys = [];
+ // The server itself owns the DNS record of its Cloudflare tunnel.
+ $resourceKeys = [$server->getMorphClass().':'.$server->id => ['kind' => 'server', 'uuid' => $server->uuid]];
foreach ($applications as $application) {
$resourceKeys[$application->getMorphClass().':'.$application->id] = ['kind' => 'application', 'uuid' => $application->uuid];
foreach (ApplicationPreview::withTrashed()->where('application_id', $application->id)->get() as $preview) {
@@ -461,10 +462,6 @@ class ServerTransferExporter
$resourceKeys[$serviceApplication->getMorphClass().':'.$serviceApplication->id] = ['kind' => 'service_application', 'uuid' => $serviceApplication->uuid];
}
}
- if ($resourceKeys === []) {
- return ['records' => collect(), 'resource_keys' => [], 'warnings' => []];
- }
-
$records = ManagedDnsRecord::query()
->whereHas('references', function ($query) use ($resourceKeys) {
$query->where(function ($query) use ($resourceKeys) {
diff --git a/app/Services/ServerTransfer/ServerTransferImporter.php b/app/Services/ServerTransfer/ServerTransferImporter.php
index 11bd69663d..707f7fdc02 100644
--- a/app/Services/ServerTransfer/ServerTransferImporter.php
+++ b/app/Services/ServerTransfer/ServerTransferImporter.php
@@ -416,7 +416,7 @@ class ServerTransferImporter
$warnings = array_merge($warnings, $this->linkSqliteVolumes());
$this->importDnsZones(data_get($bundle, 'dns_zones', []), $preserveUuids);
- $created['managed_dns_records'] = $this->importManagedDnsRecords(data_get($bundle, 'managed_dns_records', []), $teamId, $preserveUuids);
+ $created['managed_dns_records'] = $this->importManagedDnsRecords(data_get($bundle, 'managed_dns_records', []), $server, $teamId, $preserveUuids);
$created['ssl_certificates'] = $this->importSslCertificates(data_get($bundle, 'ssl_certificates', []), $server);
$created['volume_backups'] = $this->importVolumeBackups(data_get($bundle, 'volume_backups', []), $teamId);
@@ -811,6 +811,9 @@ class ServerTransferImporter
$map[$originalUuid !== '' ? $originalUuid : $model->uuid] = $model->fresh();
}
+ // The created hook of the server made a default destination; the server gets only the destinations of the bundle.
+ StandaloneDocker::query()->whereKey($existingStandalone->slice($standaloneIndex)->modelKeys())->delete();
+ SwarmDocker::query()->whereKey($existingSwarm->slice($swarmIndex)->modelKeys())->delete();
return $map;
}
@@ -821,17 +824,7 @@ class ServerTransferImporter
private function importServerSharedEnvVars(array $variables, Server $server, int $teamId): void
{
foreach ($variables as $variable) {
- SharedEnvironmentVariable::create([
- 'key' => data_get($variable, 'key'),
- 'value' => data_get($variable, 'value'),
- 'is_multiline' => (bool) data_get($variable, 'is_multiline', false),
- 'is_literal' => (bool) data_get($variable, 'is_literal', false),
- 'is_shown_once' => (bool) data_get($variable, 'is_shown_once', false),
- 'comment' => data_get($variable, 'comment'),
- 'type' => 'server',
- 'server_id' => $server->id,
- 'team_id' => $teamId,
- ]);
+ $this->createSharedVariable($variable, ['type' => 'server', 'server_id' => $server->id, 'team_id' => $teamId]);
}
}
@@ -854,19 +847,37 @@ class ServerTransferImporter
continue;
}
- SharedEnvironmentVariable::create([
- 'key' => $key,
- 'value' => data_get($variable, 'value'),
- 'is_multiline' => (bool) data_get($variable, 'is_multiline', false),
- 'is_literal' => (bool) data_get($variable, 'is_literal', false),
- 'is_shown_once' => (bool) data_get($variable, 'is_shown_once', false),
- 'comment' => data_get($variable, 'comment'),
- 'type' => 'team',
- 'team_id' => $teamId,
- ]);
+ $this->createSharedVariable($variable, ['type' => 'team', 'team_id' => $teamId]);
}
}
+ /**
+ * @param array<string, mixed> $variable A shared variable of the bundle.
+ * @param array<string, mixed> $scope The type, the team, and the server, project, or environment of the variable.
+ */
+ private function createSharedVariable(array $variable, array $scope): void
+ {
+ $shared = new SharedEnvironmentVariable([
+ 'value' => data_get($variable, 'value'),
+ 'is_multiline' => (bool) data_get($variable, 'is_multiline', false),
+ 'is_literal' => (bool) data_get($variable, 'is_literal', false),
+ 'is_shown_once' => (bool) data_get($variable, 'is_shown_once', false),
+ 'comment' => data_get($variable, 'comment'),
+ ...$scope,
+ ]);
+ $this->keepVariableKey($shared, (string) data_get($variable, 'key'));
+ $shared->save();
+ }
+
+ /**
+ * Sets the key of a variable as it is on the source. The key setter rejects names that only older Coolify
+ * versions accepted (such as my-var); deployments skip those with a warning, so the transfer keeps them.
+ */
+ private function keepVariableKey(EnvironmentVariable|SharedEnvironmentVariable $variable, string $key): void
+ {
+ $variable->setRawAttributes(['key' => $key] + $variable->getAttributes());
+ }
+
/**
* @param array<string, mixed> $payload
* @param array<string, int> $created
@@ -1037,17 +1048,7 @@ class ServerTransferImporter
if ($exists) {
continue;
}
- SharedEnvironmentVariable::create([
- 'key' => data_get($variable, 'key'),
- 'value' => data_get($variable, 'value'),
- 'is_multiline' => (bool) data_get($variable, 'is_multiline', false),
- 'is_literal' => (bool) data_get($variable, 'is_literal', false),
- 'is_shown_once' => (bool) data_get($variable, 'is_shown_once', false),
- 'comment' => data_get($variable, 'comment'),
- 'type' => 'project',
- 'project_id' => $project->id,
- 'team_id' => $teamId,
- ]);
+ $this->createSharedVariable($variable, ['type' => 'project', 'project_id' => $project->id, 'team_id' => $teamId]);
}
}
@@ -1115,17 +1116,7 @@ class ServerTransferImporter
if ($exists) {
continue;
}
- SharedEnvironmentVariable::create([
- 'key' => data_get($variable, 'key'),
- 'value' => data_get($variable, 'value'),
- 'is_multiline' => (bool) data_get($variable, 'is_multiline', false),
- 'is_literal' => (bool) data_get($variable, 'is_literal', false),
- 'is_shown_once' => (bool) data_get($variable, 'is_shown_once', false),
- 'comment' => data_get($variable, 'comment'),
- 'type' => 'environment',
- 'environment_id' => $environment->id,
- 'team_id' => $teamId,
- ]);
+ $this->createSharedVariable($variable, ['type' => 'environment', 'environment_id' => $environment->id, 'team_id' => $teamId]);
}
}
@@ -1304,11 +1295,18 @@ class ServerTransferImporter
// Maintenance mode is not fillable.
$application->forceFill(collect($attributes)->only(['is_maintenance_enabled', 'maintenance_page'])->all());
$application->save();
+ // The created hook gives a new application the newest compose parser and default variables. A transferred
+ // application keeps its parser, which names its volumes and domains, and gets only the variables of the bundle.
+ $application->forceFill(collect($attributes)->only('compose_parsing_version')->filter()->all())->saveQuietly();
+ EnvironmentVariable::query()->whereMorphedTo('resourceable', $application)->delete();
$settings = (array) data_get($payload, 'settings', []);
if ($settings !== [] && $application->settings) {
+ $portsExposes = $application->ports_exposes;
$application->settings->fill(collect($settings)->except(['id', 'application_id'])->all());
$application->settings->save();
+ // The is_static setter sets the port of a static application to 80; the user can change it after that.
+ $application->refresh()->forceFill(['ports_exposes' => $portsExposes])->saveQuietly();
}
$this->importEnvVars(data_get($payload, 'environment_variables', []), $application, false);
@@ -1415,6 +1413,8 @@ class ServerTransferImporter
// Maintenance mode and the Coolify default variables switch are not fillable.
$service->forceFill(collect($attributes)->only(['is_maintenance_enabled', 'maintenance_page', 'include_coolify_default_variables'])->all());
$service->save();
+ // The created hook gives a new service the newest compose parser; a transferred service keeps its own.
+ $service->forceFill(collect($attributes)->only('compose_parsing_version')->filter()->all())->saveQuietly();
$this->importEnvVars(data_get($payload, 'environment_variables', []), $service, false);
$this->importScheduledTasks(data_get($payload, 'scheduled_tasks', []), $service, $teamId);
@@ -1524,7 +1524,6 @@ class ServerTransferImporter
$env = new EnvironmentVariable;
$env->forceFill([
- 'key' => data_get($variable, 'key'),
'value' => data_get($variable, 'value'),
'is_literal' => (bool) data_get($variable, 'is_literal', false),
'is_multiline' => (bool) data_get($variable, 'is_multiline', false),
@@ -1542,6 +1541,7 @@ class ServerTransferImporter
'resourceable_type' => $resource->getMorphClass(),
'resourceable_id' => $resource->id,
]);
+ $this->keepVariableKey($env, (string) data_get($variable, 'key'));
// Older bundles have no version; the column default applies.
if (filled(data_get($variable, 'version'))) {
$env->version = (string) data_get($variable, 'version');
@@ -2166,7 +2166,7 @@ class ServerTransferImporter
*
* @param list<array<string, mixed>> $records
*/
- private function importManagedDnsRecords(array $records, int $teamId, bool $preserveUuids): int
+ private function importManagedDnsRecords(array $records, Server $server, int $teamId, bool $preserveUuids): int
{
$count = 0;
foreach ($records as $payload) {
@@ -2177,6 +2177,7 @@ class ServerTransferImporter
'application' => $this->applicationMap[(string) data_get($reference, 'uuid')] ?? null,
'preview' => $this->previewMap[(string) data_get($reference, 'uuid')] ?? null,
'service_application' => $this->serviceApplicationMap[(string) data_get($reference, 'uuid')] ?? null,
+ 'server' => $server,
default => null,
})
->filter()
diff --git a/app/Services/ServerTransfer/ServerTransferMigrator.php b/app/Services/ServerTransfer/ServerTransferMigrator.php
index 1c8922c8d5..3166df1d24 100644
--- a/app/Services/ServerTransfer/ServerTransferMigrator.php
+++ b/app/Services/ServerTransfer/ServerTransferMigrator.php
@@ -523,7 +523,8 @@ class ServerTransferMigrator
throw new RuntimeException('Enter the URL at which the other instance reaches this instance.');
}
- $importToken = $user->createToken("transfer back {$archive->uuid}", ['read', 'write'], now()->addHours(3), $archive->team_id);
+ // The import checks and the import need write and deploy.
+ $importToken = $user->createToken("transfer back {$archive->uuid}", ['read', 'write', 'deploy'], now()->addHours(3), $archive->team_id);
$migrateUrl = $managerUrl.'/api/v1/servers/'.rawurlencode($archive->uuid).'/migrate';
try {
diff --git a/database/seeders/GitlabAppSeeder.php b/database/seeders/GitlabAppSeeder.php
index 5dfb599024..aa31398f43 100644
--- a/database/seeders/GitlabAppSeeder.php
+++ b/database/seeders/GitlabAppSeeder.php
@@ -4,6 +4,7 @@ namespace Database\Seeders;
use App\Models\GitlabApp;
use Illuminate\Database\Seeder;
+use Illuminate\Support\Facades\DB;
class GitlabAppSeeder extends Seeder
{
@@ -21,5 +22,9 @@ class GitlabAppSeeder extends Seeder
'is_public' => true,
'team_id' => 0,
]);
+ // The explicit id does not move the Postgres sequence, so the next GitLab App would get id 1 again.
+ if (DB::getDriverName() === 'pgsql') {
+ DB::statement("SELECT setval('gitlab_apps_id_seq', (SELECT MAX(id) FROM gitlab_apps))");
+ }
}
}
diff --git a/docs/server-transfer-full-coverage.md b/docs/server-transfer-full-coverage.md
index 1574983fc3..9aa62f2b6b 100644
--- a/docs/server-transfer-full-coverage.md
+++ b/docs/server-transfer-full-coverage.md
@@ -5,7 +5,9 @@ Use values that are NOT the default, so that a lost value is visible after the t
Use the kit in `scripts/transfer-test/` (see its README): it starts the source (A) and the target (B) and seeds A with a basic set of deployed resources.
-Legend: ✅ `scripts/transfer-test/seed.sh` or `seed-extras.php` already creates it · ➕ add it · ⚠️ needs special infrastructure
+Legend: ✅ `scripts/transfer-test/seed.sh`, `seed-extras.php`, or `seed-full.php` already creates it · ➕ add it · ⚠️ needs special infrastructure
+
+`scripts/transfer-test/full-e2e.sh` creates the ✅ items, transfers the server, and compares every record and every container automatically.
The models come from `ServerTransferCoverage::TRANSFERRED` (`app/Services/ServerTransfer/ServerTransferCoverage.php`).
When you add a model or a setting to the transfer, add it to this file too.
@@ -15,9 +17,9 @@ When you add a model or a setting to the transfer, add it to this file too.
| ✓ | What | Value to set |
|---|---|---|
| ✅ | Non-root SSH user | a dev VM with the `ubuntu-non-root` profile |
-| ➕ | Name, description | any text |
+| ✅ | Name, description | any text |
| ➕ | Port | other than 22, if the VM allows it |
-| ➕ | Proxy: redirect | redirect enabled + target URL |
+| ✅ | Proxy: redirect | redirect enabled + target URL |
| ✅ | Proxy: custom error page | custom HTML (`proxy_error_page`) |
| ➕ | Server role / build server | mark a second server as a build server |
| ⚠️ | Cloud provider link | Hetzner/Vultr/DigitalOcean/Hostinger server ID + cloud provider token (needs a real cloud server) |
@@ -27,21 +29,21 @@ When you add a model or a setting to the transfer, add it to this file too.
| ✓ | What | Value to set |
|---|---|---|
-| ➕ | Wildcard domain | `http://{ip}.sslip.io` style, not empty |
-| ➕ | Concurrent builds, dynamic timeout, deployment queue limit, connection timeout | 3, 1800, 5, 20 |
-| ➕ | Server timezone | `Europe/Budapest` |
-| ➕ | Docker cleanup | force cleanup on, frequency `0 4 * * *`, threshold 70, delete unused volumes on, delete unused networks on |
-| ➕ | Disk usage notification | threshold 70, check frequency `*/30 * * * *`, interval 12 h |
-| ➕ | Security > Patches | check frequency `daily`, automatic security updates on at `04:30` (the last check result is not moved; the target shows "never" until its first check) |
-| ➕ | Terminal | terminal access off |
-| ➕ | Image retention | "disable application image retention" on |
-| ➕ | Labels / Traefik | generate exact labels on, Traefik certificate resolver `custom` |
-| ➕ | Backup compression | CPU percentage 50 |
-| ➕ | Metrics / Sentinel | metrics on, refresh rate 10 s, history 14 days, push interval 30 s |
-| ➕ | Traffic analytics | on, top N 20, sample threshold, retention 1h=3 / 1d=60 days, IP mode `anonymized` |
-| ➕ | GeoIP | on, MaxMind license key, refresh 14 days |
-| ➕ | Log drains | New Relic (key + base URI), Highlight (project ID), Axiom (dataset + key), custom (config + parser), one of them enabled |
-| ✅ | Cloudflare tunnel | tunnel on, tunnel ID, account ID, Cloudflare integration token selected |
+| ✅ | Wildcard domain | `http://{ip}.sslip.io` style, not empty |
+| ✅ | Concurrent builds, dynamic timeout, deployment queue limit, connection timeout | 3, 1800, 5, 20 |
+| ✅ | Server timezone | `Europe/Budapest` |
+| ✅ | Docker cleanup | force cleanup on, frequency `0 4 * * *`, threshold 70, delete unused volumes on, delete unused networks on |
+| ✅ | Disk usage notification | threshold 70, check frequency `*/30 * * * *`, interval 12 h |
+| ✅ | Security > Patches | check frequency `daily`, automatic security updates on at `04:30` (the last check result is not moved; the target shows "never" until its first check) |
+| ✅ | Terminal | terminal access off |
+| ✅ | Image retention | "disable application image retention" on |
+| ✅ | Labels / Traefik | generate exact labels on, Traefik certificate resolver `custom` |
+| ✅ | Backup compression | CPU percentage 50 |
+| ✅ | Metrics / Sentinel | metrics on, refresh rate 10 s, history 14 days, push interval 30 s |
+| ✅ | Traffic analytics | on, top N 20, sample threshold, retention 1h=3 / 1d=60 days, IP mode `anonymized` |
+| ✅ | GeoIP | on, MaxMind license key, refresh 14 days |
+| ✅ | Log drains | New Relic (key + base URI), Highlight (project ID), Axiom (dataset + key), custom (config + parser), one of them enabled |
+| ✅ | Cloudflare tunnel | tunnel on, tunnel ID, account ID, Cloudflare integration token selected, and the DNS record of the SSH hostname. Expected: the record moves with the server; the source keeps it only for a take back (not owned) |
| ➕ | Jump server flag | on (on a server that is only a jump host) |
## 3. Server-level records
@@ -49,9 +51,9 @@ When you add a model or a setting to the transfer, add it to this file too.
| ✓ | What | Notes |
|---|---|---|
| ✅ | Default destination | created automatically |
-| ➕ | Second standalone destination | extra Docker network, one resource on it |
-| ➕ | Server shared variables | 2 variables, one multiline, one literal, one with a comment |
-| ➕ | SSL certificates | CA certificate (created automatically) + a database with SSL on (creates a server certificate) |
+| ✅ | Second standalone destination | extra Docker network, one resource on it |
+| ✅ | Server shared variables | 2 variables, one multiline, one literal, one with a comment |
+| ✅ | SSL certificates | CA certificate (created automatically) + a database with SSL on (creates a server certificate) |
| ✅ | GitHub runner config | labels, max runners 2, docker mode `dind`, image, CPU/memory limits, 3 timeouts, PR jobs off, dedicated on, uses the team GitHub App (see 4). Expected: on the target it is **disabled** and the checklist says to enable it |
## 4. Team credentials the server uses
@@ -59,10 +61,10 @@ When you add a model or a setting to the transfer, add it to this file too.
| ✓ | What | Notes |
|---|---|---|
| ✅ | Server private key | |
-| ➕ | Deploy key | a second private key used by an application (git over SSH) |
+| ✅ | Deploy key | a second private key used by an application (git over SSH) |
| ✅ | GitHub App (team, not system-wide) | with runner fields (`organization_self_hosted_runners`, `actions`, `webhook_events`, `runner_group_id`). Expected: checklist step for Webhook/Setup/Callback URL |
-| ➕ | GitLab App (team) | used by one application. Expected: checklist step for the webhook URL |
-| ➕ | S3 storage | the dev MinIO service (the VM must reach it), used by a database backup and a volume backup |
+| ✅ | GitLab App (team) | used by one application. Expected: checklist step for the webhook URL |
+| ✅ | S3 storage | the dev MinIO service (the VM must reach it), used by a database backup and a volume backup |
| ✅ | Cloudflare integration token | for DNS zones and the tunnel |
| ✅ | Secret manager token | Infisical, Doppler, or Vault |
| ⚠️ | Cloud provider token | only with a real cloud server |
@@ -72,7 +74,7 @@ When you add a model or a setting to the transfer, add it to this file too.
| ✓ | What | Notes |
|---|---|---|
| ✅ | 2 projects, 2 environments | for example production and staging |
-| ✅/➕ | Project / environment shared variables | the seed tries to create them; check that they exist |
+| ✅ | Project / environment shared variables | the seed tries to create them; check that they exist |
| ✅ | Team shared variable | `TEAM_KEY`, used as `{{team.TEAM_KEY}}` in an application variable. Expected: created on the target |
| ✅ | Project description + icon (JPEG) | Expected: the icon is on the target |
| ✅ | Canvas positions | drag the nodes on the environment canvas |
@@ -86,22 +88,22 @@ When you add a model or a setting to the transfer, add it to this file too.
| ✅ | Docker image app (whoami) | |
| ✅ | Dockerfile app | |
| ➕ | Nixpacks app, public GitHub repo | Expected: checklist step for manual webhooks |
-| ➕ | Static app (`is_static`, `is_spa`) | |
+| ✅ | Static app (`is_static`, `is_spa`) | |
| ➕ | Docker Compose app | raw compose on, one variable with an empty value (`preserve_compose_null`) |
| ➕ | App with GitHub App source, app with GitLab App source, app with deploy key | |
-| ➕ | Domains | 2 domains, noindex domains, domain port overrides, preview URL template |
-| ➕ | Health check | custom path, port, method, return code, interval, retries, start period |
-| ➕ | Limits | memory, swap, swappiness, reservation, CPUs, cpuset, CPU shares |
+| ✅ | Domains | 2 domains, noindex domains, domain port overrides, preview URL template |
+| ✅ | Health check | custom path, port, method, return code, interval, retries, start period |
+| ✅ | Limits | memory, swap, swappiness, reservation, CPUs, cpuset, CPU shares |
| ➕ | Advanced | custom labels, custom docker run options, pre/post deployment command + container, manual webhook secrets |
| ✅ | Maintenance | maintenance mode on + custom maintenance page |
-| ➕ | All application settings that are not the default | git submodules, LFS, shallow clone, auto deploy off, force HTTPS, debug, preview deployments on, PR deployments public, log drain, GPU (driver, count, device IDs, options), include timestamps, swarm-only worker nodes, build server, consistent container name, gzip off, strip prefix off, connect to Docker network, custom internal name, container label escape off, env sorting, read-only labels, preserve repository, disable build cache, use build secrets, stop grace period 30, inject build args off, include source commit, Docker images to keep 5, custom container name prefix, redact env values in logs, Coolify default variables off, Traefik certificate resolver |
-| ➕ | Environment variables | normal, multiline, literal, shown once, build time only, runtime only, required, with comment, preview-only, and references to `{{team.*}}`, `{{project.*}}`, `{{environment.*}}`, `{{server.*}}` |
-| ✅/➕ | Persistent volume | the seed has one; add a host-path bind mount and preview suffix on |
-| ➕ | File mount + directory mount | content, chown, chmod |
-| ➕ | Volume backup | on the persistent volume: S3 on, stop during backup, all retention values, timeout, missing-backup days |
-| ✅/➕ | Scheduled tasks | the seed has one; add a disabled one with container + timeout |
+| ✅ | All application settings that are not the default | git submodules, LFS, shallow clone, auto deploy off, force HTTPS, debug, preview deployments on, PR deployments public, log drain, GPU (driver, count, device IDs, options), include timestamps, swarm-only worker nodes, build server, consistent container name, gzip off, strip prefix off, connect to Docker network, custom internal name, container label escape off, env sorting, read-only labels, preserve repository, disable build cache, use build secrets, stop grace period 30, inject build args off, include source commit, Docker images to keep 5, custom container name prefix, redact env values in logs, Coolify default variables off, Traefik certificate resolver |
+| ✅ | Environment variables | normal, multiline, literal, shown once, build time only, runtime only, required, with comment, preview-only, and references to `{{team.*}}`, `{{project.*}}`, `{{environment.*}}`, `{{server.*}}` |
+| ✅ | Persistent volume | the seed has one; add a host-path bind mount and preview suffix on |
+| ✅ | File mount + directory mount | content, chown, chmod |
+| ✅ | Volume backup | on the persistent volume: S3 on, stop during backup, all retention values, timeout, missing-backup days |
+| ✅ | Scheduled tasks | the seed has one; add a disabled one with container + timeout |
| ✅ | Tag | |
-| ➕ | Preview deployment | PR preview with domain port overrides + max restart count (needs the GitHub App, or create it in the database) |
+| ✅ | Preview deployment | PR preview with domain port overrides + max restart count (needs the GitHub App, or create it in the database) |
| ✅ | Secret manager link | the app loads variables from the secret manager token |
| ✅ | Managed DNS record | owned record in the Cloudflare zone for the app domain. Expected: the target takes ownership (provider comment changes) |
@@ -110,12 +112,12 @@ When you add a model or a setting to the transfer, add it to this file too.
| ✓ | Type | Extra settings |
|---|---|---|
| ✅ | PostgreSQL | + init script, `postgres_conf`, host auth method, SSL on + mode |
-| ➕ | MySQL | + `mysql_conf`, SSL |
+| ✅ | MySQL | + `mysql_conf`, SSL |
| ✅ | MariaDB | + `mariadb_conf`, SSL |
-| ➕ | MongoDB | + `mongo_conf`, SSL |
+| ✅ | MongoDB | + `mongo_conf`, SSL |
| ✅ | Redis | + `redis_conf`, SSL |
-| ➕ | KeyDB, Dragonfly, ClickHouse | defaults are enough, plus the common settings below |
-| ➕ | SQLite | database files list, volume link |
+| ✅ | KeyDB, Dragonfly, ClickHouse | defaults are enough, plus the common settings below |
+| ✅ | SQLite | database files list, volume link |
Common settings on at least one database: custom image, public port + public on + public port timeout, limits, custom docker run options, health check values, log drain, include timestamps, redact env values, Coolify default variables off, environment variables, persistent volume + volume backup, tags, secret manager link (if the type supports it).
@@ -126,15 +128,15 @@ Database backups (✅ one exists): add S3 on, dump all, databases list, local an
| ✓ | What | Notes |
|---|---|---|
| ✅ | One-click service (uptime-kuma) | |
-| ➕ | Custom compose service with an app and a database part | |
-| ➕ | Service app settings | domain, gzip off, strip prefix off, force HTTPS, exclude from status, redirect, port overrides, log drain, custom image, Traefik resolver |
-| ➕ | Service database settings | public port + public on, custom type |
-| ➕ | Service level | connect to network, label escape off, redact env values, Coolify default variables off, maintenance mode + page, environment variables, scheduled task, tags, volume backup on a service volume |
+| ✅ | Custom compose service with an app and a database part | |
+| ✅ | Service app settings | domain, gzip off, strip prefix off, force HTTPS, exclude from status, redirect, port overrides, log drain, custom image, Traefik resolver |
+| ✅ | Service database settings | public port + public on, custom type |
+| ✅ | Service level | connect to network, label escape off, redact env values, Coolify default variables off, maintenance mode + page, environment variables, scheduled task, tags, volume backup on a service volume |
## 9. After the transfer, check
- Transfer log: every check `OK`, the `NOTE:` line for the shared project.
- "After the transfer" checklist: GitHub App URLs, GitLab webhook, manual webhooks, GitHub runners. All URLs use the public URL of the target.
- Target: every item above has the same value. Runner config disabled. DNS records owned by the target.
-- Source: the server is an archive, the runner config is disabled, and no DNS records are tracked.
+- Source: the server is an archive, the runner config is disabled, and no DNS records are tracked. The archive refuses actions on the host, the cloud server (delete, power on), the Cloudflare tunnel, and DNS records.
- Delete the archive on the source: the containers, DNS records, and GitHub runners are not changed.
diff --git a/resources/views/livewire/server/show.blade.php b/resources/views/livewire/server/show.blade.php
index cfbad137c9..de4c475729 100644
--- a/resources/views/livewire/server/show.blade.php
+++ b/resources/views/livewire/server/show.blade.php
@@ -294,7 +294,7 @@
<x-reicon name="refresh" class="size-3.5" />
</x-forms.button>
@endif
- @if ($server->cloudProviderToken)
+ @if ($server->cloudProviderToken && ! $server->isTransferredAway())
@if ($provider === 'Hetzner' && !$server->isFunctional() && $hetznerServerStatus === 'off')
<x-forms.button type="button" wire:click.prevent="startHetznerServer" isHighlighted
canGate="update" :canResource="$server">
diff --git a/scripts/transfer-test/README.md b/scripts/transfer-test/README.md
index 0a90e0f1c4..7b0fb32b33 100644
--- a/scripts/transfer-test/README.md
+++ b/scripts/transfer-test/README.md
@@ -23,10 +23,27 @@ scripts/transfer-test/e2e.sh # transfer both VMs A -> B through th
scripts/transfer-test/reset.sh
scripts/transfer-test/reverse-e2e.sh # undo paths: transfer back, transfer over an archive, take back, archive delete (18 checks)
scripts/transfer-test/reset.sh
-scripts/transfer-test/extras-e2e.sh # fake tokens, DNS, secret links, runner config, links, icon ... (31 checks)
+scripts/transfer-test/extras-e2e.sh # fake tokens, DNS, secret links, runner config, links, icon ... (33 checks)
+scripts/transfer-test/reset.sh
+scripts/transfer-test/full-e2e.sh # every kind of resource and setting on debian-root, compared record by record and container by container
scripts/transfer-test/reset.sh
```
+`full-e2e.sh` adds the records of `seed-extras.php` and `seed-full.php` to debian-root (settings that are not the
+default, every database type, a service with compose parser version 3, a second destination, backups to the dev MinIO),
+deploys them on A, and transfers the server. Then it compares:
+
+- every record of the server on A and on B (`snapshot.sh` writes the records, `snapshot-diff.php` prints each missing
+ row, extra row, and changed column that `ServerTransferCoverage` does not explain),
+- the containers and the files in `/data/coolify` on the VM after A deployed and after B deployed everything again
+ (`runtime-snapshot.sh`),
+- a database backup to S3, a volume backup, and a scheduled task that B runs.
+
+The results are in `<state>/full/` (`db.diff`, `runtime.diff`). The VM must reach the MinIO containers of A and B:
+`sudo iptables -t raw -I PREROUTING 1 -s 10.221.<A slot>.0/24 -d <MinIO container IP>/32 -p tcp --dport 9000 -j ACCEPT`
+for each of them (not persistent). `tests/Unit/ServerTransfer/ServerTransferCoverageTest.php` runs the same record
+comparison in CI, with a value that is not the default in every column.
+
For a manual test, run `scripts/transfer-test/manual-setup.sh`: it resets, adds the fake extra records to A, and
prints the URLs, logins, and tokens.
@@ -47,6 +64,9 @@ VM server on A → Transfer, and use the target URL `http://localhost:<B port>`
| `seed-extras.php`, `verify-extras-*.php` | Fake records and checks of `extras-e2e.sh` |
| `manual-setup.sh` | Reset plus the fake extra records, then prints what to open and enter for a manual test |
| `seed-inventory.php` | Seeds a large database-only demo server (no deploys) on the current instance |
+| `full-e2e.sh`, `seed-full.php` | The full coverage test and its records |
+| `snapshot.sh`, `snapshot.php`, `snapshot-diff.php` | Write and compare the records of a server (`Tests\Support\ServerTransferSnapshot`) |
+| `runtime-snapshot.sh` | Writes the containers and Coolify files of a VM for a comparison |
Tokens and the VM SSH key are written to `<main checkout>/.dev-instances/transfer-test/<source>/` (not in git).
For a full manual test of every transferred setting, see `docs/server-transfer-full-coverage.md`.
diff --git a/scripts/transfer-test/e2e.sh b/scripts/transfer-test/e2e.sh
index 7f13cc253a..b98f218cc1 100755
--- a/scripts/transfer-test/e2e.sh
+++ b/scripts/transfer-test/e2e.sh
@@ -30,6 +30,8 @@ for profile in "${TRANSFER_PROFILES[@]}"; do
check 'A shows the take-back modal' test "$(tinker "$A" "$login_php echo (int) str_contains(Livewire\\Livewire::test(App\\Livewire\\Server\\Show::class, ['server_uuid'=>'$S'])->html(), 'Take back a transferred server?');" | tail -1)" = 1
r="$(api POST "$A_PORT" "/servers/$S/migrate" "$TA" "$(jq -nc --arg u "http://localhost:$B_PORT" --arg t "$TB" '{target_url:$u,target_token:$t}')")"
check 'second transfer refused by the prechecks' grep -q 'already transferred' <<<"$r"
+ r="$(api DELETE "$A_PORT" "/servers/$S?delete_from_provider=true" "$TA")"
+ check 'A refuses to delete the cloud server of the archive' grep -q 'managed by another Coolify instance' <<<"$r"
echo '-- target B'
b="$(api GET "$B_PORT" "/servers/$S/transfer" "$TB")"
@@ -62,6 +64,31 @@ for profile in "${TRANSFER_PROFILES[@]}"; do
for _ in $(seq 1 40); do sleep 5; ds="$(tinker "$B" "echo App\\Models\\ApplicationDeploymentQueue::where('application_id', App\\Models\\Application::where('uuid','$app')->value('id'))->latest('id')->value('status');" | tail -1)"; [[ "$ds" == finished || "$ds" == failed ]] && break; done
check "redeploy from B ($ds)" test "$ds" = finished
check 'app answers after the redeploy' bash -c "for i in {1..10}; do curl -sf -m5 -H 'Host: $app.$ip.sslip.io' http://$ip/ >/dev/null && exit 0; sleep 3; done; exit 1"
+
+ [[ "$profile" == ubuntu-non-root ]] || continue
+ echo '-- operations from B over the non-root SSH user'
+ uuid_on_b() { tinker "$B" "echo App\\Models\\$1::where('name','$2')->value('uuid');" | tail -1; }
+ pg="$(uuid_on_b StandalonePostgresql postgres)"
+ rd="$(uuid_on_b StandaloneRedis redis)"
+ sv="$(uuid_on_b Service uptime-kuma)"
+ nginx="$(uuid_on_b Application nginx-dockerfile)"
+ for u in "$pg" "$rd"; do api POST "$B_PORT" "/databases/$u/restart" "$TB" >/dev/null; done
+ api POST "$B_PORT" "/services/$sv/restart" "$TB" >/dev/null
+ sleep 20
+ stable_workloads "$profile" >/dev/null
+ running_after="$(workloads "$profile")"
+ for u in "$pg" "$rd" "$sv"; do check "restarted from B: $u runs" grep -q "$u" <<<"$running_after"; done
+ tinker "$B" "App\\Jobs\\DatabaseBackupJob::dispatchSync(App\\Models\\StandalonePostgresql::where('uuid','$pg')->first()->scheduledBackups()->firstOrFail());" >/dev/null
+ r="$(tinker "$B" "echo App\\Models\\StandalonePostgresql::where('uuid','$pg')->first()->scheduledBackups()->first()->executions()->latest('id')->value('status');" | tail -1)"
+ check "database backup from B ($r)" test "$r" = success
+ task="$(api POST "$B_PORT" "/applications/$nginx/scheduled-tasks" "$TB" '{"name":"from-b","command":"echo from-b","frequency":"0 0 * * *"}' | jq -r .uuid)"
+ api POST "$B_PORT" "/applications/$nginx/scheduled-tasks/$task/execute" "$TB" >/dev/null
+ for _ in $(seq 1 20); do
+ sleep 3
+ r="$(api GET "$B_PORT" "/applications/$nginx/scheduled-tasks/$task/executions" "$TB" | jq -r '.[0].status // empty')"
+ [[ "$r" == success || "$r" == failed ]] && break
+ done
+ check "scheduled task from B ($r)" test "$r" = success
done
echo "=== $FAILS failure(s)"
diff --git a/scripts/transfer-test/full-e2e.sh b/scripts/transfer-test/full-e2e.sh
new file mode 100755
index 0000000000..82e3c6b5dc
--- /dev/null
+++ b/scripts/transfer-test/full-e2e.sh
@@ -0,0 +1,127 @@
+#!/usr/bin/env bash
+# Full coverage: add every kind of resource and setting to debian-root on A (seed-extras.php, seed-full.php, and the
+# resources below), deploy them, transfer the server to B through the Transfer page, then compare:
+# - the database records of the server on A and on B (snapshot.sh + snapshot-diff.php),
+# - what runs on the VM after A deployed and after B deployed everything again (runtime-snapshot.sh),
+# and run a database backup, a volume backup, and a scheduled task from B.
+# Run reset.sh before and after. The files are in <state>/full/.
+source "$(dirname "$0")/lib.sh"
+TA="$(source_token)"
+TB="$(target_token)"
+PROFILE=debian-root
+S="$(vm_field "$PROFILE" uuid)"
+ip="$(vm_field "$PROFILE" ip)"
+OUT="$STATE_DIR/full"
+mkdir -p "$OUT"
+P2="$(jq -r '.projects[1]' "$STATE_DIR/resources.json")"
+
+# call <port> <token> <METHOD> <path> [json]: the response body; stops the test on an HTTP error.
+call() {
+ local out code
+ out="$(curl -sS -m 60 -X "$3" "http://127.0.0.1:$1/api/v1$4" -H "Authorization: Bearer $2" -H 'Content-Type: application/json' -H 'Accept: application/json' ${5:+-d "$5"} -w $'\n%{http_code}')"
+ code="${out##*$'\n'}"
+ out="${out%$'\n'*}"
+ [[ "$code" -lt 300 ]] || die "$3 $4 ($code): $out"
+ echo "$out"
+}
+on() { jq -nc --arg p "$P2" --arg s "$S" --arg d "${DEST:-}" '{project_uuid:$p,server_uuid:$s,destination_uuid:$d,environment_name:"production",instant_deploy:false}' | jq -c ". + $1"; }
+uuid_of() { tinker "$1" "echo App\\Models\\$2::where('name','$3')->value('uuid');" | tail -1; }
+wait_deployments() {
+ for _ in $(seq 1 60); do
+ sleep 5
+ [[ "$(tinker "$1" 'echo App\Models\ApplicationDeploymentQueue::whereIn("status", ["queued", "in_progress"])->count();' | tail -1)" == 0 ]] && return 0
+ done
+ return 1
+}
+
+echo '=== 1. resources and settings on A'
+tinker "$A" "App\\Models\\StandaloneDocker::firstOrCreate(['network' => 'second-net', 'server_id' => App\\Models\\Server::where('uuid','$S')->value('id')], ['name' => 'second-net']);" >/dev/null
+NET2_DEST="$(tinker "$A" "echo App\\Models\\StandaloneDocker::where('network','second-net')->value('uuid');" | tail -1)"
+DEST="$(tinker "$A" "echo App\\Models\\StandaloneDocker::where('server_id', App\\Models\\Server::where('uuid','$S')->value('id'))->where('network','coolify')->value('uuid');" | tail -1)"
+COMPOSE="$(printf 'services:\n web:\n image: traefik/whoami\n environment:\n - SERVICE_URL_WEB_80\n cache:\n image: redis:7-alpine\n volumes:\n - cache-data:/data\n - ./conf:/conf\n' | base64 -w0)"
+call "$A_PORT" "$TA" POST /services "$(on "{name:\"svc-legacy\",docker_compose_raw:\"$COMPOSE\"}")" >/dev/null
+call "$A_PORT" "$TA" POST /databases/postgresql "$(on '{name:"pg-ssl",postgres_user:"full",postgres_password:"full-pg-password",postgres_db:"postgres"}')" >/dev/null
+for type in mysql mongodb keydb dragonfly clickhouse redis sqlite; do
+ call "$A_PORT" "$TA" POST "/databases/$type" "$(on "{name:\"idle-$type\"}")" >/dev/null
+done
+call "$A_PORT" "$TA" POST /applications/dockerimage "$(on "{name:\"whoami-net2\",destination_uuid:\"$NET2_DEST\",docker_registry_image_name:\"traefik/whoami\",docker_registry_image_tag:\"v1.10\",ports_exposes:\"80\"}")" >/dev/null
+php_file "$A" "$TT_DIR/seed-full.php"
+
+APP="$(uuid_of "$A" Application whoami-2)"
+NET2="$(uuid_of "$A" Application whoami-net2)"
+PG="$(uuid_of "$A" StandalonePostgresql pg-ssl)"
+MD="$(uuid_of "$A" StandaloneMariadb mariadb)"
+SVC="$(uuid_of "$A" Service svc-legacy)"
+
+echo '=== 2. deploy on A'
+for u in "$APP" "$NET2"; do call "$A_PORT" "$TA" POST "/deploy?uuid=$u&force=true" >/dev/null; done
+call "$A_PORT" "$TA" POST "/databases/$PG/start" >/dev/null
+# reset.sh does not wait for database starts, so A starts MariaDB again, as B does after the transfer.
+call "$A_PORT" "$TA" POST "/databases/$MD/restart" >/dev/null
+call "$A_PORT" "$TA" POST "/services/$SVC/start" >/dev/null
+wait_deployments "$A" || bad 'deployments on A finished'
+tinker "$A" 'foreach (App\Models\ApplicationDeploymentQueue::latest("id")->take(2)->get() as $d) echo " deploy ".$d->application_name.": ".$d->status.PHP_EOL;'
+stable_workloads "$PROFILE" >/dev/null
+cache="$(ssh_vm "$PROFILE" "docker ps --format '{{.Names}}' | grep '^cache-$SVC'")"
+ssh_vm "$PROFILE" "docker exec $cache sh -c 'echo kept-by-transfer > /conf/marker'"
+# The fake records of seed-extras.php (secret manager, DNS) would make a deployment fail, so they come after it.
+php_file "$A" "$TT_DIR/seed-extras.php"
+"$TT_DIR/runtime-snapshot.sh" "$PROFILE" "$OUT/runtime-A.txt"
+"$TT_DIR/snapshot.sh" A "$S" "$OUT/db-A.json"
+
+echo "=== 3. transfer $S A -> B"
+check "transfer succeeded ($(transfer_from_page "$S"))" test "$(tinker "$A" "echo data_get(App\\Models\\Server::where('uuid','$S')->first()->server_metadata, 'migration.status');" | tail -1)" = succeeded
+tinker "$A" 'echo config("app.id");' | tail -1 | docker exec -i "$B" sh -c 'cat > /tmp/source-app-id'
+
+echo '=== 4. records on B'
+extras="$(php_file "$B" "$TT_DIR/verify-extras-target.php"; php_file "$A" "$TT_DIR/verify-extras-source.php")"
+grep -E '^(PASS|FAIL)' <<<"$extras"
+FAILS=$((FAILS + $(grep -c '^FAIL' <<<"$extras")))
+"$TT_DIR/snapshot.sh" B "$S" "$OUT/db-B.json"
+php "$TT_DIR/snapshot-diff.php" "$OUT/db-A.json" "$OUT/db-B.json" >"$OUT/db.diff"
+grep -v '^expected' "$OUT/db.diff"
+check 'every record and value of A is on B (db.diff)' grep -q '^=== 0 unexplained' "$OUT/db.diff"
+
+echo '=== 5. deploy and restart everything from B'
+# The fake Infisical token of seed-extras.php cannot give secrets to a deployment.
+tinker "$B" "App\\Models\\SecretManagerLink::query()->delete();" >/dev/null
+for u in "$APP" "$NET2"; do call "$B_PORT" "$TB" POST "/deploy?uuid=$u&force=true" >/dev/null; done
+for u in "$PG" "$MD"; do call "$B_PORT" "$TB" POST "/databases/$u/restart" >/dev/null; done
+call "$B_PORT" "$TB" POST "/services/$SVC/restart" >/dev/null
+wait_deployments "$B" || bad 'deployments on B finished'
+check 'deployments from B finished' test "$(tinker "$B" 'echo App\Models\ApplicationDeploymentQueue::where("status", "!=", "finished")->count();' | tail -1)" = 0
+sleep 20
+stable_workloads "$PROFILE" >/dev/null
+"$TT_DIR/runtime-snapshot.sh" "$PROFILE" "$OUT/runtime-B.txt"
+# USES_TEAM comes from seed-extras.php, which runs after the deployment on A.
+without_team_var() { sed -E '/USES_TEAM/d; s/,$//' "$1"; }
+diff <(without_team_var "$OUT/runtime-A.txt") <(without_team_var "$OUT/runtime-B.txt") >"$OUT/runtime.diff" && ok 'B runs the same containers and files as A' || {
+ bad "B runs other containers or files than A ($(grep -c '^[<>]' "$OUT/runtime.diff") lines in runtime.diff)"
+ head -60 "$OUT/runtime.diff"
+}
+sentinel="$(ssh_vm "$PROFILE" "docker inspect coolify-sentinel --format '{{range .Config.Env}}{{println .}}{{end}}'")"
+for setting in COLLECTOR_ENABLED=true COLLECTOR_REFRESH_RATE_SECONDS=10 COLLECTOR_RETENTION_PERIOD_DAYS=14 PUSH_INTERVAL_SECONDS=30; do
+ check "Sentinel of B uses the moved setting $setting" grep -qx "$setting" <<<"$sentinel"
+done
+cache="$(ssh_vm "$PROFILE" "docker ps --format '{{.Names}}' | grep '^cache-$SVC'")"
+check 'the ./ bind mount of the parser v3 service keeps its data' test "$(ssh_vm "$PROFILE" "docker exec $cache cat /conf/marker")" = kept-by-transfer
+
+echo '=== 6. backups and scheduled tasks from B'
+tinker "$B" "App\\Jobs\\DatabaseBackupJob::dispatchSync(App\\Models\\ScheduledDatabaseBackup::where('description','full coverage backup')->firstOrFail());" >/dev/null
+r="$(tinker "$B" "\$e = App\\Models\\ScheduledDatabaseBackup::where('description','full coverage backup')->first()->executions()->latest('id')->first(); echo json_encode([\$e?->status, (bool) \$e?->s3_uploaded, \$e?->message]);" | tail -1)"
+check "database backup from B to S3 ($r)" test "$(jq -c '.[0:2]' <<<"$r")" = '["success",true]'
+volume="$(tinker "$B" "echo App\\Models\\LocalPersistentVolume::where('name','$APP-data')->value('uuid');" | tail -1)"
+call "$B_PORT" "$TB" POST "/applications/$APP/storages/$volume/backups/run" >/dev/null
+for _ in $(seq 1 30); do
+ sleep 5
+ r="$(tinker "$B" "\$e = App\\Models\\ScheduledVolumeBackup::whereHasMorph('backupable', [App\\Models\\LocalPersistentVolume::class], fn (\$q) => \$q->where('uuid', '$volume'))->first()?->executions()->latest('id')->first(); echo json_encode([\$e?->status?->value ?? \$e?->status, \$e?->message]);" | tail -1)"
+ [[ "$(jq -r '.[0]' <<<"$r")" =~ ^(success|failed)$ ]] && break
+done
+check "volume backup from B ($r)" test "$(jq -r '.[0]' <<<"$r")" = success
+tinker "$B" "App\\Jobs\\ScheduledTaskJob::dispatchSync(App\\Models\\ScheduledTask::where('name','service-task')->firstOrFail());" >/dev/null
+r="$(tinker "$B" "\$e = App\\Models\\ScheduledTask::where('name','service-task')->first()->executions()->latest('id')->first(); echo json_encode([\$e?->status, \$e?->message]);" | tail -1)"
+check "scheduled task of the service from B ($r)" test "$(jq -r '.[0]' <<<"$r")" = success
+check 'whoami-net2 answers over HTTP' bash -c "curl -sf -m5 -H 'Host: $NET2.$ip.sslip.io' http://$ip/ >/dev/null"
+
+echo "=== $FAILS failure(s). Files: $OUT"
+exit "$FAILS"
diff --git a/scripts/transfer-test/runtime-snapshot.sh b/scripts/transfer-test/runtime-snapshot.sh
new file mode 100755
index 0000000000..cc7b0b359a
--- /dev/null
+++ b/scripts/transfer-test/runtime-snapshot.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+# Write what Coolify runs on a VM of the source to a file: the workload containers (normalized docker inspect) and the
+# files that Coolify writes in /data/coolify. Take one after the source deployed and one after the target deployed
+# again, then compare them with `diff`. Values that change with every deployment are left out.
+#
+# Usage: scripts/transfer-test/runtime-snapshot.sh <profile> <output file>
+source "$(dirname "$0")/lib.sh"
+
+[[ $# -eq 2 ]] || die 'Usage: runtime-snapshot.sh <profile> <output file>'
+inspect="$(ssh_vm "$1" 'docker ps -q | xargs -r docker inspect')"
+# .env lines are sorted: their order has no meaning and follows the database IDs of the variables.
+files="$(ssh_vm "$1" 'cd /data/coolify && find applications databases services -type f -size -64k 2>/dev/null | sort | while read -r f; do printf "=== %s\n" "$f"; case "$f" in *.env) sort "$f" ;; *) cat "$f" ;; esac; echo; done')"
+jq -S '
+ map(select(.Name | test("^/coolify-(proxy|sentinel)$") | not)) | map({
+ name: (.Name | ltrimstr("/")),
+ image: .Config.Image, cmd: .Config.Cmd, entrypoint: .Config.Entrypoint, user: .Config.User, healthcheck: .Config.Healthcheck,
+ env: ((.Config.Env // []) | map(select(test("^(SOURCE_COMMIT|HOSTNAME)=") | not)) | sort),
+ labels: ((.Config.Labels // {}) | with_entries(select(.key | test("^(com\\.docker\\.compose\\.(config-hash|container-number|oneoff|version|depends_on|replace|image)|org\\.opencontainers\\.)") | not))),
+ host: (.HostConfig | {Memory, MemorySwap, MemorySwappiness, MemoryReservation, NanoCpus, CpusetCpus, CpuShares, RestartPolicy, PortBindings, CapAdd, ShmSize, Ulimits, LogConfig, ExtraHosts, Privileged, Init}),
+ mounts: ((.Mounts // []) | map({Type, Name, Source, Destination, RW}) | sort_by(.Destination)),
+ networks: (.NetworkSettings.Networks | to_entries | map({network: .key, aliases: ((.value.Aliases // []) | map(select(test("^[0-9a-f]{12}$") | not)) | sort)}) | sort_by(.network))
+ }) | sort_by(.name)' <<<"$inspect" >"$2"
+printf '%s\n' "$files" >>"$2"
+# Values that every deployment changes: the container name suffix, the artifact folder, and the deployment date.
+sed -i -E 's/-[0-9]{8}T[0-9]{6}/-<deployed>/g; s#/artifacts/[a-z0-9]+#/artifacts/<id>#g; s/^(Latest Deployment Date:).*/\1 <date>/; s/^(SOURCE_COMMIT)=.*/\1=<varies>/' "$2"
+echo "runtime snapshot of $1: $(jq length <<<"$inspect") containers -> $2"
diff --git a/scripts/transfer-test/seed-extras.php b/scripts/transfer-test/seed-extras.php
index 11b6a85fde..7059519335 100644
--- a/scripts/transfer-test/seed-extras.php
+++ b/scripts/transfer-test/seed-extras.php
@@ -49,6 +49,8 @@ $quiet(SecretManagerLink::class, ['resourceable_type' => $app->getMorphClass(),
// Server: Cloudflare tunnel token + custom proxy error page
$server->settings->forceFill(['cloudflare_tunnel_integration_token_id' => $cloudflare->id, 'cloudflare_tunnel_id' => 'fake-tunnel', 'cloudflare_tunnel_account_id' => 'fake-account'])->saveQuietly();
$server->forceFill(['proxy_error_page' => '<h1>fake error page</h1>'])->saveQuietly();
+// The server owns the DNS record of the SSH hostname of its tunnel
+$quiet(ManagedDnsRecord::class, ['team_id' => $teamId, 'integration_token_id' => $cloudflare->id, 'dns_provider_zone_id' => $zone->id, 'provider_record_id' => 'fake-ssh-record-id', 'type' => 'CNAME', 'name' => 'ssh-debian.example.test', 'content' => 'fake-tunnel.cfargotunnel.com', 'owned' => true])->addReference($server);
// GitHub App + runner config (enabled) + one idle runner
$githubApp = $quiet(GithubApp::class, ['name' => 'fake-gh-app', 'api_url' => 'https://api.github.com', 'html_url' => 'https://github.com', 'organization' => 'fake-org', 'app_id' => 123, 'installation_id' => 456, 'client_id' => 'fake-client', 'client_secret' => 'fake-secret', 'webhook_secret' => 'fake-webhook', 'is_system_wide' => false, 'is_public' => false, 'team_id' => $teamId, 'private_key_id' => $server->private_key_id]);
@@ -79,12 +81,11 @@ $app->forceFill(['is_maintenance_enabled' => true, 'maintenance_page' => '<h1>fa
// A git application that uses a system-wide GitHub App, which the transfer does not move
$systemApp = $quiet(GithubApp::class, ['name' => 'fake-system-wide-app', 'api_url' => 'https://api.github.com', 'html_url' => 'https://github.com', 'team_id' => 0, 'is_system_wide' => true, 'is_public' => false]);
-$gitApp = new Application;
-$gitApp->forceFill([
- 'uuid' => new_public_id(), 'name' => 'git-shop', 'build_pack' => 'nixpacks', 'git_repository' => 'acme/shop', 'git_branch' => 'main', 'ports_exposes' => '3000',
+$gitApp = Application::create([
+ 'name' => 'git-shop', 'build_pack' => 'nixpacks', 'git_repository' => 'acme/shop', 'git_branch' => 'main', 'ports_exposes' => '3000',
'environment_id' => $environment->id, 'destination_id' => $app->destination_id, 'destination_type' => $app->destination_type,
- 'source_type' => GithubApp::class, 'source_id' => $systemApp->id,
-])->saveQuietly();
+]);
+$gitApp->forceFill(['source_type' => GithubApp::class, 'source_id' => $systemApp->id])->saveQuietly();
// Project icon: a 1x1 JPEG
app(ProjectIconStorageService::class)->storeProjectContents($project, base64_decode('/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA='));
diff --git a/scripts/transfer-test/seed-full.php b/scripts/transfer-test/seed-full.php
new file mode 100644
index 0000000000..bdbee95719
--- /dev/null
+++ b/scripts/transfer-test/seed-full.php
@@ -0,0 +1,184 @@
+<?php
+
+// Non-default values on development-qemu-debian-root of the source (A), for full-e2e.sh. Run after
+// seed-extras.php and after full-e2e.sh created the resources through the API. Values that a transfer must keep
+// are not the defaults, so a lost value shows up in the snapshot diff. Deployed resources keep working values.
+
+use App\Models\Application;
+use App\Models\ApplicationPreview;
+use App\Models\EnvironmentVariable;
+use App\Models\GitlabApp;
+use App\Models\LocalFileVolume;
+use App\Models\LocalPersistentVolume;
+use App\Models\PrivateKey;
+use App\Models\S3Storage;
+use App\Models\ScheduledDatabaseBackup;
+use App\Models\ScheduledTask;
+use App\Models\ScheduledVolumeBackup;
+use App\Models\Server;
+use App\Models\Service;
+use App\Models\SharedEnvironmentVariable;
+use App\Models\StandalonePostgresql;
+use App\Models\Tag;
+use Illuminate\Support\Facades\DB;
+use Tests\Support\ServerTransferFuzzer as Fuzzer;
+
+$server = Server::where('uuid', 'development-qemu-debian-root')->firstOrFail();
+$teamId = $server->team_id;
+$ip = $server->ip;
+$app = Application::where('name', 'whoami-2')->firstOrFail();
+$environment = $app->environment;
+$project = $environment->project;
+$s3 = S3Storage::where('team_id', $teamId)->firstOrFail();
+
+// 1. Server, proxy, and server settings
+$server->forceFill(['description' => 'full coverage server'])->saveQuietly();
+$server->proxy->set('redirect_enabled', true);
+$server->proxy->set('redirect_url', 'https://redirect.example.test');
+$server->saveQuietly();
+$server->settings->forceFill([
+ 'wildcard_domain' => "http://{$ip}.sslip.io", 'concurrent_builds' => 3, 'dynamic_timeout' => 1800, 'deployment_queue_limit' => 5,
+ 'connection_timeout' => 20, 'server_timezone' => 'Europe/Budapest', 'force_docker_cleanup' => true, 'docker_cleanup_frequency' => '0 4 * * *',
+ 'docker_cleanup_threshold' => 70, 'delete_unused_volumes' => true, 'delete_unused_networks' => true,
+ 'server_disk_usage_notification_threshold' => 70, 'server_disk_usage_check_frequency' => '*/30 * * * *', 'server_disk_usage_notification_interval_hours' => 12,
+ 'patch_check_frequency' => 'daily', 'is_auto_security_updates_enabled' => true, 'auto_security_updates_time' => '04:30',
+ 'is_terminal_enabled' => false, 'disable_application_image_retention' => true, 'generate_exact_labels' => true,
+ 'traefik_certificate_resolver' => 'custom', 'backup_compression_cpu_percentage' => 50,
+ 'is_metrics_enabled' => true, 'sentinel_metrics_refresh_rate_seconds' => 10, 'sentinel_metrics_history_days' => 14, 'sentinel_push_interval_seconds' => 30,
+ 'is_traffic_analytics_enabled' => true, 'traffic_topn' => 20, 'traffic_sample_threshold' => 9, 'traffic_retention_1h_days' => 3, 'traffic_retention_1d_days' => 60,
+ 'traffic_ip_mode' => 'anonymized', 'is_geoip_enabled' => true, 'geoip_maxmind_license_key' => 'fake-maxmind-key', 'geoip_refresh_days' => 14,
+ 'logdrain_newrelic_license_key' => 'fake-newrelic', 'logdrain_newrelic_base_uri' => 'https://log-api.eu.newrelic.com/log/v1',
+ 'logdrain_highlight_project_id' => 'fake-highlight', 'logdrain_axiom_dataset_name' => 'fake-dataset', 'logdrain_axiom_api_key' => 'fake-axiom',
+ 'logdrain_custom_config' => "[OUTPUT]\n Name stdout\n", 'logdrain_custom_config_parser' => "[PARSER]\n Name fake\n",
+ 'logdrain_cloudwatch_region' => 'eu-central-1', 'logdrain_cloudwatch_group' => 'fake-group', 'logdrain_cloudwatch_stream_prefix' => 'fake-prefix',
+])->saveQuietly();
+
+// 2. Shared variables: server (multiline, literal, comment, empty), project, environment
+$shared = fn (array $attributes) => SharedEnvironmentVariable::create(['team_id' => $teamId, ...$attributes]);
+$shared(['type' => 'server', 'server_id' => $server->id, 'key' => 'SRV_MULTI', 'value' => "line one\n line two\n", 'is_multiline' => true, 'comment' => 'multiline']);
+$shared(['type' => 'server', 'server_id' => $server->id, 'key' => 'SRV_LITERAL', 'value' => '$NOT_EXPANDED', 'is_literal' => true]);
+$shared(['type' => 'server', 'server_id' => $server->id, 'key' => 'SRV_EMPTY', 'value' => '']);
+$shared(['type' => 'project', 'project_id' => $project->id, 'key' => 'PRJ_KEY', 'value' => 'project-value', 'is_shown_once' => true]);
+$shared(['type' => 'environment', 'environment_id' => $environment->id, 'key' => 'ENV_KEY', 'value' => 'environment-value']);
+
+// 3. whoami-2 (deployed): domains, health check, limits, advanced options, settings
+$app->forceFill([
+ 'fqdn' => "http://whoami2.{$ip}.sslip.io,http://whoami2b.{$ip}.sslip.io", 'noindex_domains' => ["http://whoami2b.{$ip}.sslip.io"],
+ 'description' => 'full coverage app', 'ports_mappings' => '18080:80', 'preview_url_template' => 'pr-{{pr_id}}.{{domain}}', 'redirect' => 'non-www',
+ 'health_check_enabled' => true, 'health_check_path' => '/health', 'health_check_port' => '80', 'health_check_interval' => 7,
+ 'health_check_timeout' => 4, 'health_check_retries' => 3, 'health_check_start_period' => 9,
+ 'limits_memory' => '128m', 'limits_memory_swap' => '256m', 'limits_memory_swappiness' => 30, 'limits_memory_reservation' => '64m',
+ 'limits_cpus' => '0.5', 'limits_cpuset' => '0', 'limits_cpu_shares' => 512,
+ 'custom_docker_run_options' => '--cap-add=NET_ADMIN --ulimit nofile=1024:2048', 'custom_network_aliases' => 'whoami-alias',
+ 'watch_paths' => "src/**\ndocs/*.md",
+ 'manual_webhook_secret_github' => 'fake-gh-secret', 'is_http_basic_auth_enabled' => true, 'http_basic_auth_username' => 'fuzz',
+ 'http_basic_auth_password' => 'fuzz-password', 'max_restart_count' => 4,
+])->save();
+$app->settings->forceFill([
+ 'is_gzip_enabled' => false, 'is_stripprefix_enabled' => false, 'is_include_timestamps' => true, 'is_container_label_escape_enabled' => false,
+ 'is_env_sorting_enabled' => true, 'docker_images_to_keep' => 5, 'stop_grace_period' => 30, 'redact_all_env_values_in_logs' => true,
+ 'include_coolify_default_variables' => false, 'traefik_certificate_resolver' => 'custom', 'connect_to_docker_network' => true,
+ 'custom_internal_name' => 'whoami-two', 'is_permanent_redirect_enabled' => true, 'is_log_drain_enabled' => false,
+ 'is_preview_deployments_enabled' => true, 'is_pr_deployments_public_enabled' => true, 'is_auto_deploy_enabled' => false,
+])->save();
+
+// Variables of every kind, and references to every shared scope
+$env = fn (array $attributes) => EnvironmentVariable::create(['resourceable_type' => $app->getMorphClass(), 'resourceable_id' => $app->id, ...$attributes]);
+$env(['key' => 'MULTI_LINE', 'value' => "first\nsecond", 'is_multiline' => true, 'comment' => 'two lines']);
+$env(['key' => 'LITERAL_VAR', 'value' => '$HOME/not-expanded', 'is_literal' => true]);
+$env(['key' => 'SHOWN_ONCE', 'value' => 'only-once', 'is_shown_once' => true]);
+$env(['key' => 'BUILD_ONLY', 'value' => 'build', 'is_runtime' => false, 'is_buildtime' => true]);
+$env(['key' => 'RUNTIME_ONLY', 'value' => 'runtime', 'is_runtime' => true, 'is_buildtime' => false]);
+$env(['key' => 'REQUIRED_VAR', 'value' => 'required', 'is_required' => true]);
+$env(['key' => 'PREVIEW_ONLY', 'value' => 'preview', 'is_preview' => true]);
+$env(['key' => 'USES_PROJECT', 'value' => '{{project.PRJ_KEY}}']);
+$env(['key' => 'USES_ENVIRONMENT', 'value' => '{{environment.ENV_KEY}}']);
+$env(['key' => 'USES_SERVER', 'value' => '{{server.SRV_LITERAL}}']);
+
+// Storages: file mount with whitespace, directory mount, host bind mount, persistent volume with an S3 backup
+$file = fn (array $attributes) => LocalFileVolume::create(['resource_type' => $app->getMorphClass(), 'resource_id' => $app->id, ...$attributes]);
+$file(['fs_path' => "/data/coolify/applications/{$app->uuid}/etc/fuzz.conf", 'mount_path' => '/etc/fuzz.conf', 'content' => " indented: true\nlast: line\n", 'chown' => '1000:1000', 'chmod' => '0640']);
+$file(['fs_path' => "/data/coolify/applications/{$app->uuid}/fuzz-dir", 'mount_path' => '/fuzz-dir', 'is_directory' => true]);
+LocalPersistentVolume::create(['name' => 'host-bind', 'mount_path' => '/host', 'host_path' => '/srv/fuzz-host', 'resource_type' => $app->getMorphClass(), 'resource_id' => $app->id]);
+$volume = LocalPersistentVolume::create(['name' => "{$app->uuid}-data", 'mount_path' => '/data', 'is_preview_suffix_enabled' => true, 'resource_type' => $app->getMorphClass(), 'resource_id' => $app->id]);
+$volumeBackup = ScheduledVolumeBackup::create([
+ 'backupable_type' => $volume->getMorphClass(), 'backupable_id' => $volume->id, 'team_id' => $teamId, 's3_storage_id' => $s3->id,
+ 'frequency' => '0 5 * * *', 'enabled' => true, 'save_s3' => true, 'stop_during_backup' => true, 'retention_amount_locally' => 3,
+ 'retention_days_locally' => 4, 'retention_max_storage_locally' => 5, 'retention_amount_s3' => 6, 'retention_days_s3' => 7,
+ 'retention_max_storage_s3' => 8, 'timeout' => 900, 'missing_backup_notification_days' => 2,
+]);
+$volumeBackup->s3Storages()->sync([$s3->id]);
+ScheduledTask::create(['name' => 'disabled-task', 'command' => 'echo disabled', 'frequency' => '0 1 * * *', 'enabled' => false, 'container' => 'whoami', 'timeout' => 120, 'application_id' => $app->id, 'team_id' => $teamId]);
+
+// 4. PostgreSQL with SSL (started): init script, config, public port, limits, health check, backups to S3
+$pg = StandalonePostgresql::where('name', 'pg-ssl')->firstOrFail();
+$pg->forceFill([
+ 'description' => 'full coverage postgres', 'image' => 'postgres:17-alpine', 'postgres_initdb_args' => '--data-checksums', 'postgres_host_auth_method' => 'scram-sha-256',
+ 'init_scripts' => [['index' => 0, 'filename' => 'init.sql', 'content' => "CREATE TABLE IF NOT EXISTS fuzz (id int);\n"]],
+ 'postgres_conf' => "max_connections = 50\n", 'enable_ssl' => true, 'ssl_mode' => 'verify-full', 'is_public' => true, 'public_port' => 25432,
+ 'public_port_timeout' => 1800, 'limits_memory' => '256m', 'limits_cpus' => '0.5', 'custom_docker_run_options' => '--shm-size=128m',
+ 'health_check_interval' => 11, 'health_check_timeout' => 6, 'health_check_retries' => 4, 'health_check_start_period' => 12,
+ 'is_include_timestamps' => true, 'redact_all_env_values_in_logs' => true, 'include_coolify_default_variables' => false,
+])->save();
+EnvironmentVariable::create(['key' => 'PG_EXTRA', 'value' => 'pg-extra', 'resourceable_type' => $pg->getMorphClass(), 'resourceable_id' => $pg->id]);
+$pg->tags()->attach(Tag::firstOrCreate(['name' => 'database', 'team_id' => $teamId])->id);
+$backup = ScheduledDatabaseBackup::create([
+ 'team_id' => $teamId, 'database_type' => $pg->getMorphClass(), 'database_id' => $pg->id, 's3_storage_id' => $s3->id, 'description' => 'full coverage backup',
+ 'enabled' => true, 'save_s3' => true, 'frequency' => '0 6 * * *', 'databases_to_backup' => 'postgres', 'dump_all' => false,
+ 'database_backup_retention_amount_locally' => 3, 'database_backup_retention_days_locally' => 4, 'database_backup_retention_max_storage_locally' => 5,
+ 'database_backup_retention_amount_s3' => 6, 'database_backup_retention_days_s3' => 7, 'database_backup_retention_max_storage_s3' => 8,
+ 'timeout' => 1200, 'disable_local_backup' => false, 'missing_backup_notification_days' => 2,
+]);
+$backup->s3Storages()->sync([$s3->id]);
+
+// 5. Legacy service (parser version 3) with a ./ bind mount, service app and database settings
+$service = Service::where('name', 'svc-legacy')->firstOrFail();
+$service->forceFill([
+ 'compose_parsing_version' => '3', 'description' => 'parser v3 service', 'connect_to_docker_network' => true, 'is_container_label_escape_enabled' => false,
+ 'redact_all_env_values_in_logs' => true, 'include_coolify_default_variables' => false,
+])->saveQuietly();
+$serviceApp = $service->applications()->firstOrFail();
+$serviceApp->forceFill([
+ 'fqdn' => "http://svc-legacy.{$ip}.sslip.io", 'is_gzip_enabled' => false, 'is_stripprefix_enabled' => false, 'exclude_from_status' => true,
+ 'redirect' => 'non-www', 'traefik_certificate_resolver' => 'custom', 'human_name' => 'Legacy Web', 'description' => 'service app',
+])->save();
+$serviceDb = $service->databases()->firstOrFail();
+$serviceDb->forceFill(['public_port' => 26379, 'is_public' => false, 'custom_type' => 'redis', 'human_name' => 'Legacy Cache'])->save();
+EnvironmentVariable::create(['key' => 'SERVICE_EXTRA', 'value' => 'service-extra', 'resourceable_type' => $service->getMorphClass(), 'resourceable_id' => $service->id]);
+ScheduledTask::create(['name' => 'service-task', 'command' => 'echo service', 'frequency' => '0 2 * * *', 'container' => 'cache', 'service_id' => $service->id, 'team_id' => $teamId]);
+$service->tags()->attach(Tag::firstOrCreate(['name' => 'legacy', 'team_id' => $teamId])->id);
+
+// 6. Records that are not deployed: git sources, deploy key, preview. These and the databases that are not started get
+// a non-default value in every column (Tests\Support\ServerTransferFuzzer), except the columns that must stay valid.
+$deployKey = PrivateKey::create(['team_id' => $teamId, 'name' => 'fake deploy key', 'private_key' => generateSSHKey('ed25519')['private'], 'is_git_related' => true]);
+$gitlab = new GitlabApp;
+$gitlab->forceFill(['uuid' => new_public_id(), 'name' => 'fake-gitlab', 'api_url' => 'https://gitlab.example.test/api/v4', 'html_url' => 'https://gitlab.example.test',
+ 'is_system_wide' => false, 'team_id' => $teamId, 'private_key_id' => $deployKey->id])->saveQuietly();
+Fuzzer::fill($gitlab, ['is_system_wide', 'api_url', 'html_url']);
+$keepApplication = ['name', 'fqdn', 'build_pack', 'git_repository', 'status', 'docker_compose_raw', 'docker_compose', 'docker_compose_domains', 'domain_port_overrides',
+ 'noindex_domains', 'custom_labels', 'domain_dns_statuses', 'dockerfile', 'custom_nginx_configuration', 'watch_paths', 'custom_network_aliases'];
+foreach ([['deploykey-app', 'nixpacks', null, $deployKey->id, '[email protected]:acme/private.git'], ['gitlab-app', 'nixpacks', $gitlab, null, 'acme/gitlab-repo'], ['static-site', 'static', null, null, 'acme/static-site']] as [$name, $buildPack, $source, $keyId, $repo]) {
+ $git = Application::create(['name' => $name, 'build_pack' => $buildPack, 'git_repository' => $repo, 'git_branch' => 'main', 'ports_exposes' => '3000',
+ 'environment_id' => $environment->id, 'destination_id' => $app->destination_id, 'destination_type' => $app->destination_type]);
+ $git->forceFill(['source_type' => $source ? $source::class : null, 'source_id' => $source?->id, 'private_key_id' => $keyId])->saveQuietly();
+ Fuzzer::fill($git, $keepApplication, ['compose_parsing_version' => '2', 'fqdn' => "http://{$name}.{$ip}.sslip.io", 'redirect' => 'www']);
+ Fuzzer::fill($git->settings);
+}
+// The is_static setter sets port 80; the user can set another port after that.
+Application::where('name', 'static-site')->firstOrFail()->forceFill(['ports_exposes' => '8080'])->saveQuietly();
+// Keys that only older Coolify versions accepted. Deployments skip them with a warning.
+$legacy = EnvironmentVariable::create(['key' => 'LEGACY_KEY', 'value' => 'legacy', 'resourceable_type' => $app->getMorphClass(), 'resourceable_id' => Application::where('name', 'static-site')->value('id')]);
+DB::table('environment_variables')->where('id', $legacy->id)->update(['key' => 'legacy-key']);
+$legacyShared = $shared(['type' => 'server', 'server_id' => $server->id, 'key' => 'LEGACY_SHARED', 'value' => 'legacy']);
+DB::table('shared_environment_variables')->where('id', $legacyShared->id)->update(['key' => 'legacy-shared']);
+$preview = new ApplicationPreview;
+$preview->forceFill(['application_id' => $app->id, 'pull_request_id' => 42, 'pull_request_html_url' => 'https://github.com/acme/shop/pull/42',
+ 'fqdn' => "http://pr-42.whoami2.{$ip}.sslip.io", 'max_restart_count' => 3, 'docker_registry_image_tag' => 'pr-42'])->save();
+foreach (['StandaloneMysql', 'StandaloneMongodb', 'StandaloneKeydb', 'StandaloneDragonfly', 'StandaloneClickhouse', 'StandaloneRedis', 'StandaloneSqlite'] as $type) {
+ foreach (("App\\Models\\{$type}")::where('name', 'like', 'idle-%')->get() as $database) {
+ // ssl_mode has a check constraint; pg-ssl covers it.
+ Fuzzer::fill($database, ['status', 'is_public', 'public_port', 'init_scripts', 'sqlite_databases', 'ssl_mode'], ['description' => "idle {$type}"]);
+ }
+}
+
+echo "seeded full coverage\n";
diff --git a/scripts/transfer-test/snapshot-diff.php b/scripts/transfer-test/snapshot-diff.php
new file mode 100644
index 0000000000..ef1974bf5e
--- /dev/null
+++ b/scripts/transfer-test/snapshot-diff.php
@@ -0,0 +1,29 @@
+<?php
+
+// Compare two snapshots of snapshot.sh (the source before the transfer, the target after it).
+// Prints the columns that ServerTransferCoverage leaves out on purpose with their reason, then one line per
+// missing row, extra row, and changed column that has no reason. Exits with the number of unexplained lines.
+//
+// Usage: php scripts/transfer-test/snapshot-diff.php <source.json> <target.json>
+
+require __DIR__.'/../../vendor/autoload.php';
+
+use Tests\Support\ServerTransferSnapshot;
+
+[$before, $after] = array_map(fn (string $file) => json_decode(file_get_contents($file), true, flags: JSON_THROW_ON_ERROR), array_slice($argv, 1, 2));
+$expected = [
+ ...array_fill_keys(ServerTransferSnapshot::LIVE_RUNTIME_COLUMNS, 'Runtime state that the instances update.'),
+ 'GithubRunnerConfig.is_enabled' => 'The target disables the runners until the user enables them.',
+ 'Application.publish_directory' => 'The model fills the default when the value is empty.',
+ 'Application.dockerfile_location' => 'The model fills the default when the value is empty.',
+ 'Application.docker_compose_location' => 'The model fills the default when the value is empty.',
+];
+['unexplained' => $unexplained, 'expected' => $expected] = ServerTransferSnapshot::diff($before, $after, $expected);
+foreach ($expected as $line) {
+ echo "expected {$line}\n";
+}
+foreach ($unexplained as $line) {
+ echo "DIFF {$line}\n";
+}
+echo '=== '.count($unexplained)." unexplained difference(s)\n";
+exit(min(count($unexplained), 255));
diff --git a/scripts/transfer-test/snapshot.php b/scripts/transfer-test/snapshot.php
new file mode 100644
index 0000000000..16f54bba03
--- /dev/null
+++ b/scripts/transfer-test/snapshot.php
@@ -0,0 +1,10 @@
+<?php
+
+use Tests\Support\ServerTransferSnapshot;
+
+// Writes the portable snapshot of a server (Tests\Support\ServerTransferSnapshot) to a file. snapshot.sh runs it.
+// Input (set before `require`): $snapshotServer (server uuid), $snapshotOut (output file).
+
+$snapshot = ServerTransferSnapshot::take($snapshotServer);
+file_put_contents($snapshotOut, json_encode($snapshot, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
+echo 'snapshot: '.collect($snapshot)->map(fn (array $rows) => count($rows))->sum()." rows\n";
diff --git a/scripts/transfer-test/snapshot.sh b/scripts/transfer-test/snapshot.sh
new file mode 100755
index 0000000000..4e1afe64e4
--- /dev/null
+++ b/scripts/transfer-test/snapshot.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+# Write the portable snapshot of a server (see snapshot.php) on the source (A) or the target (B) to a file.
+#
+# Usage: scripts/transfer-test/snapshot.sh A|B <server uuid> <output file>
+source "$(dirname "$0")/lib.sh"
+
+[[ $# -eq 3 ]] || die 'Usage: snapshot.sh A|B <server uuid> <output file>'
+C="$A"
+[[ "$1" == B ]] && C="$B"
+docker cp "$TT_DIR/snapshot.php" "$C:/tmp/snapshot.php" >/dev/null
+docker exec -u www-data "$C" php artisan tinker --execute "\$snapshotServer = '$2'; \$snapshotOut = '/tmp/snapshot.json'; require '/tmp/snapshot.php';" 2>&1 | grep -v '^$'
+docker cp "$C:/tmp/snapshot.json" "$3" >/dev/null
diff --git a/scripts/transfer-test/verify-extras-source.php b/scripts/transfer-test/verify-extras-source.php
index 2caeb569c1..629ac3abf0 100644
--- a/scripts/transfer-test/verify-extras-source.php
+++ b/scripts/transfer-test/verify-extras-source.php
@@ -21,6 +21,7 @@ $check('runner config disabled on the source', GithubRunnerConfig::where('server
$check('runner execution cancelled on the source', GithubRunnerExecution::where('runner_name', 'coolify-runner-fake')->value('status')?->value === 'cancelled');
$record = ManagedDnsRecord::where('name', 'whoami2.example.test')->first();
$check('source keeps the DNS record for a take back, not owned', $record !== null && $record->owned === false);
+$check('source keeps the tunnel SSH DNS record for a take back, not owned', ManagedDnsRecord::where('name', 'ssh-debian.example.test')->value('owned') === false);
$check('precheck NOTE about the system-wide GitHub App', $messages->contains(fn ($m) => str_starts_with($m, "NOTE: the system-wide GitHub App 'fake-system-wide-app'")));
$checklist = implode("\n", (array) ($migration['checklist'] ?? []));
$check('checklist: GitHub App URLs', str_contains($checklist, 'GitHub App fake-gh-app'));
diff --git a/scripts/transfer-test/verify-extras-target.php b/scripts/transfer-test/verify-extras-target.php
index b34de610e4..0a5d57a43f 100644
--- a/scripts/transfer-test/verify-extras-target.php
+++ b/scripts/transfer-test/verify-extras-target.php
@@ -42,6 +42,9 @@ $sourceAppId = trim((string) @file_get_contents('/tmp/source-app-id'));
$sameInstanceId = $sourceAppId === (string) config('app.id');
$check('DNS ownership '.($sameInstanceId ? 'kept (same instance ID, no adoption needed)' : 'dropped (fake token cannot adopt)'), $record?->owned === $sameInstanceId);
+$ssh = ManagedDnsRecord::where('name', 'ssh-debian.example.test')->first();
+$check('tunnel SSH DNS record moved with the server', $ssh?->references()->where('resource_type', $server?->getMorphClass())->where('resource_id', $server?->id)->exists() === true && $ssh->owned === $sameInstanceId);
+
$githubApp = GithubApp::where('name', 'fake-gh-app')->first();
$runner = GithubRunnerConfig::where('server_id', $server?->id)->first();
$check('GitHub App moved (only the runner config uses it)', $githubApp !== null && $githubApp->organization === 'fake-org');
diff --git a/tests/Feature/Api/ServerTransferApiTest.php b/tests/Feature/Api/ServerTransferApiTest.php
index c1d9aa536a..b755449333 100644
--- a/tests/Feature/Api/ServerTransferApiTest.php
+++ b/tests/Feature/Api/ServerTransferApiTest.php
@@ -9,9 +9,11 @@ use App\Models\Environment;
use App\Models\EnvironmentVariable;
use App\Models\GithubApp;
use App\Models\InstanceSettings;
+use App\Models\LocalFileVolume;
use App\Models\PrivateKey;
use App\Models\Project;
use App\Models\Server;
+use App\Models\SharedEnvironmentVariable;
use App\Models\StandaloneDocker;
use App\Models\Team;
use App\Models\User;
@@ -164,6 +166,29 @@ describe('POST /api/v1/servers/import', function () {
->toBe('claimed');
});
+ test('keeps whitespace and empty strings of the bundle values', function () {
+ $this->application->forceFill(['dockerfile' => "FROM nginx:alpine\nEXPOSE 80\n", 'build_pack' => 'dockerfile'])->saveQuietly();
+ LocalFileVolume::withoutEvents(fn () => LocalFileVolume::forceCreate([
+ 'uuid' => new_public_id(), 'fs_path' => '/data/coolify/applications/app.yml', 'mount_path' => '/etc/app.yml',
+ 'content' => " indented: true\nlast: line\n", 'resource_type' => Application::class, 'resource_id' => $this->application->id,
+ ]));
+ SharedEnvironmentVariable::create(['key' => 'EMPTY_ON_SERVER', 'value' => '', 'type' => 'server', 'server_id' => $this->server->id, 'team_id' => $this->team->id]);
+ $export = transferExportForApiTest($this->server);
+ $appUuid = $this->application->uuid;
+ $this->application->forceDelete();
+ $this->server->forceDelete();
+ $this->privateKey->delete();
+
+ $this->withHeaders(transferHeaders($this->sensitiveToken))
+ ->postJson('/api/v1/servers/import', ['bundle' => $export])
+ ->assertCreated();
+
+ $imported = Application::where('uuid', $appUuid)->firstOrFail();
+ expect($imported->dockerfile)->toBe("FROM nginx:alpine\nEXPOSE 80\n")
+ ->and($imported->fileStorages()->value('content'))->toBe(" indented: true\nlast: line\n")
+ ->and(SharedEnvironmentVariable::where('key', 'EMPTY_ON_SERVER')->first()?->value)->toBe('');
+ });
+
test('rejects import when ip still exists', function () {
$export = transferExportForApiTest($this->server);
diff --git a/tests/Support/ServerTransferFuzzer.php b/tests/Support/ServerTransferFuzzer.php
new file mode 100644
index 0000000000..731f8be0f1
--- /dev/null
+++ b/tests/Support/ServerTransferFuzzer.php
@@ -0,0 +1,62 @@
+<?php
+
+namespace Tests\Support;
+
+use BackedEnum;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * Gives every column of a record a value that is not the default, so a value that a server transfer
+ * loses shows up in ServerTransferSnapshot::diff(). Keys, foreign keys, and $keep columns stay as they are.
+ */
+final class ServerTransferFuzzer
+{
+ private const KEPT = ['id', 'uuid', 'created_at', 'updated_at', 'deleted_at', 'team_id', 'created_by'];
+
+ /**
+ * @param list<string> $keep
+ * @param array<string, mixed> $values Values to use instead of generated ones.
+ */
+ public static function fill(Model $model, array $keep = [], array $values = []): Model
+ {
+ $casts = $model->getCasts();
+ $fuzzed = [];
+ foreach (Schema::getColumns($model->getTable()) as $column) {
+ $name = $column['name'];
+ $morph = preg_replace('/_(type|id)$/', '', $name);
+ if (in_array($name, [...self::KEPT, ...$keep], true) || isset(ServerTransferSnapshot::FOREIGN_KEYS[$name])
+ || (in_array($morph, ServerTransferSnapshot::MORPHS, true) && Schema::hasColumn($model->getTable(), "{$morph}_type"))) {
+ continue;
+ }
+ $value = self::value($name, strtolower($column['type_name']), (string) ($casts[$name] ?? ''), $column['default'], $model->getAttributes()[$name] ?? null);
+ // Text must fit the column, such as character varying(10).
+ $fuzzed[$name] = is_string($value) && preg_match('/char[a-z ]*\((\d+)\)/', (string) $column['type'], $length) ? substr($value, 0, (int) $length[1]) : $value;
+ }
+ $model->forceFill([...$fuzzed, ...$values]);
+ $model->saveQuietly();
+
+ return $model;
+ }
+
+ private static function value(string $name, string $type, string $cast, mixed $default, mixed $current): mixed
+ {
+ $default = strtolower(trim((string) $default, "'"));
+ $enum = explode(':', $cast)[0];
+ if (enum_exists($enum) && is_subclass_of($enum, BackedEnum::class)) {
+ $cases = $enum::cases();
+ $other = collect($cases)->first(fn (BackedEnum $case) => $case->value !== ($current instanceof BackedEnum ? $current->value : ($current ?? $default)));
+
+ return ($other ?? $cases[0])->value;
+ }
+
+ return match (true) {
+ str_contains($cast, 'array') || str_contains($cast, 'json') || str_contains($cast, 'collection') || str_contains($cast, 'Schemaless') || str_contains($type, 'json') => ['fuzz' => $name],
+ in_array($cast, ['bool', 'boolean'], true) || str_contains($type, 'bool') || in_array($default, ['true', 'false'], true) => ! filter_var($current ?? $default, FILTER_VALIDATE_BOOLEAN),
+ str_contains($cast, 'date') || str_contains($type, 'timestamp') || str_contains($type, 'date') || (str_ends_with($name, '_at') && ! str_contains($type, 'int')) => '2031-02-03 04:05:06',
+ in_array($cast, ['int', 'integer'], true) || str_contains($type, 'int') => (int) ($current ?? $default) + 7,
+ in_array($cast, ['float', 'double', 'decimal'], true) || in_array($type, ['numeric', 'float4', 'float8', 'real', 'double', 'decimal'], true) => (float) ($current ?? $default) + 1.5,
+ default => "fuzz-{$name}",
+ };
+ }
+}
diff --git a/tests/Support/ServerTransferSnapshot.php b/tests/Support/ServerTransferSnapshot.php
new file mode 100644
index 0000000000..f9ef4eb3ca
--- /dev/null
+++ b/tests/Support/ServerTransferSnapshot.php
@@ -0,0 +1,403 @@
+<?php
+
+namespace Tests\Support;
+
+use App\Services\ServerTransfer\ServerTransferCoverage;
+use BackedEnum;
+use DateTimeInterface;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\Relation;
+use Illuminate\Support\Facades\DB;
+use RuntimeException;
+use Throwable;
+
+/**
+ * A portable copy of one server and every record that a server transfer moves, to compare the source
+ * with the target. Rows are keyed by model class and an identity that is the same on both instances
+ * (the uuid, or a key built from the parent). Foreign keys are replaced with the identity of the
+ * referenced row, and encrypted columns are decrypted, so other IDs and APP_KEYs give the same snapshot.
+ *
+ * Used by tests/Unit/ServerTransfer/ServerTransferCoverageTest.php and by the live kit (scripts/transfer-test/snapshot.sh).
+ */
+final class ServerTransferSnapshot
+{
+ /** Belongs-to columns and the table they point to. */
+ public const FOREIGN_KEYS = [
+ 'private_key_id' => 'private_keys', 'server_id' => 'servers', 'environment_id' => 'environments', 'project_id' => 'projects',
+ 'application_id' => 'applications', 'service_id' => 'services', 's3_storage_id' => 's3_storages',
+ 'integration_token_id' => 'integration_tokens', 'cloudflare_tunnel_integration_token_id' => 'integration_tokens',
+ 'dns_provider_zone_id' => 'dns_provider_zones', 'github_app_id' => 'github_apps', 'cloud_provider_token_id' => 'cloud_provider_tokens',
+ 'managed_dns_record_id' => 'managed_dns_records', 'standalone_sqlite_id' => 'standalone_sqlites', 'icon_s3_storage_id' => 's3_storages',
+ 'scheduled_database_backup_id' => 'scheduled_database_backups', 'scheduled_volume_backup_id' => 'scheduled_volume_backups',
+ ];
+
+ /** Polymorphic relations: `<name>_type` + `<name>_id`. */
+ public const MORPHS = ['destination', 'source', 'resourceable', 'resource', 'database', 'backupable', 'taggable', 'target'];
+
+ /** The instance sets these itself; they never match between two instances. */
+ private const IGNORED_COLUMNS = ['id', 'created_at', 'updated_at', 'team_id', 'created_by'];
+
+ private const DATABASE_TABLES = ['standalone_postgresqls', 'standalone_mysqls', 'standalone_mariadbs', 'standalone_mongodbs', 'standalone_redis',
+ 'standalone_keydbs', 'standalone_dragonflies', 'standalone_clickhouses', 'standalone_sqlites'];
+
+ private const RESOURCE_TABLES = ['applications', 'services', 'service_applications', 'service_databases', ...self::DATABASE_TABLES];
+
+ /** Records that a moved record needs. Their own children are not collected. */
+ private const DEPENDENCY_TABLES = ['private_keys', 's3_storages', 'integration_tokens', 'dns_provider_zones', 'github_apps', 'gitlab_apps',
+ 'gitea_apps', 'cloud_provider_tokens', 'environments', 'projects', 'managed_dns_records'];
+
+ /** Values that the live instances change while they manage the resources, not the transfer. */
+ public const LIVE_RUNTIME_COLUMNS = ['last_online_at', 'status', 'docker_version_checked_at', 'compose_version_checked_at', 'started_at', 'config_hash', 'container_present'];
+
+ /** @var array<string, array<int|string, array<string, mixed>>> table => id => row */
+ private array $rows = [];
+
+ /** @var array<string, array<int|string, string>> */
+ private array $identities = [];
+
+ /** @var array<string, class-string<Model>> */
+ private array $classByTable = [];
+
+ /**
+ * @return array<string, array<string, array<string, mixed>>> model class => identity => column => value
+ */
+ public static function take(string $serverUuid): array
+ {
+ return (new self)->collect($serverUuid)->portable();
+ }
+
+ /**
+ * Differences between two snapshots: a row that is missing or extra, or a column that changed.
+ * Columns that ServerTransferCoverage leaves out on purpose, and $alsoExpected columns
+ * ("Class.column" or "column"), are returned as expected with the reason.
+ *
+ * @param array<string, string> $alsoExpected
+ * @return array{unexplained: list<string>, expected: list<string>}
+ */
+ public static function diff(array $before, array $after, array $alsoExpected = []): array
+ {
+ $short = fn (mixed $value) => mb_strimwidth(is_string($value) ? $value : (string) json_encode($value, JSON_UNESCAPED_SLASHES), 0, 160, '…');
+ $result = ['unexplained' => [], 'expected' => []];
+ foreach (array_unique([...array_keys($before), ...array_keys($after)]) as $class) {
+ $name = class_basename($class);
+ foreach (array_unique([...array_keys($before[$class] ?? []), ...array_keys($after[$class] ?? [])]) as $key) {
+ $a = $before[$class][$key] ?? null;
+ $b = $after[$class][$key] ?? null;
+ if ($a === null || $b === null) {
+ $result['unexplained'][] = ($b === null ? 'missing ' : 'extra ')."{$name} {$key}";
+
+ continue;
+ }
+ foreach (array_unique([...array_keys($a), ...array_keys($b)]) as $column) {
+ if (($a[$column] ?? null) === ($b[$column] ?? null)) {
+ continue;
+ }
+ $line = "{$name} {$key} .{$column}: ".$short($a[$column] ?? null).' => '.$short($b[$column] ?? null);
+ $reason = ServerTransferCoverage::NOT_EXPORTED_COLUMNS[$class][$column] ?? $alsoExpected["{$name}.{$column}"] ?? $alsoExpected[$column] ?? match (true) {
+ ($a[$column] ?? '') === ($b[$column] ?? '') => 'No value and an empty text mean the same.',
+ is_string($a[$column] ?? null) && str_starts_with($a[$column], 'system-wide ') && ($b[$column] ?? null) === null => 'A system-wide git source is instance data; the target links its own copy when it has one.',
+ default => null,
+ };
+ if ($reason === null) {
+ $result['unexplained'][] = $line;
+ } else {
+ $result['expected'][] = "{$line} [{$reason}]";
+ }
+ }
+ }
+ }
+
+ return $result;
+ }
+
+ private function __construct()
+ {
+ foreach (array_keys(ServerTransferCoverage::TRANSFERRED) as $class) {
+ $this->classByTable[(new $class)->getTable()] = $class;
+ }
+ }
+
+ /** Children that belong to a parent and move with it: child table => [column or morph => parent tables]. */
+ private function children(): array
+ {
+ $children = [
+ 'server_settings' => ['server_id' => ['servers']],
+ 'standalone_dockers' => ['server_id' => ['servers']],
+ 'swarm_dockers' => ['server_id' => ['servers']],
+ 'ssl_certificates' => ['server_id' => ['servers']],
+ 'github_runner_configs' => ['server_id' => ['servers']],
+ 'applications' => ['destination' => ['standalone_dockers', 'swarm_dockers']],
+ 'services' => ['destination' => ['standalone_dockers', 'swarm_dockers'], 'server_id' => ['servers']],
+ 'application_settings' => ['application_id' => ['applications']],
+ 'application_previews' => ['application_id' => ['applications']],
+ 'scheduled_tasks' => ['application_id' => ['applications'], 'service_id' => ['services']],
+ 'service_applications' => ['service_id' => ['services']],
+ 'service_databases' => ['service_id' => ['services']],
+ 'environment_variables' => ['resourceable' => self::RESOURCE_TABLES],
+ 'local_persistent_volumes' => ['resource' => [...self::RESOURCE_TABLES, 'application_previews']],
+ 'local_file_volumes' => ['resource' => self::RESOURCE_TABLES],
+ 'secret_manager_links' => ['resourceable' => self::RESOURCE_TABLES],
+ 'scheduled_database_backups' => ['database' => [...self::DATABASE_TABLES, 'service_databases']],
+ 'scheduled_volume_backups' => ['backupable' => [...self::RESOURCE_TABLES, 'local_persistent_volumes']],
+ 'managed_dns_record_references' => ['resource' => self::RESOURCE_TABLES],
+ 'resource_links' => ['source' => self::RESOURCE_TABLES],
+ 'shared_environment_variables' => ['server_id' => ['servers'], 'project_id' => ['projects'], 'environment_id' => ['environments']],
+ 'scheduled_database_backup_s3_storage' => ['scheduled_database_backup_id' => ['scheduled_database_backups']],
+ 'scheduled_volume_backup_s3_storage' => ['scheduled_volume_backup_id' => ['scheduled_volume_backups']],
+ ];
+ foreach (self::DATABASE_TABLES as $table) {
+ $children[$table] = ['destination' => ['standalone_dockers', 'swarm_dockers']];
+ }
+
+ return $children;
+ }
+
+ private function collect(string $serverUuid): self
+ {
+ $server = DB::table('servers')->where('uuid', $serverUuid)->first() ?? throw new RuntimeException("No server {$serverUuid}");
+ $this->add('servers', [$server]);
+ do {
+ $new = $this->collectChildren() + $this->collectDependencies() + $this->collectTags();
+ } while ($new > 0);
+
+ return $this;
+ }
+
+ private function collectChildren(): int
+ {
+ $new = 0;
+ foreach ($this->children() as $childTable => $links) {
+ foreach ($links as $link => $parentTables) {
+ foreach ($parentTables as $parentTable) {
+ $parentIds = array_keys($this->rows[$parentTable] ?? []);
+ if ($parentIds === []) {
+ continue;
+ }
+ $query = DB::table($childTable);
+ if (str_ends_with($link, '_id')) {
+ $query->whereIn($link, $parentIds);
+ if ($childTable === 'shared_environment_variables') {
+ $query->where('type', ['server_id' => 'server', 'project_id' => 'project', 'environment_id' => 'environment'][$link]);
+ }
+ } else {
+ $types = $this->morphTypesOf($childTable, $link, $parentTable);
+ if ($types === []) {
+ continue;
+ }
+ $query->whereIn("{$link}_type", $types)->whereIn("{$link}_id", $parentIds);
+ }
+ $new += $this->add($childTable, $query->get());
+ }
+ }
+ }
+
+ return $new;
+ }
+
+ private function collectDependencies(): int
+ {
+ $new = 0;
+ foreach ($this->rows as $tableRows) {
+ foreach ($tableRows as $row) {
+ foreach ($row as $column => $value) {
+ $target = self::FOREIGN_KEYS[$column] ?? null;
+ if ($value !== null && in_array($target, self::DEPENDENCY_TABLES, true)) {
+ $new += $this->add($target, DB::table($target)->where('id', $value)->get());
+ }
+ $morph = str_ends_with($column, '_type') ? substr($column, 0, -5) : null;
+ if ($morph !== null && in_array($morph, self::MORPHS, true) && isset($row["{$morph}_id"])) {
+ $target = $this->morphTable($value);
+ if (in_array($target, self::DEPENDENCY_TABLES, true)) {
+ $new += $this->add($target, DB::table($target)->where('id', $row["{$morph}_id"])->get());
+ }
+ }
+ }
+ }
+ }
+ $recordIds = collect($this->rows['managed_dns_record_references'] ?? [])->pluck('managed_dns_record_id')->all();
+
+ return $new + $this->add('managed_dns_records', DB::table('managed_dns_records')->whereIn('id', $recordIds)->get());
+ }
+
+ private function collectTags(): int
+ {
+ $new = 0;
+ foreach (self::RESOURCE_TABLES as $resourceTable) {
+ $ids = array_keys($this->rows[$resourceTable] ?? []);
+ $types = $this->morphTypesOf('taggables', 'taggable', $resourceTable);
+ if ($ids === [] || $types === []) {
+ continue;
+ }
+ foreach (DB::table('taggables')->whereIn('taggable_type', $types)->whereIn('taggable_id', $ids)->get() as $pivot) {
+ $key = "{$pivot->taggable_type}|{$pivot->taggable_id}|{$pivot->tag_id}";
+ if (! isset($this->rows['taggables'][$key])) {
+ $this->rows['taggables'][$key] = ['id' => $key, ...((array) $pivot)];
+ $new++;
+ }
+ $new += $this->add('tags', DB::table('tags')->where('id', $pivot->tag_id)->get());
+ }
+ }
+
+ return $new;
+ }
+
+ /** @return list<string> */
+ private function morphTypesOf(string $table, string $morph, string $parentTable): array
+ {
+ return DB::table($table)->distinct()->pluck("{$morph}_type")
+ ->filter(fn (?string $type) => $this->morphTable($type) === $parentTable)->values()->all();
+ }
+
+ private function add(string $table, iterable $found): int
+ {
+ $new = 0;
+ foreach ($found as $row) {
+ $row = (array) $row;
+ if (! empty($row['is_system_wide'])) {
+ continue;
+ }
+ if (($row['deleted_at'] ?? null) === null && ! isset($this->rows[$table][$row['id']])) {
+ $this->rows[$table][$row['id']] = $row;
+ $new++;
+ }
+ }
+
+ return $new;
+ }
+
+ private function morphTable(?string $type): ?string
+ {
+ if ($type === null) {
+ return null;
+ }
+ $class = Relation::getMorphedModel($type) ?? $type;
+
+ return array_search($class, $this->classByTable, true) ?: (class_exists($class) ? (new $class)->getTable() : null);
+ }
+
+ private function identity(string $table, int|string|null $id): ?string
+ {
+ if ($id === null) {
+ return null;
+ }
+ if (isset($this->identities[$table][$id])) {
+ return $this->identities[$table][$id];
+ }
+ $row = $this->rows[$table][$id] ?? (array) (DB::table($table)->where('id', $id)->first() ?? []);
+ if ($row === []) {
+ return "{$table}#missing";
+ }
+ $morph = fn (string $name) => $this->morphTable($row["{$name}_type"] ?? null).':'.$this->identity((string) $this->morphTable($row["{$name}_type"] ?? null), $row["{$name}_id"] ?? null);
+
+ return $this->identities[$table][$id] = match (true) {
+ ! empty($row['uuid']) => $row['uuid'],
+ $table === 'server_settings' => 'settings of '.$this->identity('servers', $row['server_id']),
+ $table === 'application_settings' => 'settings of '.$this->identity('applications', $row['application_id']),
+ $table === 'ssl_certificates' => $this->identity('servers', $row['server_id']).'|'.($row['is_ca_certificate'] ? 'CA' : $morph('resource')).'|'.$row['common_name'],
+ $table === 'shared_environment_variables' => $row['type'].'|'.match ($row['type']) {
+ 'server' => $this->identity('servers', $row['server_id']),
+ 'project' => $this->identity('projects', $row['project_id']),
+ 'environment' => $this->identity('environments', $row['environment_id']),
+ default => 'team',
+ }.'|'.$row['key'],
+ $table === 'managed_dns_record_references' => $this->identity('managed_dns_records', $row['managed_dns_record_id']).'|'.$morph('resource'),
+ $table === 'taggables' => $morph('taggable').'|'.$this->identity('tags', $row['tag_id']),
+ $table === 'tags' => 'tag '.$row['name'],
+ $table === 'scheduled_database_backup_s3_storage' => $this->identity('scheduled_database_backups', $row['scheduled_database_backup_id']).'|'.$this->identity('s3_storages', $row['s3_storage_id']),
+ $table === 'scheduled_volume_backup_s3_storage' => $this->identity('scheduled_volume_backups', $row['scheduled_volume_backup_id']).'|'.$this->identity('s3_storages', $row['s3_storage_id']),
+ default => "{$table}#{$id}",
+ };
+ }
+
+ private function portable(): array
+ {
+ $snapshot = [];
+ foreach ($this->rows as $table => $tableRows) {
+ $class = $this->classByTable[$table] ?? $table;
+ $model = class_exists($class) ? new $class : null;
+ foreach ($tableRows as $id => $row) {
+ if ($table === 'resource_links' && ! isset($this->rows[$this->morphTable($row['target_type'])][$row['target_id']])) {
+ continue;
+ }
+ $values = [];
+ foreach ($row as $column => $value) {
+ if (in_array($column, self::IGNORED_COLUMNS, true) || $table === 'taggables') {
+ continue;
+ }
+ $morph = preg_replace('/_(type|id)$/', '', $column);
+ if (in_array($morph, self::MORPHS, true) && array_key_exists("{$morph}_type", $row) && array_key_exists("{$morph}_id", $row)) {
+ if (str_ends_with($column, '_type')) {
+ $target = $this->morphTable($value);
+ $systemWide = in_array($target, ['github_apps', 'gitlab_apps', 'gitea_apps'], true)
+ && DB::table($target)->where('id', $row["{$morph}_id"])->value('is_system_wide');
+ $values[$morph] = $target === null ? null : ($systemWide ? 'system-wide ' : '').$target.':'.$this->identity($target, $row["{$morph}_id"]);
+ }
+
+ continue;
+ }
+ if (isset(self::FOREIGN_KEYS[$column])) {
+ $values[$column] = $value === null ? null : self::FOREIGN_KEYS[$column].':'.$this->identity(self::FOREIGN_KEYS[$column], $value);
+
+ continue;
+ }
+ $values[$column] = $this->normalize($this->decrypted($model, $row, $column, $value));
+ }
+ ksort($values);
+ $key = $this->identity($table, $id);
+ // Two rows with one identity (for example two variables with the same key) must not hide each other.
+ for ($n = 2; isset($snapshot[$class][$key]); $n++) {
+ $key = $this->identity($table, $id)." (duplicate {$n})";
+ }
+ $snapshot[$class][$key] = $values;
+ }
+ }
+ ksort($snapshot);
+
+ return array_map(function (array $rows) {
+ ksort($rows);
+
+ return $rows;
+ }, $snapshot);
+ }
+
+ private function decrypted(?Model $model, array $row, string $column, mixed $value): mixed
+ {
+ $cast = (string) ($model?->getCasts()[$column] ?? '');
+ $looksEncrypted = is_string($value) && str_starts_with($value, 'eyJpdiI6');
+ if ($value === null || ! ($looksEncrypted || str_starts_with($cast, 'encrypted'))) {
+ return $value;
+ }
+ try {
+ return str_starts_with($cast, 'encrypted') ? $model->newFromBuilder($row)->getAttribute($column) : decrypt($value, false);
+ } catch (Throwable) {
+ try {
+ return decrypt($value);
+ } catch (Throwable $e) {
+ return 'UNDECRYPTABLE: '.$e->getMessage();
+ }
+ }
+ }
+
+ private function normalize(mixed $value): mixed
+ {
+ if (is_string($value) && $value !== '' && in_array($value[0], ['{', '['], true)) {
+ $decoded = json_decode($value, true);
+ if (json_last_error() === JSON_ERROR_NONE) {
+ $value = $decoded;
+ }
+ }
+ if (is_array($value)) {
+ if (! array_is_list($value)) {
+ ksort($value);
+ }
+
+ return array_map(fn ($item) => $this->normalize($item), $value);
+ }
+
+ return match (true) {
+ $value instanceof BackedEnum => $value->value,
+ $value instanceof DateTimeInterface => $value->format('Y-m-d H:i:s'),
+ default => $value,
+ };
+ }
+}
diff --git a/tests/Unit/ServerTransfer/ServerTransferCoverageTest.php b/tests/Unit/ServerTransfer/ServerTransferCoverageTest.php
index 82448a4b6b..29ddb8df11 100644
--- a/tests/Unit/ServerTransfer/ServerTransferCoverageTest.php
+++ b/tests/Unit/ServerTransfer/ServerTransferCoverageTest.php
@@ -33,15 +33,19 @@ use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
use App\Models\Tag;
use App\Models\Team;
+use App\Models\User;
use App\Services\ServerTransfer\ServerTransferCoverage;
use App\Services\ServerTransfer\ServerTransferExporter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Arr;
+use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
+use Tests\Support\ServerTransferFuzzer;
+use Tests\Support\ServerTransferSnapshot;
use Tests\TestCase;
uses(TestCase::class, RefreshDatabase::class);
@@ -209,3 +213,62 @@ test('every column of a transferred model is in the bundle or has a reason why n
->and(array_values(array_diff(array_keys(ServerTransferCoverage::NOT_EXPORTED_COLUMNS[$modelClass] ?? []), $columns)))
->toBe([], "These {$modelClass} columns no longer exist, so remove them from ServerTransferCoverage::NOT_EXPORTED_COLUMNS.");
})->with(array_keys(ServerTransferCoverage::TRANSFERRED));
+
+test('every exported value arrives unchanged on the target', function () {
+ $keep = [
+ Server::class => ['ip', 'port', 'user', 'name'],
+ PrivateKey::class => ['private_key', 'fingerprint'],
+ GithubApp::class => ['is_system_wide'],
+ GitlabApp::class => ['is_system_wide'],
+ GiteaApp::class => ['is_system_wide'],
+ EnvironmentVariable::class => ['key', 'value', 'is_preview'],
+ SharedEnvironmentVariable::class => ['key', 'type'],
+ Environment::class => ['canvas_positions'],
+ ];
+ $values = [
+ Server::class => ['proxy' => ['type' => 'TRAEFIK', 'status' => 'running', 'redirect_enabled' => false, 'redirect_url' => 'https://fuzz.example.test']],
+ Application::class => ['fqdn' => 'https://fuzz-a.example.test,https://fuzz-b.example.test', 'domain_port_overrides' => null, 'noindex_domains' => ['https://fuzz-b.example.test']],
+ ApplicationPreview::class => ['fqdn' => 'https://pr-fuzz.example.test', 'domain_port_overrides' => null],
+ ServiceApplication::class => ['fqdn' => 'https://fuzz-service.example.test', 'domain_port_overrides' => null, 'noindex_domains' => []],
+ GithubRunnerConfig::class => ['labels' => ['fuzz-label'], 'max_runners' => 5, 'runner_image' => 'ghcr.io/fuzz/runner:2', 'cpu_limit' => '1.5', 'memory_limit' => '2g', 'capacity_wait_timeout' => 33, 'idle_timeout' => 44, 'job_timeout' => 55],
+ LocalFileVolume::class => ['fs_path' => '/data/coolify/applications/fuzz/app.conf', 'mount_path' => '/etc/fuzz/app.conf', 'chown' => '1000:1000', 'chmod' => '0640'],
+ ];
+ foreach (array_keys(ServerTransferCoverage::TRANSFERRED) as $class) {
+ $class::query()->withoutGlobalScopes()->get()
+ // Coolify sets the predefined server variables itself.
+ ->reject(fn (Model $record) => $record instanceof SharedEnvironmentVariable && str_starts_with($record->key, 'COOLIFY_'))
+ ->each(fn (Model $record) => ServerTransferFuzzer::fill($record, $keep[$class] ?? [], $values[$class] ?? []));
+ }
+ $s3 = S3Storage::query()->firstOrFail();
+ ScheduledDatabaseBackup::query()->firstOrFail()->s3Storages()->attach($s3->id);
+ ScheduledVolumeBackup::query()->firstOrFail()->s3Storages()->attach($s3->id);
+ // Coolify sets is_shared when it saves a variable.
+ EnvironmentVariable::query()->get()->each(fn (EnvironmentVariable $variable) => $variable->forceFill(['is_shared' => $variable->is_shared])->saveQuietly());
+ $teamId = $this->server->team_id;
+ $user = User::factory()->create();
+ Team::find($teamId)->members()->attach($user->id, ['role' => 'owner']);
+ session(['currentTeam' => Team::find($teamId)]);
+ $token = $user->createToken('round-trip', ['*', 'read:sensitive'])->plainTextToken;
+ $before = ServerTransferSnapshot::take($this->server->uuid);
+ $bundle = app(ServerTransferExporter::class)->export($this->server->fresh());
+
+ Schema::disableForeignKeyConstraints();
+ foreach (array_keys(ServerTransferCoverage::TRANSFERRED) as $class) {
+ DB::table((new $class)->getTable())->delete();
+ }
+ foreach (['taggables', 'scheduled_database_backup_s3_storage', 'scheduled_volume_backup_s3_storage'] as $pivot) {
+ DB::table($pivot)->delete();
+ }
+ Schema::enableForeignKeyConstraints();
+ Server::flushIdentityMap();
+
+ $response = $this->withHeaders(['Authorization' => "Bearer {$token}", 'Accept' => 'application/json'])
+ ->postJson('/api/v1/servers/import', ['bundle' => $bundle]);
+ expect($response->status())->toBe(201, (string) $response->json('message'));
+
+ $changedOnPurpose = [
+ 'last_online_at' => 'The import sets the status, which sets the time.',
+ 'GithubRunnerConfig.is_enabled' => 'The target disables the runners until the user enables them.',
+ ];
+ expect(ServerTransferSnapshot::diff($before, ServerTransferSnapshot::take($this->server->uuid), $changedOnPurpose)['unexplained'])->toBe([]);
+});
diff --git a/tests/Unit/ServerTransfer/ServerTransferDnsTest.php b/tests/Unit/ServerTransfer/ServerTransferDnsTest.php
index 3dc6aedef1..e2d496c818 100644
--- a/tests/Unit/ServerTransfer/ServerTransferDnsTest.php
+++ b/tests/Unit/ServerTransfer/ServerTransferDnsTest.php
@@ -248,3 +248,17 @@ test('the target does not own a record it cannot adopt and the import still succ
])],
'the provider cannot be reached' => [fn (ManagedDnsRecord $record) => Http::fake(fn () => throw new ConnectionException('Connection refused'))],
]);
+
+test('the DNS record of the Cloudflare tunnel moves with the server', function () {
+ $this->server->settings->forceFill(['is_cloudflare_tunnel' => true, 'cloudflare_tunnel_id' => 'tun-1', 'cloudflare_tunnel_integration_token_id' => $this->cloudflareToken->id])->saveQuietly();
+ $record = dnsTransferRecord($this, 'ssh.example.com', [$this->server]);
+ $bundle = $this->exporter->export($this->server->fresh());
+
+ removeDnsTransferSource($this);
+ $this->importer->import($bundle, teamId: $this->team->id);
+
+ $imported = ManagedDnsRecord::where('name', 'ssh.example.com')->firstOrFail();
+ $server = Server::where('uuid', $this->server->uuid)->firstOrFail();
+ expect($imported->uuid)->toBe($record->uuid)
+ ->and($imported->references()->where('resource_type', $server->getMorphClass())->where('resource_id', $server->id)->exists())->toBeTrue();
+});
diff --git a/tests/Unit/ServerTransfer/ServerTransferExporterImporterTest.php b/tests/Unit/ServerTransfer/ServerTransferExporterImporterTest.php
index 2e9610d31f..0e656a35e7 100644
--- a/tests/Unit/ServerTransfer/ServerTransferExporterImporterTest.php
+++ b/tests/Unit/ServerTransfer/ServerTransferExporterImporterTest.php
@@ -29,6 +29,7 @@ use App\Models\SharedEnvironmentVariable;
use App\Models\StandaloneDocker;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneSqlite;
+use App\Models\SwarmDocker;
use App\Models\Tag;
use App\Models\Team;
use App\Models\User;
@@ -341,6 +342,71 @@ test('round trip import preserves uuids secrets and related resources after sour
->and($shared->value)->toBe('shared-secret');
});
+test('an imported application and service keep their compose parser version and their variables', function () {
+ $this->application->forceFill(['build_pack' => 'nixpacks', 'compose_parsing_version' => '3'])->saveQuietly();
+ EnvironmentVariable::updateOrCreate(['key' => 'NIXPACKS_NODE_VERSION', 'resourceable_type' => $this->application->getMorphClass(), 'resourceable_id' => $this->application->id], ['value' => '18']);
+ $this->service->forceFill(['compose_parsing_version' => '3'])->saveQuietly();
+ $bundle = $this->exporter->export($this->server);
+ $applicationUuid = $this->application->uuid;
+ $serviceUuid = $this->service->uuid;
+ removeTransferSourceResources($this);
+
+ $this->importer->import($bundle, teamId: Team::factory()->create()->id);
+
+ $application = Application::where('uuid', $applicationUuid)->firstOrFail();
+ expect($application->compose_parsing_version)->toBe('3')
+ ->and(Service::where('uuid', $serviceUuid)->value('compose_parsing_version'))->toBe('3')
+ ->and($application->environment_variables()->where('key', 'NIXPACKS_NODE_VERSION')->pluck('value')->all())->toBe(['18']);
+});
+
+test('a static application keeps the port that the user set after turning on static', function () {
+ $this->application->settings->forceFill(['is_static' => true])->save();
+ $this->application->refresh()->forceFill(['ports_exposes' => '8080'])->saveQuietly();
+ $bundle = $this->exporter->export($this->server);
+ $applicationUuid = $this->application->uuid;
+ removeTransferSourceResources($this);
+
+ $this->importer->import($bundle, teamId: Team::factory()->create()->id);
+
+ $application = Application::where('uuid', $applicationUuid)->firstOrFail();
+ expect($application->ports_exposes)->toBe('8080')
+ ->and($application->settings->is_static)->toBeTrue();
+});
+
+test('a swarm server gets only the destinations of the bundle', function () {
+ $swarm = (new SwarmDocker)->forceFill(['uuid' => new_public_id(), 'name' => 'swarm', 'network' => 'swarm-overlay', 'server_id' => $this->server->id]);
+ $swarm->saveQuietly();
+ foreach ([$this->application, $this->database, $this->service] as $resource) {
+ $resource->forceFill(['destination_type' => $swarm->getMorphClass(), 'destination_id' => $swarm->id])->saveQuietly();
+ }
+ $this->destination->delete();
+ $this->server->settings->forceFill(['is_swarm_manager' => true])->saveQuietly();
+ $bundle = $this->exporter->export($this->server->fresh());
+ $serverUuid = $this->server->uuid;
+ removeTransferSourceResources($this);
+
+ $this->importer->import($bundle, teamId: Team::factory()->create()->id);
+
+ $server = Server::where('uuid', $serverUuid)->firstOrFail();
+ expect($server->standaloneDockers()->count())->toBe(0)
+ ->and($server->swarmDockers()->pluck('network')->all())->toBe(['swarm-overlay']);
+});
+
+test('variables with a legacy key that new variables cannot use move unchanged', function () {
+ $variable = EnvironmentVariable::create(['key' => 'LEGACY_KEY', 'value' => 'legacy', 'resourceable_type' => $this->application->getMorphClass(), 'resourceable_id' => $this->application->id]);
+ DB::table('environment_variables')->where('id', $variable->id)->update(['key' => 'legacy-key']);
+ $shared = SharedEnvironmentVariable::create(['type' => 'server', 'server_id' => $this->server->id, 'team_id' => $this->team->id, 'key' => 'LEGACY_SHARED', 'value' => 'shared']);
+ DB::table('shared_environment_variables')->where('id', $shared->id)->update(['key' => 'legacy-shared']);
+ $bundle = $this->exporter->export($this->server);
+ $applicationUuid = $this->application->uuid;
+ removeTransferSourceResources($this);
+
+ $this->importer->import($bundle, teamId: Team::factory()->create()->id);
+
+ expect(Application::where('uuid', $applicationUuid)->firstOrFail()->environment_variables()->where('key', 'legacy-key')->value('value'))->toBe('legacy')
+ ->and(SharedEnvironmentVariable::where('key', 'legacy-shared')->value('value'))->toBe('shared');
+});
+
test('import validates the claimed server in the background, but a dry run does not', function () {
$bundle = $this->exporter->export($this->server);
$serverUuid = $this->server->uuid;
diff --git a/tests/Unit/ServerTransfer/ServerTransferMigratorTest.php b/tests/Unit/ServerTransfer/ServerTransferMigratorTest.php
index 914b416170..2c94b5cb1e 100644
--- a/tests/Unit/ServerTransfer/ServerTransferMigratorTest.php
+++ b/tests/Unit/ServerTransfer/ServerTransferMigratorTest.php
@@ -654,13 +654,21 @@ test('transfer back asks the managing instance to transfer the archive here with
$token = $user->tokens()->sole();
expect((int) $token->team_id)->toBe($this->team->id)
- ->and($token->abilities)->toBe(['read', 'write'])
->and($token->expires_at->isFuture())->toBeTrue()
->and(data_get($this->server->fresh()->server_metadata, 'transfer.transfer_back.from'))->toBe('https://8.8.8.8');
- Http::assertSent(fn ($request) => $request->url() === "https://8.8.8.8/api/v1/servers/{$this->server->uuid}/migrate"
- && $request->hasHeader('Authorization', 'Bearer token-of-b')
- && $request['target_url'] === 'https://coolify-a.test'
- && str_starts_with((string) $request['target_token'], $token->id.'|'));
+ $importToken = null;
+ Http::assertSent(function ($request) use ($token, &$importToken) {
+ $importToken = (string) $request['target_token'];
+
+ return $request->url() === "https://8.8.8.8/api/v1/servers/{$this->server->uuid}/migrate"
+ && $request->hasHeader('Authorization', 'Bearer token-of-b')
+ && $request['target_url'] === 'https://coolify-a.test'
+ && str_starts_with($importToken, $token->id.'|');
+ });
+ // The other instance runs the import checks and the import with this token. An empty bundle fails only the validation.
+ $this->withHeaders(['Authorization' => "Bearer {$importToken}", 'Accept' => 'application/json'])
+ ->postJson('/api/v1/servers/import', ['bundle' => []])
+ ->assertStatus(422);
});
test('a refused transfer back deletes the token and shows the reason of the other instance', function () {
diff --git a/tests/Unit/ServerTransfer/TransferredServerArchiveTest.php b/tests/Unit/ServerTransfer/TransferredServerArchiveTest.php
new file mode 100644
index 0000000000..4da9f4587d
--- /dev/null
+++ b/tests/Unit/ServerTransfer/TransferredServerArchiveTest.php
@@ -0,0 +1,236 @@
+<?php
+
+use App\Actions\Server\DeleteServer;
+use App\Jobs\CheckMissingDatabaseBackupsJob;
+use App\Jobs\CheckMissingVolumeBackupsJob;
+use App\Jobs\ServerCloudProviderStatusCheckJob;
+use App\Jobs\ServerManagerJob;
+use App\Livewire\Server\CloudflareTunnel;
+use App\Livewire\Server\Show;
+use App\Models\Application;
+use App\Models\CloudProviderToken;
+use App\Models\DnsProviderZone;
+use App\Models\Environment;
+use App\Models\InstanceSettings;
+use App\Models\IntegrationToken;
+use App\Models\LocalPersistentVolume;
+use App\Models\ManagedDnsRecord;
+use App\Models\PrivateKey;
+use App\Models\Project;
+use App\Models\ScheduledDatabaseBackup;
+use App\Models\ScheduledVolumeBackup;
+use App\Models\Server;
+use App\Models\StandaloneDocker;
+use App\Models\StandalonePostgresql;
+use App\Models\Team;
+use App\Models\User;
+use App\Notifications\Database\BackupMissing;
+use App\Services\CloudflareTunnelService;
+use App\Services\Dns\CloudflareDnsProvider;
+use App\Services\ServerTransfer\ServerTransferClaimer;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Carbon;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Notification;
+use Illuminate\Support\Facades\Process;
+use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Facades\Storage;
+use Livewire\Livewire;
+use Tests\TestCase;
+
+uses(TestCase::class, RefreshDatabase::class);
+
+/**
+ * On the source, a transferred server is only an archive: another instance manages the host, its cloud server,
+ * its Cloudflare tunnel, and its DNS records.
+ */
+beforeEach(function () {
+ Server::flushIdentityMap();
+ Process::fake();
+ Storage::fake('ssh-keys');
+ config()->set('app.maintenance.store', 'array');
+ InstanceSettings::forceCreate(['id' => 0, 'is_api_enabled' => true, 'instance_timezone' => 'UTC']);
+
+ $this->team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ $this->cloudToken = CloudProviderToken::factory()->create(['team_id' => $this->team->id, 'provider' => 'hetzner']);
+ $this->server = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'private_key_id' => PrivateKey::factory()->create(['team_id' => $this->team->id])->id,
+ 'ip' => '203.0.113.10',
+ 'hetzner_server_id' => 4242,
+ 'cloud_provider_token_id' => $this->cloudToken->id,
+ ]);
+ $destination = StandaloneDocker::where('server_id', $this->server->id)->firstOrFail();
+ $environment = Environment::factory()->create(['project_id' => Project::factory()->create(['team_id' => $this->team->id])->id]);
+ $this->application = Application::factory()->create([
+ 'environment_id' => $environment->id, 'destination_id' => $destination->id, 'destination_type' => $destination->getMorphClass(),
+ 'fqdn' => 'https://shop.example.com',
+ ]);
+ $this->cloudflare = IntegrationToken::factory()->create(['team_id' => $this->team->id, 'provider' => 'cloudflare', 'token' => 'cf', 'capabilities' => ['dns', 'tunnel']]);
+ $this->zone = DnsProviderZone::factory()->create(['integration_token_id' => $this->cloudflare->id, 'provider_zone_id' => 'zone-1', 'name' => 'example.com', 'account_id' => 'acc-1']);
+});
+
+function archiveTransferredServer(Server $server): Server
+{
+ app(ServerTransferClaimer::class)->markTransferred($server, targetInstanceUrl: 'https://target.test');
+
+ return Server::query()->with('settings')->findOrFail($server->id);
+}
+
+test('the API does not delete the cloud server of an archive', function () {
+ Http::fake();
+ $server = archiveTransferredServer($this->server);
+ session(['currentTeam' => $this->team]);
+ $token = $this->user->createToken('api', ['*'])->plainTextToken;
+
+ $this->withHeaders(['Authorization' => "Bearer {$token}", 'Accept' => 'application/json'])
+ ->deleteJson("/api/v1/servers/{$server->uuid}?delete_from_provider=true")
+ ->assertStatus(422);
+
+ Http::assertNothingSent();
+ expect(Server::whereKey($server->id)->exists())->toBeTrue();
+});
+
+test('the API deletes only the records of an archive, like the server page', function () {
+ Http::fake();
+ Queue::fake();
+ $server = archiveTransferredServer($this->server);
+ session(['currentTeam' => $this->team]);
+ $token = $this->user->createToken('api', ['*'])->plainTextToken;
+
+ $this->withHeaders(['Authorization' => "Bearer {$token}", 'Accept' => 'application/json'])
+ ->deleteJson("/api/v1/servers/{$server->uuid}")
+ ->assertOk();
+
+ expect(Server::withTrashed()->whereKey($server->id)->exists())->toBeFalse()
+ ->and(Application::withTrashed()->whereKey($this->application->id)->exists())->toBeFalse();
+ Http::assertNothingSent();
+ Process::assertNothingRan();
+ Queue::assertNotPushed(DeleteServer::class);
+});
+
+test('the delete action never deletes the cloud server of an archive', function () {
+ Http::fake();
+ $server = archiveTransferredServer($this->server);
+ $server->delete();
+
+ DeleteServer::run($server->id, true, 4242, $this->cloudToken->id, $this->team->id);
+
+ Http::assertNothingSent();
+});
+
+test('the server page does not power on the cloud server of an archive', function () {
+ Http::fake();
+ $server = archiveTransferredServer($this->server);
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->team]);
+
+ Livewire::test(Show::class, ['server_uuid' => $server->uuid])->call('startHetznerServer');
+
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/actions/poweron'));
+});
+
+test('the Cloudflare tunnel of an archive is not changed at Cloudflare', function () {
+ Http::fake();
+ $this->server->settings->forceFill(['is_cloudflare_tunnel' => true, 'cloudflare_tunnel_id' => 'tun-1', 'cloudflare_tunnel_account_id' => 'acc-1', 'cloudflare_tunnel_integration_token_id' => $this->cloudflare->id])->saveQuietly();
+ $server = archiveTransferredServer($this->server);
+ $tunnels = app(CloudflareTunnelService::class);
+
+ $warnings = $tunnels->tearDown($server);
+
+ expect($warnings)->toBe(['This server is managed by another Coolify instance.'])
+ ->and(fn () => $tunnels->setUp($server, $this->cloudflare, 'ssh.example.com'))->toThrow(RuntimeException::class, 'managed by another Coolify instance')
+ ->and($server->fresh()->settings->cloudflare_tunnel_id)->toBe('tun-1');
+ Http::assertNothingSent();
+});
+
+test('the tunnel settings of an archive cannot disable its Cloudflare tunnel', function () {
+ Http::fake();
+ $this->server->settings->forceFill(['is_cloudflare_tunnel' => true, 'cloudflare_tunnel_id' => 'tun-1', 'cloudflare_tunnel_account_id' => 'acc-1', 'cloudflare_tunnel_integration_token_id' => $this->cloudflare->id])->saveQuietly();
+ $server = archiveTransferredServer($this->server);
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->team]);
+
+ Livewire::test(CloudflareTunnel::class, ['server_uuid' => $server->uuid])->call('toggleCloudflareTunnels');
+
+ expect((bool) $server->fresh()->settings->is_cloudflare_tunnel)->toBeTrue();
+ Http::assertNothingSent();
+});
+
+test('DNS records of the resources of an archive are not created or replaced', function () {
+ fakeCloudflareDns();
+ archiveTransferredServer($this->server);
+ $dns = app(CloudflareDnsProvider::class);
+
+ expect(fn () => $dns->createRecord($this->zone, 'shop.example.com', '203.0.113.10', $this->application->fresh()))
+ ->toThrow(RuntimeException::class, 'managed by another Coolify instance')
+ ->and(fn () => $dns->replaceRecord($this->zone, 'record-1', 'shop.example.com', '203.0.113.10', $this->application->fresh()))
+ ->toThrow(RuntimeException::class, 'managed by another Coolify instance')
+ ->and(sentDnsRequests('POST') + sentDnsRequests('PUT') + sentDnsRequests('PATCH'))->toBe(0);
+});
+
+test('scp does not connect to an archive', function () {
+ $server = archiveTransferredServer($this->server);
+
+ expect(fn () => instant_scp('/tmp/local-file', '/tmp/remote-file', $server))->toThrow(RuntimeException::class, 'Server is disabled.');
+
+ Process::assertNothingRan();
+});
+
+test('the source keeps the DNS record of the Cloudflare tunnel only for a take back', function () {
+ $record = ManagedDnsRecord::factory()->owned()->create(['team_id' => $this->team->id, 'dns_provider_zone_id' => $this->zone->id, 'integration_token_id' => $this->cloudflare->id, 'name' => 'ssh.example.com']);
+ $record->addReference($this->server);
+
+ archiveTransferredServer($this->server);
+
+ expect($record->fresh()->owned)->toBeFalse();
+});
+
+test('missing backups of an archive are not reported', function () {
+ Notification::fake();
+ $this->team->emailNotificationSettings->update(['smtp_enabled' => true, 'backup_failure_email_notifications' => true]);
+ $database = StandalonePostgresql::withoutEvents(fn () => StandalonePostgresql::forceCreate([
+ 'uuid' => new_public_id(), 'name' => 'archived-db', 'postgres_password' => 'secret',
+ 'environment_id' => $this->application->environment_id, 'destination_id' => $this->application->destination_id, 'destination_type' => $this->application->destination_type,
+ ]));
+ $backup = ScheduledDatabaseBackup::create([
+ 'enabled' => true, 'frequency' => '0 0 * * *', 'save_s3' => false, 'team_id' => $this->team->id, 'missing_backup_notification_days' => 2,
+ 'database_type' => $database->getMorphClass(), 'database_id' => $database->id,
+ ]);
+ ScheduledDatabaseBackup::whereKey($backup->id)->update(['created_at' => now()->subDays(3)]);
+ archiveTransferredServer($this->server);
+
+ (new CheckMissingDatabaseBackupsJob)->handle();
+
+ Notification::assertNotSentTo($this->team, BackupMissing::class);
+});
+
+test('missing volume backups of an archive are not reported', function () {
+ Notification::fake();
+ $this->team->emailNotificationSettings->update(['smtp_enabled' => true, 'backup_failure_email_notifications' => true]);
+ $volume = LocalPersistentVolume::create(['name' => 'archived-data', 'mount_path' => '/data', 'resource_type' => $this->application->getMorphClass(), 'resource_id' => $this->application->id]);
+ $backup = ScheduledVolumeBackup::create([
+ 'backupable_type' => $volume->getMorphClass(), 'backupable_id' => $volume->id, 'team_id' => $this->team->id,
+ 'frequency' => '0 0 * * *', 'enabled' => true, 'missing_backup_notification_days' => 2,
+ ]);
+ ScheduledVolumeBackup::whereKey($backup->id)->update(['created_at' => now()->subDays(3)]);
+ archiveTransferredServer($this->server);
+
+ (new CheckMissingVolumeBackupsJob)->handle();
+
+ Notification::assertNothingSent();
+});
+
+test('the cloud provider state of an archive is not checked', function () {
+ // A minute at which the provider state check is due.
+ Carbon::setTestNow('2026-07-11 12:00:00');
+ Queue::fake();
+ archiveTransferredServer($this->server);
+
+ (new ServerManagerJob)->handle();
+
+ Queue::assertNotPushed(ServerCloudProviderStatusCheckJob::class);
+ Carbon::setTestNow();
+});