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(previews): remove only the preview's own networks and volumes

Andras Bacsai129cc9704707
diff --git a/app/Exceptions/DeploymentException.php b/app/Exceptions/DeploymentException.php
index 01e0a8235c..97e28f6542 100644
--- a/app/Exceptions/DeploymentException.php
+++ b/app/Exceptions/DeploymentException.php
@@ -11,6 +11,8 @@ use Exception;
*/
class DeploymentException extends Exception
{
+ private bool $messageAlreadyLogged = false;
+
/**
* Create a new deployment exception instance.
*
@@ -29,4 +31,21 @@ class DeploymentException extends Exception
{
return new static($exception->getMessage(), $exception->getCode(), $exception);
}
+
+ /**
+ * Create an exception for a message that is already a visible line in the deployment log,
+ * so the failure handler does not show the same explanation again.
+ */
+ public static function alreadyLogged(string $message, int $code = 0, ?\Throwable $previous = null): static
+ {
+ $exception = new static($message, $code, $previous);
+ $exception->messageAlreadyLogged = true;
+
+ return $exception;
+ }
+
+ public function isMessageAlreadyLogged(): bool
+ {
+ return $this->messageAlreadyLogged;
+ }
}
diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php
index 605a77dbf2..6650df00f9 100644
--- a/app/Jobs/ApplicationDeploymentJob.php
+++ b/app/Jobs/ApplicationDeploymentJob.php
@@ -1464,7 +1464,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
$message = 'Deployment stopped: '.lcfirst(html_entity_decode($e->getMessage(), ENT_QUOTES | ENT_HTML5));
$this->application_deployment_queue->addLogEntry($message, 'stderr');
- throw new DeploymentException($message);
+ throw DeploymentException::alreadyLogged($message, previous: $e);
}
}
@@ -1485,10 +1485,10 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
$missing = RemoteSecretReferences::missingKeys($value, $secrets);
if ($missing !== []) {
- $message = 'Missing secret keys: '.implode(', ', $missing)." (referenced by {$envKey}).";
+ $message = 'Missing secret keys: '.implode(', ', $missing)." (referenced by {$envKey}). Check the secret manager source of this application.";
$this->application_deployment_queue->addLogEntry($message, 'stderr');
- throw new DeploymentException($message.' Check the secret manager source of this application.');
+ throw DeploymentException::alreadyLogged($message);
}
return RemoteSecretReferences::substitute($value, $secrets);
@@ -2087,7 +2087,8 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
} catch (\InvalidArgumentException $exception) {
$this->logInvalidBuildtimeEnvironmentVariableKey($key, $origin);
- throw new DeploymentException(
+ // The log already explains the problem and how to fix it.
+ throw DeploymentException::alreadyLogged(
"Invalid environment variable name from {$origin}: ".ValidationPatterns::displayShellEnvironmentVariableKey($key).'. Names must start with a letter or underscore and contain only letters, numbers, underscores, and dots.',
previous: $exception,
);
@@ -5555,7 +5556,11 @@ COPY ./nginx.conf /etc/nginx/conf.d/default.conf");
$errorClass = get_class($exception);
$this->application_deployment_queue->addLogEntry('========================================', 'stderr');
- $this->application_deployment_queue->addLogEntry("Deployment failed: {$errorMessage}", 'stderr');
+ if ($exception instanceof DeploymentException && $exception->isMessageAlreadyLogged()) {
+ $this->application_deployment_queue->addLogEntry('Deployment failed.', 'stderr');
+ } else {
+ $this->application_deployment_queue->addLogEntry("Deployment failed: {$errorMessage}", 'stderr');
+ }
$this->application_deployment_queue->addLogEntry("Error type: {$errorClass}", 'stderr', hidden: true);
$this->application_deployment_queue->addLogEntry("Error code: {$errorCode}", 'stderr', hidden: true);
diff --git a/app/Models/ApplicationPreview.php b/app/Models/ApplicationPreview.php
index 4c0fc59ae6..0d862b2829 100644
--- a/app/Models/ApplicationPreview.php
+++ b/app/Models/ApplicationPreview.php
@@ -7,8 +7,10 @@ use App\Support\ValidationPatterns;
use App\Traits\HasRestartLimit;
use App\Traits\ReleasesManagedDnsRecords;
use Illuminate\Database\Eloquent\SoftDeletes;
+use Illuminate\Support\Collection;
use RuntimeException;
use Spatie\Url\Url;
+use Throwable;
class ApplicationPreview extends BaseModel
{
@@ -51,26 +53,12 @@ class ApplicationPreview extends BaseModel
$application = $preview->application;
if (data_get($preview, 'application.build_pack') === 'dockercompose') {
- // Docker Compose volume and network cleanup
$composeFile = $application->parse(pull_request_id: $preview->pull_request_id);
- $volumes = data_get($composeFile, 'volumes');
- $networks = data_get($composeFile, 'networks');
- $networkKeys = collect($networks)->keys();
- $volumeKeys = collect($volumes)->keys();
- $volumeKeys->each(function ($key) use ($server) {
- if (! preg_match(ValidationPatterns::VOLUME_NAME_PATTERN, $key)) {
- return;
- }
- instant_remote_process(['docker volume rm -f '.escapeshellarg($key)], $server, false);
- });
- $networkKeys->each(function ($key) use ($server) {
- if (! preg_match(ValidationPatterns::DOCKER_NETWORK_PATTERN, $key)) {
- return;
- }
- $k = escapeshellarg($key);
- instant_remote_process(["docker network disconnect {$k} coolify-proxy"], $server, false);
- instant_remote_process(["docker network rm {$k}"], $server, false);
- });
+ foreach ($preview->generatedComposeVolumeNames($application, collect(data_get($composeFile, 'volumes', []))) as $volumeName) {
+ // Docker does not remove a volume that a container still uses, also with -f.
+ instant_remote_process(['docker volume rm -f '.escapeshellarg($volumeName)], $server, false);
+ }
+ $preview->removeComposePreviewNetwork($application, $server);
} else {
// Regular application volume cleanup
$persistentStorages = $application->persistentStorages()
@@ -108,6 +96,78 @@ class ApplicationPreview extends BaseModel
});
}
+ /**
+ * Names of the Docker Compose volumes that Coolify generated for this preview. The parser names
+ * them "{uuid}_{volume}-pr-{id}" ("{uuid}-{volume}-pr-{id}" before parser version 3). Volumes
+ * named in the Compose file (external, shared, or of the main application) are not included.
+ *
+ * @param Collection<array-key, mixed> $volumes top-level volumes of the parsed preview Compose file
+ * @return list<string>
+ */
+ private function generatedComposeVolumeNames(Application $application, Collection $volumes): array
+ {
+ $prefix = $application->uuid.((int) $application->compose_parsing_version >= 3 ? '_' : '-');
+ $suffix = addPreviewDeploymentSuffix('', $this->pull_request_id);
+
+ return $volumes
+ ->map(function (mixed $volume, int|string $key) use ($prefix, $suffix): ?string {
+ $key = (string) $key;
+ if (filter_var(data_get($volume, 'external', false), FILTER_VALIDATE_BOOLEAN)) {
+ return null;
+ }
+ if (data_get($volume, 'name', $key) !== $key) {
+ return null;
+ }
+ if (strlen($key) <= strlen($prefix.$suffix)
+ || ! str_starts_with($key, $prefix)
+ || ! str_ends_with($key, $suffix)
+ || ! preg_match(ValidationPatterns::VOLUME_NAME_PATTERN, $key)) {
+ return null;
+ }
+
+ return $key;
+ })
+ ->filter()
+ ->unique()
+ ->values()
+ ->all();
+ }
+
+ /**
+ * Removes the network that the deployment created for this preview ("{uuid}-{id}"). Networks
+ * named in the Compose file (such as coolify or an external proxy network) are never removed.
+ * The network stays when a container other than coolify-proxy still uses it.
+ */
+ private function removeComposePreviewNetwork(Application $application, Server $server): void
+ {
+ $network = "{$application->uuid}-{$this->pull_request_id}";
+ if (! isUsableDockerNetworkName($network) || $network === $application->destination?->network) {
+ return;
+ }
+
+ $quotedNetwork = escapeshellarg($network);
+ try {
+ $output = instant_remote_process(["docker network inspect --format '{{json .Containers}}' {$quotedNetwork}"], $server);
+ } catch (Throwable) {
+ // The network does not exist or its state is not known.
+ return;
+ }
+
+ $containers = json_decode($output ?? '{}', true);
+ if (! is_array($containers)) {
+ return;
+ }
+ $otherContainers = collect($containers)
+ ->map(fn (mixed $container): mixed => data_get($container, 'Name'))
+ ->reject(fn (mixed $name): bool => $name === 'coolify-proxy');
+ if ($otherContainers->isNotEmpty()) {
+ return;
+ }
+
+ instant_remote_process(["docker network disconnect {$quotedNetwork} coolify-proxy"], $server, false);
+ instant_remote_process(["docker network rm {$quotedNetwork}"], $server, false);
+ }
+
public static function findPreviewByApplicationAndPullId(int $application_id, int $pull_request_id)
{
return self::where('application_id', $application_id)->where('pull_request_id', $pull_request_id)->firstOrFail();
diff --git a/tests/Feature/ApplicationComposeInjectionValidationTest.php b/tests/Feature/ApplicationComposeInjectionValidationTest.php
index 659583ca68..a9f5ed20c8 100644
--- a/tests/Feature/ApplicationComposeInjectionValidationTest.php
+++ b/tests/Feature/ApplicationComposeInjectionValidationTest.php
@@ -287,6 +287,42 @@ test('a deployment stops with a visible log line when the repository Compose fil
Process::assertNotRan(fn ($process) => str_contains(is_array($process->command) ? implode(' ', $process->command) : $process->command, 'base64 -d'));
})->with(['production' => 0, 'pull request preview' => 42]);
+test('the deployment log shows the unsafe Compose file explanation once and a short failure line', function () {
+ fakeRepositoryCompose(composeInjectionPayloads()['service name command substitution'][0]);
+ $logEntries = [];
+ $queue = Mockery::mock(ApplicationDeploymentQueue::class);
+ $queue->shouldReceive('addLogEntry')->andReturnUsing(function (string $message, string $type = 'stdout', bool $hidden = false) use (&$logEntries) {
+ $logEntries[] = [$message, $type, $hidden];
+ });
+ $job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial()->shouldAllowMockingProtectedMethods();
+ $job->shouldReceive('failDeployment')->once();
+ foreach ([
+ 'application' => $this->application,
+ 'application_deployment_queue' => $queue,
+ 'pull_request_id' => 0,
+ 'deployment_uuid' => 'deployment-uuid',
+ ] as $property => $value) {
+ (new ReflectionProperty(ApplicationDeploymentJob::class, $property))->setValue($job, $value);
+ }
+
+ try {
+ (new ReflectionMethod(ApplicationDeploymentJob::class, 'loadComposeFileForDeployment'))->invoke($job);
+ $this->fail('The deployment did not stop.');
+ } catch (DeploymentException $exception) {
+ $job->failed($exception);
+ }
+
+ $visible = collect($logEntries)->filter(fn (array $entry): bool => $entry[2] === false)->pluck(0);
+ $explanation = 'the Docker Compose file at /docker-compose.yml (branch: main) is not safe to use';
+ expect($visible->filter(fn (string $line): bool => str_contains($line, $explanation)))->toHaveCount(1)
+ ->and($visible)->toContain('Deployment failed.')
+ ->and($visible->implode("\n"))->not->toContain('Deployment failed: ');
+
+ $hidden = collect($logEntries)->filter(fn (array $entry): bool => $entry[2] === true)->pluck(0)->implode("\n");
+ expect($hidden)->toContain('Error type: '.DeploymentException::class)
+ ->toContain('Location: ');
+});
+
test('a deployment loads a safe repository Compose file', function () {
$compose = "services:\n web:\n image: nginx:1.27\n";
fakeRepositoryCompose($compose);
diff --git a/tests/Feature/ApplicationDeploymentControlVarFilteringTest.php b/tests/Feature/ApplicationDeploymentControlVarFilteringTest.php
index 5f61f78c47..e98d42ff2d 100644
--- a/tests/Feature/ApplicationDeploymentControlVarFilteringTest.php
+++ b/tests/Feature/ApplicationDeploymentControlVarFilteringTest.php
@@ -649,6 +649,27 @@ it('explains invalid Nixpacks plan variable keys in deployment logs', function (
->toContain('https://nixpacks.com/docs/configuration/file');
});
+it('marks an invalid variable name failure as already explained in the deployment log', function () {
+ [$application, $server] = makeDeploymentControlVarFixture([
+ 'build_pack' => 'nixpacks',
+ ]);
+
+ [$job, $reflection] = makeControlVarFilteringJob($application, $server, [
+ 'nixpacks_plan_json' => collect([
+ 'variables' => [
+ 'XPACK;SECURITY;ENABLED' => 'true',
+ ],
+ ]),
+ ]);
+
+ try {
+ invokeDeploymentJobMethod($job, $reflection, 'generate_buildtime_environment_variables');
+ $this->fail('The deployment did not stop.');
+ } catch (DeploymentException $exception) {
+ expect($exception->isMessageAlreadyLogged())->toBeTrue();
+ }
+});
+
it('truncates long Nixpacks plan variable keys in deployment logs', function () {
[$application, $server] = makeDeploymentControlVarFixture([
'build_pack' => 'nixpacks',
diff --git a/tests/Feature/ApplicationPreviewComposeCleanupTest.php b/tests/Feature/ApplicationPreviewComposeCleanupTest.php
new file mode 100644
index 0000000000..7fec3852f6
--- /dev/null
+++ b/tests/Feature/ApplicationPreviewComposeCleanupTest.php
@@ -0,0 +1,249 @@
+<?php
+
+use App\Jobs\DeleteResourceJob;
+use App\Models\Application;
+use App\Models\ApplicationPreview;
+use App\Models\Environment;
+use App\Models\InstanceSettings;
+use App\Models\PrivateKey;
+use App\Models\Project;
+use App\Models\Server;
+use App\Models\StandaloneDocker;
+use App\Models\Team;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Process;
+use Illuminate\Support\Facades\Queue;
+
+uses(RefreshDatabase::class);
+
+/**
+ * A Compose file that uses shared networks and volumes next to its own resources.
+ */
+const PREVIEW_CLEANUP_COMPOSE = <<<'YAML'
+services:
+ web:
+ image: nginx:alpine
+ volumes:
+ - app-data:/data
+ - shared-data:/shared
+ networks:
+ - backend
+ - proxy
+ - coolify
+volumes:
+ app-data: {}
+ shared-data:
+ external: true
+ name: shared-data
+ main-only:
+ name: main-db-data
+networks:
+ backend: {}
+ proxy:
+ external: true
+ name: shared-proxy
+ coolify:
+ external: true
+YAML;
+
+beforeEach(function () {
+ InstanceSettings::unguarded(fn () => InstanceSettings::firstOrCreate(['id' => 0]));
+ config(['constants.ssh.mux_enabled' => false]);
+ Queue::fake();
+
+ $team = Team::factory()->create();
+ $privateKey = PrivateKey::factory()->create(['team_id' => $team->id]);
+ $server = Server::factory()->create([
+ 'team_id' => $team->id,
+ 'private_key_id' => $privateKey->id,
+ 'user' => 'deploy',
+ ]);
+ $destination = StandaloneDocker::where('server_id', $server->id)->firstOrFail();
+ $project = Project::factory()->create(['team_id' => $team->id]);
+ $environment = $project->environments()->first()
+ ?? Environment::factory()->create(['project_id' => $project->id]);
+
+ $this->application = Application::factory()->create([
+ 'build_pack' => 'dockercompose',
+ 'docker_compose_raw' => PREVIEW_CLEANUP_COMPOSE,
+ 'environment_id' => $environment->id,
+ 'destination_id' => $destination->id,
+ 'destination_type' => $destination->getMorphClass(),
+ ]);
+ $this->application->settings->update(['connect_to_docker_network' => true]);
+ $this->destinationNetwork = $destination->network;
+ $this->uuid = $this->application->uuid;
+ $this->previewNetwork = "{$this->uuid}-42";
+
+ $this->preview = ApplicationPreview::create([
+ 'uuid' => 'preview-compose-cleanup-test',
+ 'application_id' => $this->application->id,
+ 'pull_request_id' => 42,
+ 'pull_request_html_url' => 'https://github.com/example/repository/pull/42',
+ ]);
+});
+
+/**
+ * @param array<int, string> $commands
+ * @param array<string, mixed>|null $previewNetworkContainers null when the network does not exist
+ */
+function fakePreviewCleanupServer(array &$commands, string $previewNetwork, ?array $previewNetworkContainers = [], string $dockerPs = ''): void
+{
+ Process::fake(function ($process) use (&$commands, $previewNetwork, $previewNetworkContainers, $dockerPs) {
+ $command = is_array($process->command) ? implode(' ', $process->command) : $process->command;
+ $commands[] = $command;
+
+ if (str_contains($command, 'docker network inspect') && str_contains($command, "'{$previewNetwork}'")) {
+ if ($previewNetworkContainers === null) {
+ return Process::result(errorOutput: "Error response from daemon: network {$previewNetwork} not found", exitCode: 1);
+ }
+
+ return Process::result(output: json_encode((object) $previewNetworkContainers));
+ }
+ if (str_contains($command, 'docker ps -a')) {
+ return Process::result(output: $dockerPs);
+ }
+
+ return Process::result(output: '');
+ });
+}
+
+/**
+ * @param array<int, string> $commands
+ * @return array<int, string>
+ */
+function dockerResourceCommands(array $commands): array
+{
+ return array_values(array_filter(
+ $commands,
+ fn (string $command): bool => str_contains($command, 'docker volume') || str_contains($command, 'docker network'),
+ ));
+}
+
+it('removes only the network and volumes that Coolify generated for the preview', function () {
+ $commands = [];
+ fakePreviewCleanupServer($commands, $this->previewNetwork, ['abc' => ['Name' => 'coolify-proxy']]);
+
+ $this->preview->forceDelete();
+
+ $resourceCommands = implode("\n", dockerResourceCommands($commands));
+
+ expect($resourceCommands)
+ ->toContain("sudo docker volume rm -f '{$this->uuid}_app-data-pr-42'")
+ ->toContain("sudo docker volume rm -f '{$this->uuid}_shared-data-pr-42'")
+ ->toContain("sudo docker network disconnect '{$this->previewNetwork}' coolify-proxy")
+ ->toContain("sudo docker network rm '{$this->previewNetwork}'")
+ ->not->toContain("'app-data'")
+ ->not->toContain("'shared-data'")
+ ->not->toContain("'main-only'")
+ ->not->toContain("'main-db-data'")
+ ->not->toContain("'backend'")
+ ->not->toContain("'proxy'")
+ ->not->toContain("'shared-proxy'")
+ ->not->toContain("'coolify'")
+ ->not->toContain("'{$this->destinationNetwork}'");
+
+ expect(ApplicationPreview::withTrashed()->find($this->preview->id))->toBeNull();
+});
+
+it('keeps the preview network when another container still uses it', function () {
+ $commands = [];
+ fakePreviewCleanupServer($commands, $this->previewNetwork, [
+ 'abc' => ['Name' => 'coolify-proxy'],
+ 'def' => ['Name' => 'other-app-container'],
+ ]);
+
+ $this->preview->forceDelete();
+
+ $resourceCommands = implode("\n", dockerResourceCommands($commands));
+
+ expect($resourceCommands)
+ ->toContain("docker network inspect --format '{{json .Containers}}' '{$this->previewNetwork}'")
+ ->not->toContain('docker network disconnect')
+ ->not->toContain('docker network rm');
+});
+
+it('does not run network commands when the preview network does not exist', function () {
+ $commands = [];
+ fakePreviewCleanupServer($commands, $this->previewNetwork, null);
+
+ $this->preview->forceDelete();
+
+ $resourceCommands = implode("\n", dockerResourceCommands($commands));
+
+ expect($resourceCommands)
+ ->not->toContain('docker network disconnect')
+ ->not->toContain('docker network rm')
+ ->toContain("docker volume rm -f '{$this->uuid}_app-data-pr-42'");
+});
+
+it('keeps the destination network when it has the generated preview name pattern', function () {
+ StandaloneDocker::query()->whereKey($this->application->destination_id)->update(['network' => $this->previewNetwork]);
+ $commands = [];
+ fakePreviewCleanupServer($commands, $this->previewNetwork, []);
+
+ $this->preview->forceDelete();
+
+ expect(implode("\n", dockerResourceCommands($commands)))
+ ->not->toContain('docker network disconnect')
+ ->not->toContain('docker network rm');
+});
+
+it('uses remove commands with quoted values that the non-root sudo parser keeps intact', function () {
+ $commands = [];
+ fakePreviewCleanupServer($commands, $this->previewNetwork, []);
+
+ $this->preview->forceDelete();
+
+ foreach (dockerResourceCommands($commands) as $command) {
+ $remoteCommand = str($command)->after('sudo ')->before("\n")->value();
+ expect($command)->toContain('sudo docker ')
+ ->and($command)->not->toContain('sudo sudo')
+ ->and($command)->not->toContain('| sudo')
+ ->and($remoteCommand)->not->toContain('$(');
+ }
+});
+
+it('removes the preview containers, network, and volumes through the delete job and keeps shared resources', function () {
+ $previewContainer = json_encode([
+ 'Names' => "web-{$this->uuid}-pr-42",
+ 'Labels' => "coolify.applicationId={$this->application->id},coolify.pullRequestId=42",
+ 'State' => 'running',
+ ]);
+ $mainContainer = json_encode([
+ 'Names' => "web-{$this->uuid}",
+ 'Labels' => "coolify.applicationId={$this->application->id},coolify.pullRequestId=0",
+ 'State' => 'running',
+ ]);
+ $commands = [];
+ fakePreviewCleanupServer($commands, $this->previewNetwork, [], $previewContainer."\n".$mainContainer);
+
+ (new DeleteResourceJob($this->preview))->handle();
+
+ $all = implode("\n", $commands);
+ $containerRemoval = collect($commands)->search(fn (string $command): bool => str_contains($command, "docker rm -f 'web-{$this->uuid}-pr-42'"));
+ $networkRemoval = collect($commands)->search(fn (string $command): bool => str_contains($command, "docker network rm '{$this->previewNetwork}'"));
+
+ expect($containerRemoval)->not->toBeFalse()
+ ->and($networkRemoval)->not->toBeFalse()
+ ->and($containerRemoval)->toBeLessThan($networkRemoval)
+ ->and($all)->not->toContain("docker rm -f 'web-{$this->uuid}'")
+ ->and($all)->toContain("docker volume rm -f '{$this->uuid}_app-data-pr-42'")
+ ->and(implode("\n", dockerResourceCommands($commands)))
+ ->not->toContain("'coolify'")
+ ->not->toContain("'shared-proxy'")
+ ->not->toContain("'shared-data'");
+
+ expect(ApplicationPreview::withTrashed()->find($this->preview->id))->toBeNull();
+});
+
+it('parses a preview with a bind mount in development mode', function () {
+ // In development, bind sources are rewritten to the dev volume; the preview suffix returned a plain string.
+ config(['app.env' => 'local']);
+ Process::fake();
+ $this->application->update(['docker_compose_raw' => "services:\n web:\n image: nginx:alpine\n volumes:\n - type: bind\n source: ./config/app.conf\n target: /etc/app.conf\n content: hello\n"]);
+
+ $compose = $this->application->fresh()->parse(pull_request_id: 42);
+
+ expect(json_encode($compose, JSON_UNESCAPED_SLASHES))->toContain('/config/app.conf-pr-42');
+});
diff --git a/tests/Feature/SecretManagers/SecretManagerLinkTest.php b/tests/Feature/SecretManagers/SecretManagerLinkTest.php
index 524fa272c2..362130c728 100644
--- a/tests/Feature/SecretManagers/SecretManagerLinkTest.php
+++ b/tests/Feature/SecretManagers/SecretManagerLinkTest.php
@@ -378,6 +378,38 @@ test('a missing secret key fails the deployment and names the variable', functio
->toThrow(DeploymentException::class, 'Missing secret keys: GONE_KEY (referenced by DB_PASSWORD).');
});
+test('a missing secret key is a visible log line once and marks the failure as already logged', function () {
+ Http::fake([
+ 'https://api.doppler.com/v3/configs/config/secrets/download*' => Http::response([
+ 'OTHER' => 'value',
+ ]),
+ ]);
+
+ createSecretManagerLink('doppler');
+
+ $env = $this->application->environment_variables()->create([
+ 'key' => 'DB_PASSWORD',
+ 'value' => '{{vault.GONE_KEY}}',
+ ]);
+ $job = makeDeploymentJobForSecrets();
+
+ try {
+ resolveEnvOnJob($job, $env);
+ $this->fail('The deployment did not stop.');
+ } catch (DeploymentException $exception) {
+ expect($exception->isMessageAlreadyLogged())->toBeTrue();
+ }
+
+ $queue = (new ReflectionProperty($job, 'application_deployment_queue'))->getValue($job);
+ $visible = collect(json_decode($queue->refresh()->logs, true))
+ ->reject(fn (array $entry): bool => (bool) ($entry['hidden'] ?? false))
+ ->pluck('output');
+
+ expect($visible->filter(fn (string $line): bool => str_contains($line, 'Missing secret keys: GONE_KEY (referenced by DB_PASSWORD).')))
+ ->toHaveCount(1)
+ ->and($visible->implode("\n"))->toContain('Check the secret manager source of this application.');
+});
+
test('a reference without a configured source fails the deployment', function () {
Http::fake();
diff --git a/tests/Unit/DeploymentExceptionTest.php b/tests/Unit/DeploymentExceptionTest.php
index 5dd448df41..76168fe0c2 100644
--- a/tests/Unit/DeploymentExceptionTest.php
+++ b/tests/Unit/DeploymentExceptionTest.php
@@ -69,3 +69,15 @@ test('RuntimeException is still reported when thrown', function () {
expect($shouldReport)->toBeTrue();
});
+
+test('DeploymentException marks a message as already logged only when asked', function () {
+ $previous = new RuntimeException('Original error');
+ $logged = DeploymentException::alreadyLogged('Shown in the log', 7, $previous);
+
+ expect($logged->isMessageAlreadyLogged())->toBeTrue()
+ ->and($logged->getMessage())->toBe('Shown in the log')
+ ->and($logged->getCode())->toBe(7)
+ ->and($logged->getPrevious())->toBe($previous)
+ ->and((new DeploymentException('Not shown yet'))->isMessageAlreadyLogged())->toBeFalse()
+ ->and(DeploymentException::fromException($previous)->isMessageAlreadyLogged())->toBeFalse();
+});