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(compose): validate Git-based Docker Compose applications

Andras Bacsai5b2724621ad6
diff --git a/app/Http/Controllers/Api/ApplicationsController.php b/app/Http/Controllers/Api/ApplicationsController.php
index a23c8b2ed7..f36bd48014 100644
--- a/app/Http/Controllers/Api/ApplicationsController.php
+++ b/app/Http/Controllers/Api/ApplicationsController.php
@@ -1254,6 +1254,22 @@ class ApplicationsController extends Controller
], 422);
}
+ if ($request->filled('docker_compose_raw')) {
+ try {
+ if (! is_string($request->input('docker_compose_raw'))) {
+ throw new \Exception('The docker_compose_raw field must be a string.');
+ }
+ validateDockerComposeForInjection($request->input('docker_compose_raw'));
+ } catch (\Exception $e) {
+ return response()->json([
+ 'message' => 'Validation failed.',
+ 'errors' => [
+ 'docker_compose_raw' => $e->getMessage(),
+ ],
+ ], 422);
+ }
+ }
+
$return = $this->validateTagsParameter($request);
if ($return instanceof JsonResponse) {
return $return;
diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php
index 810f3336c9..605a77dbf2 100644
--- a/app/Jobs/ApplicationDeploymentJob.php
+++ b/app/Jobs/ApplicationDeploymentJob.php
@@ -706,7 +706,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
$realPathInGit = str($path)->replace($this->application->workdir(), $this->workdir)->value();
// check if the file is a directory or a file inside the repository
$this->execute_remote_command(
- [executeInDocker($this->deployment_uuid, "stat -c '%F' {$realPathInGit}"), 'hidden' => true, 'ignore_errors' => true, 'save' => $saveName]
+ [executeInDocker($this->deployment_uuid, "stat -c '%F' ".escapeshellarg($realPathInGit)), 'hidden' => true, 'ignore_errors' => true, 'save' => $saveName]
);
if ($this->saved_outputs->has($saveName)) {
$fileStat = $this->trimmedSavedOutput($saveName);
@@ -731,7 +731,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
$this->generate_build_env_variables();
- $this->application->loadComposeFile(isInit: false);
+ $this->loadComposeFileForDeployment();
if ($this->application->settings->is_raw_compose_deployment_enabled) {
$this->application->oldRawParser();
$yaml = $composeFile = $this->application->docker_compose_raw;
@@ -1451,6 +1451,23 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
return $this->remote_secrets_cache = $secrets;
}
+ /**
+ * Reads the Compose file from the repository again (also for pull request previews). If the file is not
+ * safe to use, the deployment stops here with a visible log line, before a command uses the file.
+ */
+ private function loadComposeFileForDeployment(): void
+ {
+ try {
+ $this->application->loadComposeFile(isInit: false);
+ } catch (DeploymentException $e) {
+ // Deployment logs escape HTML themselves, so undo the escaping that error toasts need.
+ $message = 'Deployment stopped: '.lcfirst(html_entity_decode($e->getMessage(), ENT_QUOTES | ENT_HTML5));
+ $this->application_deployment_queue->addLogEntry($message, 'stderr');
+
+ throw new DeploymentException($message);
+ }
+ }
+
/**
* Replace {{vault.KEY}} references with values from the configured secret
* manager source. Missing keys fail the deployment with a
diff --git a/app/Livewire/Project/Application/General.php b/app/Livewire/Project/Application/General.php
index 97b82025be..bcc2996449 100644
--- a/app/Livewire/Project/Application/General.php
+++ b/app/Livewire/Project/Application/General.php
@@ -8,6 +8,7 @@ use App\Livewire\Project\Service\Storage;
use App\Models\Application;
use App\Rules\ValidGitBranch;
use App\Support\ValidationPatterns;
+use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection;
@@ -333,10 +334,30 @@ class General extends Component
$this->syncData();
}
+ /**
+ * The Compose field is read-only in the UI, but a Livewire request can still change it. A changed value
+ * must pass the same injection checks as a Compose file from the repository before the model gets it.
+ *
+ * @throws Exception If the changed Compose content is not safe to use (the message is HTML-escaped)
+ */
+ private function validateChangedDockerComposeRaw(): void
+ {
+ if (blank($this->dockerComposeRaw) || $this->dockerComposeRaw === $this->application->docker_compose_raw) {
+ return;
+ }
+
+ try {
+ validateDockerComposeForInjection($this->dockerComposeRaw);
+ } catch (Exception $e) {
+ throw new Exception(e($e->getMessage()), 0, $e);
+ }
+ }
+
private function syncData(bool $toModel = false): void
{
if ($toModel) {
$this->validate();
+ $this->validateChangedDockerComposeRaw();
// Application properties
$this->application->name = $this->name;
diff --git a/app/Models/Application.php b/app/Models/Application.php
index bb047e910d..605a320562 100644
--- a/app/Models/Application.php
+++ b/app/Models/Application.php
@@ -4,6 +4,7 @@ namespace App\Models;
use App\Enums\ApplicationDeploymentStatus;
use App\Enums\BuildPackTypes;
+use App\Exceptions\DeploymentException;
use App\Services\ConfigurationGenerator;
use App\Services\DeploymentConfiguration\ApplicationConfigurationSnapshot;
use App\Services\DeploymentConfiguration\ConfigurationDiff;
@@ -2224,6 +2225,12 @@ class Application extends BaseModel
]);
}
+ /**
+ * Reads the Compose file from the repository and saves it only after validateDockerComposeForInjection()
+ * accepts it, because the parser and the deployment build shell commands from parts of it.
+ *
+ * @throws DeploymentException If the Compose file is not safe to use (the message is HTML-escaped)
+ */
public function loadComposeFile($isInit = false, ?string $restoreBaseDirectory = null, ?string $restoreDockerComposeLocation = null)
{
// Use provided restore values or capture current values as fallback
@@ -2273,6 +2280,16 @@ class Application extends BaseModel
instant_remote_process($commands, $this->destination->server, false);
}
if ($composeFileContent) {
+ try {
+ validateDockerComposeForInjection($composeFileContent);
+ } catch (\Exception $e) {
+ $this->docker_compose_location = $initialDockerComposeLocation;
+ $this->base_directory = $initialBaseDirectory;
+ $this->save();
+
+ throw new DeploymentException(e("The Docker Compose file at {$workdir}{$composeFile} (branch: {$this->git_branch}) is not safe to use, so Coolify did not load it. {$e->getMessage()}"));
+ }
+
$this->docker_compose_raw = $composeFileContent;
$this->save();
$parsedServices = $this->parse();
diff --git a/bootstrap/helpers/parsers.php b/bootstrap/helpers/parsers.php
index efec4f4e28..21ef175a5e 100644
--- a/bootstrap/helpers/parsers.php
+++ b/bootstrap/helpers/parsers.php
@@ -201,7 +201,23 @@ function validateComposeNetworkNameField(string $name): void
return;
}
- validateComposeNetworkName($name, 'network name field');
+ // Compose also resolves variables inside a longer name, for example ${COMPOSE_PROJECT_NAME}_default.
+ // Each variable must be $VAR, ${VAR}, ${VAR:-default} or ${VAR-default} with a safe default; the name
+ // is then checked with each variable replaced, so no shell syntax can remain.
+ $withoutVariables = preg_replace_callback(
+ '/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}|\$[A-Za-z_][A-Za-z0-9_]*/',
+ function (array $matches): string {
+ $default = $matches[2] ?? '';
+ if ($default !== '' && preg_match('/\A[A-Za-z0-9_.-]+\z/', $default) !== 1) {
+ throw new Exception('Invalid Docker Compose network name field. Variable defaults may contain only alphanumeric characters, dots, hyphens, and underscores.');
+ }
+
+ return 'x';
+ },
+ $name,
+ );
+
+ validateComposeNetworkName($withoutVariables ?? $name, 'network name field');
}
/**
diff --git a/tests/Feature/ApplicationComposeInjectionValidationTest.php b/tests/Feature/ApplicationComposeInjectionValidationTest.php
new file mode 100644
index 0000000000..659583ca68
--- /dev/null
+++ b/tests/Feature/ApplicationComposeInjectionValidationTest.php
@@ -0,0 +1,313 @@
+<?php
+
+use App\Actions\Application\LoadComposeFile;
+use App\Exceptions\DeploymentException;
+use App\Jobs\ApplicationDeploymentJob;
+use App\Livewire\Project\Application\General;
+use App\Models\Application;
+use App\Models\ApplicationDeploymentQueue;
+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 App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Process;
+use Illuminate\Support\Facades\Queue;
+use Livewire\Livewire;
+
+uses(RefreshDatabase::class);
+
+const SAFE_APPLICATION_COMPOSE = "services:\n web:\n image: nginx:alpine\n";
+
+beforeEach(function () {
+ InstanceSettings::forceCreate(['id' => 0]);
+ config(['constants.ssh.mux_enabled' => false]);
+
+ $this->team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ session(['currentTeam' => $this->team]);
+ $this->token = $this->user->createToken('compose-injection-test', ['*'])->plainTextToken;
+
+ $this->server = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'private_key_id' => PrivateKey::factory()->create(['team_id' => $this->team->id])->id,
+ ]);
+ $this->destination = StandaloneDocker::query()->where('server_id', $this->server->id)->firstOrFail();
+ $this->project = Project::factory()->create(['team_id' => $this->team->id]);
+ $this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
+
+ $this->application = Application::factory()->create([
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ 'build_pack' => 'dockercompose',
+ 'git_repository' => 'https://github.com/coollabsio/compose-app',
+ 'git_branch' => 'main',
+ 'base_directory' => '/',
+ 'docker_compose_location' => '/docker-compose.yml',
+ 'docker_compose_raw' => SAFE_APPLICATION_COMPOSE,
+ 'redirect' => 'both',
+ 'static_image' => 'nginx:alpine',
+ ])->fresh();
+});
+
+/**
+ * @return array<string, array{string}>
+ */
+function composeInjectionPayloads(): array
+{
+ return [
+ 'service name command substitution' => ["services:\n web\$(touch /tmp/pwned):\n image: nginx\n"],
+ 'service name command separator' => ["services:\n 'web;touch /tmp/pwned':\n image: nginx\n"],
+ 'network name command substitution' => ["services:\n web:\n image: nginx\n networks:\n - edge\nnetworks:\n edge:\n name: 'edge\$(touch /tmp/pwned)'\n"],
+ 'volume source command separator' => ["services:\n web:\n image: nginx\n volumes:\n - './data;touch /tmp/pwned:/data'\n"],
+ ];
+}
+
+/**
+ * The server returns $compose when Coolify reads the Compose file from the repository.
+ */
+function fakeRepositoryCompose(string $compose): void
+{
+ Process::fake(function ($process) use ($compose) {
+ $command = is_array($process->command) ? implode(' ', $process->command) : $process->command;
+ if (str_contains($command, 'git --version')) {
+ return Process::result(output: 'git version 2.43.0');
+ }
+ if (str_contains($command, 'head -c')) {
+ return Process::result(output: $compose);
+ }
+
+ return Process::result(output: '');
+ });
+}
+
+/**
+ * A deployment job that only has the state needed to load the Compose file.
+ *
+ * @param array<int, array{0: string, 1: string}> $logEntries
+ */
+function composeDeploymentJob(Application $application, int $pullRequestId, array &$logEntries): ApplicationDeploymentJob
+{
+ $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 = (new ReflectionClass(ApplicationDeploymentJob::class))->newInstanceWithoutConstructor();
+ foreach ([
+ 'application' => $application,
+ 'application_deployment_queue' => $queue,
+ 'pull_request_id' => $pullRequestId,
+ 'deployment_uuid' => 'deployment-uuid',
+ ] as $property => $value) {
+ (new ReflectionProperty(ApplicationDeploymentJob::class, $property))->setValue($job, $value);
+ }
+
+ return $job;
+}
+
+test('loading the Compose file from Git rejects injection and does not save it', function (string $compose) {
+ fakeRepositoryCompose($compose);
+
+ expect(fn () => $this->application->loadComposeFile())
+ ->toThrow(DeploymentException::class, 'The Docker Compose file at /docker-compose.yml (branch: main) is not safe to use');
+
+ expect($this->application->refresh()->docker_compose_raw)->toBe(SAFE_APPLICATION_COMPOSE);
+})->with(composeInjectionPayloads());
+
+test('the rejection message is HTML-safe for error toasts', function () {
+ fakeRepositoryCompose("services:\n web:\n image: nginx\n volumes:\n - './data>/etc/passwd:/data'\n");
+
+ expect(fn () => $this->application->loadComposeFile())
+ ->toThrow(function (DeploymentException $exception) {
+ expect($exception->getMessage())->toContain('&gt;')->not->toContain("'>'");
+ });
+});
+
+test('loading the Compose file from Git restores the previous location when validation fails', function () {
+ fakeRepositoryCompose(composeInjectionPayloads()['service name command separator'][0]);
+ $this->application->docker_compose_location = '/compose/evil.yml';
+
+ expect(fn () => $this->application->loadComposeFile(restoreDockerComposeLocation: '/docker-compose.yml', restoreBaseDirectory: '/'))
+ ->toThrow(DeploymentException::class);
+
+ expect($this->application->refresh())
+ ->docker_compose_location->toBe('/docker-compose.yml')
+ ->docker_compose_raw->toBe(SAFE_APPLICATION_COMPOSE);
+});
+
+test('loading a safe Compose file from Git saves it', function () {
+ $compose = "services:\n api:\n image: acme/api:\${TAG:-latest}\n command: sh -c 'migrate && serve > /dev/null'\n";
+ fakeRepositoryCompose($compose);
+
+ $this->application->loadComposeFile();
+
+ expect($this->application->refresh()->docker_compose_raw)->toBe(trim($compose));
+});
+
+test('the queued LoadComposeFile action rejects injection', function () {
+ fakeRepositoryCompose(composeInjectionPayloads()['service name command substitution'][0]);
+
+ expect(fn () => LoadComposeFile::run($this->application))->toThrow(DeploymentException::class);
+ expect($this->application->refresh()->docker_compose_raw)->toBe(SAFE_APPLICATION_COMPOSE);
+});
+
+test('the Reload Compose File button shows the validation error and does not save', function (string $compose) {
+ $this->actingAs($this->user);
+ fakeRepositoryCompose($compose);
+
+ Livewire::test(General::class, ['application' => $this->application])
+ ->call('loadComposeFile')
+ ->assertDispatched('error', fn (string $event, array $params): bool => str_contains($params[0], 'is not safe to use'))
+ ->assertNotDispatched('success')
+ ->assertSet('dockerComposeRaw', SAFE_APPLICATION_COMPOSE);
+
+ expect($this->application->refresh()->docker_compose_raw)->toBe(SAFE_APPLICATION_COMPOSE);
+})->with(composeInjectionPayloads());
+
+test('saving the General form rejects an injected raw Compose file', function (string $compose) {
+ $this->actingAs($this->user);
+ fakeRepositoryCompose(SAFE_APPLICATION_COMPOSE);
+
+ Livewire::test(General::class, ['application' => $this->application])
+ ->set('dockerComposeRaw', $compose)
+ ->call('submit')
+ ->assertDispatched('error', fn (string $event, array $params): bool => str_starts_with($params[0], 'Invalid Docker'))
+ ->assertNotDispatched('success');
+
+ expect($this->application->refresh()->docker_compose_raw)->toBe(SAFE_APPLICATION_COMPOSE);
+})->with(composeInjectionPayloads());
+
+test('an instant save of the General form rejects an injected raw Compose file', function () {
+ $this->actingAs($this->user);
+ fakeRepositoryCompose(SAFE_APPLICATION_COMPOSE);
+
+ Livewire::test(General::class, ['application' => $this->application])
+ ->set('dockerComposeRaw', composeInjectionPayloads()['service name command substitution'][0])
+ ->set('isHttpBasicAuthEnabled', true)
+ ->set('httpBasicAuthUsername', 'admin')
+ ->set('httpBasicAuthPassword', 'password123')
+ ->call('instantSave')
+ ->assertDispatched('error', fn (string $event, array $params): bool => str_starts_with($params[0], 'Invalid Docker Compose service name'))
+ ->assertNotDispatched('success');
+
+ expect($this->application->refresh())
+ ->docker_compose_raw->toBe(SAFE_APPLICATION_COMPOSE)
+ ->is_http_basic_auth_enabled->toBeFalsy();
+});
+
+test('saving the General form accepts a safe raw Compose file', function () {
+ $this->actingAs($this->user);
+ $compose = "services:\n web:\n image: nginx:alpine\n healthcheck:\n test: ['CMD-SHELL', 'curl -f http://localhost || exit 1']\n";
+ // Saving the form reloads the Compose file from the repository when it resets the labels.
+ fakeRepositoryCompose($compose);
+
+ Livewire::test(General::class, ['application' => $this->application])
+ ->set('dockerComposeRaw', $compose)
+ ->call('submit')
+ // submit() also runs real DNS checks for the domains, so only Compose errors are relevant here.
+ ->assertNotDispatched('error', fn (string $event, array $params): bool => str_contains((string) ($params[0] ?? ''), 'Docker Compose'));
+
+ expect($this->application->refresh()->docker_compose_raw)->toBe(trim($compose));
+});
+
+test('API create rejects an injected docker_compose_raw and creates no application', function (string $compose) {
+ Queue::fake();
+
+ $this->withHeaders(['Authorization' => 'Bearer '.$this->token])
+ ->postJson('/api/v1/applications/public', [
+ 'project_uuid' => $this->project->uuid,
+ 'environment_uuid' => $this->environment->uuid,
+ 'server_uuid' => $this->server->uuid,
+ 'git_repository' => 'https://gitlab.com/coolify/compose-app',
+ 'git_branch' => 'main',
+ 'build_pack' => 'dockercompose',
+ 'ports_exposes' => '80',
+ 'autogenerate_domain' => false,
+ 'docker_compose_raw' => $compose,
+ ])
+ ->assertUnprocessable()
+ ->assertJsonPath('message', 'Validation failed.')
+ ->assertJsonStructure(['errors' => ['docker_compose_raw']]);
+
+ expect(Application::query()->where('git_repository', 'https://gitlab.com/coolify/compose-app')->exists())->toBeFalse();
+})->with(composeInjectionPayloads());
+
+test('API create accepts a safe docker_compose_raw', function () {
+ Queue::fake();
+
+ $this->withHeaders(['Authorization' => 'Bearer '.$this->token])
+ ->postJson('/api/v1/applications/public', [
+ 'project_uuid' => $this->project->uuid,
+ 'environment_uuid' => $this->environment->uuid,
+ 'server_uuid' => $this->server->uuid,
+ 'git_repository' => 'https://gitlab.com/coolify/compose-app',
+ 'git_branch' => 'main',
+ 'build_pack' => 'dockercompose',
+ 'ports_exposes' => '80',
+ 'autogenerate_domain' => false,
+ 'docker_compose_raw' => SAFE_APPLICATION_COMPOSE,
+ ])
+ ->assertCreated();
+});
+
+test('API update does not accept docker_compose_raw', function () {
+ $this->withHeaders(['Authorization' => 'Bearer '.$this->token])
+ ->patchJson("/api/v1/applications/{$this->application->uuid}", [
+ 'docker_compose_raw' => composeInjectionPayloads()['service name command substitution'][0],
+ ])
+ ->assertUnprocessable()
+ ->assertJsonStructure(['errors' => ['docker_compose_raw']]);
+
+ expect($this->application->refresh()->docker_compose_raw)->toBe(SAFE_APPLICATION_COMPOSE);
+});
+
+test('a deployment stops with a visible log line when the repository Compose file is not safe', function (int $pullRequestId) {
+ fakeRepositoryCompose(composeInjectionPayloads()['service name command substitution'][0]);
+ $logEntries = [];
+ $job = composeDeploymentJob($this->application, $pullRequestId, $logEntries);
+
+ expect(fn () => (new ReflectionMethod(ApplicationDeploymentJob::class, 'loadComposeFileForDeployment'))->invoke($job))
+ ->toThrow(DeploymentException::class, 'Deployment stopped: the Docker Compose file at /docker-compose.yml (branch: main) is not safe to use');
+
+ $visible = collect($logEntries)->filter(fn (array $entry): bool => $entry[2] === false)->pluck(0)->implode("\n");
+ expect($visible)
+ ->toContain('Deployment stopped: the Docker Compose file at /docker-compose.yml (branch: main) is not safe to use')
+ ->toContain('Invalid Docker Compose service name')
+ ->not->toContain('&#039;')
+ ->not->toContain('#0 ')
+ ->not->toContain('.php');
+ expect($this->application->refresh()->docker_compose_raw)->toBe(SAFE_APPLICATION_COMPOSE);
+ 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('a deployment loads a safe repository Compose file', function () {
+ $compose = "services:\n web:\n image: nginx:1.27\n";
+ fakeRepositoryCompose($compose);
+ $logEntries = [];
+
+ (new ReflectionMethod(ApplicationDeploymentJob::class, 'loadComposeFileForDeployment'))
+ ->invoke(composeDeploymentJob($this->application, 0, $logEntries));
+
+ expect($this->application->refresh()->docker_compose_raw)->toBe(trim($compose));
+});
+
+test('the Compose deployment validates the repository file before any command uses it', function () {
+ $method = new ReflectionMethod(ApplicationDeploymentJob::class, 'deploy_docker_compose_buildpack');
+ $lines = array_slice(file($method->getFileName()), $method->getStartLine() - 1, $method->getEndLine() - $method->getStartLine() + 1);
+ $body = implode('', $lines);
+
+ $loadPosition = strpos($body, '$this->loadComposeFileForDeployment();');
+ expect($loadPosition)->not->toBeFalse()
+ ->and($body)->not->toContain('$this->application->loadComposeFile(')
+ ->and($loadPosition)->toBeLessThan(strpos($body, '$this->application->oldRawParser()'))
+ ->and($loadPosition)->toBeLessThan(strpos($body, '$this->application->parse('))
+ ->and($loadPosition)->toBeLessThan(strpos($body, 'base64 -d'))
+ ->and($body)->toContain('"stat -c \'%F\' ".escapeshellarg($realPathInGit)');
+});
diff --git a/tests/Unit/DockerComposeInjectionCompatibilityTest.php b/tests/Unit/DockerComposeInjectionCompatibilityTest.php
new file mode 100644
index 0000000000..21db47628e
--- /dev/null
+++ b/tests/Unit/DockerComposeInjectionCompatibilityTest.php
@@ -0,0 +1,231 @@
+<?php
+
+/**
+ * validateDockerComposeForInjection() must block shell injection without rejecting valid Compose files.
+ * Git-based Docker Compose applications and Services use the same rules.
+ */
+function composeTemplateFiles(): array
+{
+ $files = glob(dirname(__DIR__, 2).'/templates/compose/*.{yaml,yml}', GLOB_BRACE);
+
+ return collect($files)->mapWithKeys(fn (string $file): array => [basename($file) => [$file]])->all();
+}
+
+test('every service template passes the Compose injection validator', function (string $file) {
+ validateDockerComposeForInjection(file_get_contents($file));
+
+ expect(true)->toBeTrue();
+})->with(composeTemplateFiles());
+
+test('the service template corpus is not empty', function () {
+ expect(count(composeTemplateFiles()))->toBeGreaterThan(300);
+});
+
+test('realistic application Compose files pass the injection validator', function (string $compose) {
+ validateDockerComposeForInjection($compose);
+
+ expect(true)->toBeTrue();
+})->with([
+ 'long syntax volumes, bind mounts and named volumes' => <<<'YAML'
+services:
+ app:
+ build:
+ context: ./apps/web
+ dockerfile: Dockerfile.prod
+ args:
+ NODE_ENV: production
+ volumes:
+ - type: bind
+ source: ./config/app.conf
+ target: /etc/app/app.conf
+ read_only: true
+ - type: bind
+ source: /srv/shared/uploads
+ target: /app/uploads
+ - type: volume
+ source: app-cache
+ target: /app/cache
+ volume:
+ nocopy: true
+ - type: tmpfs
+ target: /app/tmp
+ - ./data:/app/data
+ - ./logs:/app/logs:rw
+ - /var/run/docker.sock:/var/run/docker.sock:ro
+ - ~/backups:/backups
+ - app-data:/var/lib/app
+ - "./my data:/app/spaced"
+volumes:
+ app-cache:
+ app-data:
+ driver: local
+YAML,
+ 'variables in images, environment, ports, labels, build contexts and volumes' => <<<'YAML'
+services:
+ api:
+ image: ${REGISTRY:-ghcr.io}/acme/api:${API_TAG:-latest}
+ build:
+ context: ${BUILD_CONTEXT:-.}
+ args:
+ - VERSION=${VERSION}
+ environment:
+ DATABASE_URL: postgres://${DB_USER}:${DB_PASS:-secret}@db:5432/${DB_NAME}
+ FEATURE_FLAGS: "${FLAGS:-a,b;c|d&e}"
+ SERVICE_FQDN_API_3000: /api
+ ports:
+ - "${API_PORT:-3000}:3000"
+ labels:
+ - traefik.http.routers.api.rule=Host(`${API_HOST}`) && PathPrefix(`/api`)
+ - "com.example.description=Backend > frontend | edge"
+ volumes:
+ - ${DATA_DIR:-./data}:/data
+ - ${HOME}/.config/api:/config:ro
+ - type: bind
+ source: ${CERT_DIR:-./certs}
+ target: /certs
+ - type: bind
+ source: ${PWD}/secrets
+ target: /run/secrets/app
+YAML,
+ 'network names that mix variables and text' => <<<'YAML'
+services:
+ web:
+ image: nginx:1.27
+ networks:
+ - project
+ - env
+ - plain
+networks:
+ project:
+ name: ${COMPOSE_PROJECT_NAME}_default
+ env:
+ name: app-${APP_ENV:-prod}-net
+ plain:
+ external: true
+ name: $SHARED_PREFIX.edge
+YAML,
+ 'networks with variable name field and service network forms' => <<<'YAML'
+services:
+ web:
+ image: nginx:1.27
+ networks:
+ - frontend
+ - backend
+ worker:
+ image: acme/worker
+ networks:
+ backend:
+ aliases:
+ - queue-worker
+ ipv4_address: 172.20.0.10
+ shared:
+networks:
+ frontend:
+ backend:
+ driver: bridge
+ ipam:
+ config:
+ - subnet: 172.20.0.0/16
+ shared:
+ external: true
+ name: ${SHARED_NETWORK:-edge.proxy_net}
+YAML,
+ 'anchors, merge keys, x- extensions and profiles' => <<<'YAML'
+x-logging: &default-logging
+ driver: json-file
+ options:
+ max-size: "10m"
+x-common: &common
+ restart: unless-stopped
+ logging: *default-logging
+ environment: &common-env
+ TZ: UTC
+ volumes:
+ - ./shared:/shared:ro
+services:
+ web:
+ <<: *common
+ image: nginx
+ profiles: [frontend]
+ debug:
+ <<: *common
+ image: busybox
+ profiles:
+ - debug
+ environment:
+ <<: *common-env
+ DEBUG: "1"
+YAML,
+ 'depends_on conditions, healthchecks, commands and entrypoints with shell syntax' => <<<'YAML'
+services:
+ db:
+ image: postgres:16
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB} || exit 1"]
+ interval: 5s
+ timeout: 5s
+ retries: 10
+ cache:
+ image: redis:7
+ command: redis-server --requirepass "$${REDIS_PASSWORD}" --save 60 1 > /dev/null
+ healthcheck:
+ test: redis-cli -a "$$REDIS_PASSWORD" ping | grep PONG && echo ok; exit 0
+ app:
+ image: acme/app
+ entrypoint: ["/bin/sh", "-c"]
+ command:
+ - |
+ until nc -z db 5432; do sleep 1; done
+ php artisan migrate --force && exec php-fpm < /dev/null
+ working_dir: /var/www
+ depends_on:
+ db:
+ condition: service_healthy
+ cache:
+ condition: service_started
+ restart: true
+ cron:
+ image: acme/app
+ command: sh -c 'echo "$(date) start" >> /tmp/cron.log & crond -f'
+ depends_on: [app]
+YAML,
+ 'configs, secrets, service names with dots and dashes' => <<<'YAML'
+services:
+ api.v2:
+ image: acme/api
+ secrets:
+ - db_password
+ configs:
+ - source: app_config
+ target: /etc/app/config.yml
+ web-frontend_1:
+ image: acme/web
+ container_name: my-web
+secrets:
+ db_password:
+ file: ./secrets/db_password.txt
+configs:
+ app_config:
+ content: |
+ key: value; other | thing
+YAML,
+]);
+
+test('Compose injection payloads are rejected', function (string $compose, string $message) {
+ expect(fn () => validateDockerComposeForInjection($compose))->toThrow(Exception::class, $message);
+})->with([
+ 'service name command substitution' => ["services:\n web\$(touch /tmp/pwned):\n image: nginx\n", 'Invalid Docker Compose service name'],
+ 'service name command separator' => ["services:\n 'web;touch /tmp/pwned':\n image: nginx\n", 'Invalid Docker Compose service name'],
+ 'service name backtick' => ["services:\n 'web`id`':\n image: nginx\n", 'Invalid Docker Compose service name'],
+ 'string volume source' => ["services:\n web:\n image: nginx\n volumes:\n - './data\$(touch /tmp/pwned):/data'\n", 'Invalid Docker volume definition'],
+ 'long volume source' => ["services:\n web:\n image: nginx\n volumes:\n - type: bind\n source: '/srv;touch /tmp/pwned'\n target: /data\n", 'Invalid Docker volume definition'],
+ 'long volume variable default' => ["services:\n web:\n image: nginx\n volumes:\n - type: bind\n source: '\${DATA:-/srv\$(touch /tmp/pwned)}'\n target: /data\n", 'Invalid Docker volume definition'],
+ 'service network key' => ["services:\n web:\n image: nginx\n networks:\n 'net\$(touch /tmp/pwned)': {}\n", 'Invalid Docker Compose service network'],
+ 'service network list item' => ["services:\n web:\n image: nginx\n networks:\n - 'net;touch /tmp/pwned'\n", 'Invalid Docker Compose service network'],
+ 'top-level network key' => ["services:\n web:\n image: nginx\nnetworks:\n 'net\$(touch /tmp/pwned)':\n driver: bridge\n", 'Invalid Docker Compose network name'],
+ 'top-level network name field' => ["services:\n web:\n image: nginx\nnetworks:\n edge:\n name: 'edge;touch /tmp/pwned'\n", 'Invalid Docker Compose network name field'],
+ 'mixed network name with command substitution' => ["services:\n web:\n image: nginx\nnetworks:\n edge:\n name: '\${PREFIX}\$(touch /tmp/pwned)'\n", 'Invalid Docker Compose network name field'],
+ 'mixed network name with a separator' => ["services:\n web:\n image: nginx\nnetworks:\n edge:\n name: '\${PREFIX}_net;touch /tmp/pwned'\n", 'Invalid Docker Compose network name field'],
+ 'mixed network name with an unsafe default' => ["services:\n web:\n image: nginx\nnetworks:\n edge:\n name: 'app-\${ENV:-x y}'\n", 'Invalid Docker Compose network name field'],
+ 'network name variable with an unsafe default' => ["services:\n web:\n image: nginx\nnetworks:\n edge:\n name: '\${NET:-x\$(touch /tmp/pwned)}'\n", 'Invalid Docker Compose network name field'],
+]);
diff --git a/tests/Unit/PreSaveValidationTest.php b/tests/Unit/PreSaveValidationTest.php
index eb3188ed82..ac9d8d2adc 100644
--- a/tests/Unit/PreSaveValidationTest.php
+++ b/tests/Unit/PreSaveValidationTest.php
@@ -301,10 +301,21 @@ test('validateDockerComposeForInjection still blocks unsafe compose network name
'default with command substitution' => ['${NET:-$(id)}', 'name'],
'command substitution' => ['$(id)', 'name'],
'backticks' => ['`id`', 'name'],
- 'text around the variable' => ['prefix_${NET}', 'name'],
+ 'text around a variable with command substitution' => ['prefix_${NET}$(id)', 'name'],
'nested variable' => ['${NET:-${OTHER}}', 'name'],
'invalid variable name' => ['${1NET}', 'name'],
'required-variable form' => ['${NET:?missing}', 'name'],
'newline' => ["\${NET}\nid", 'name'],
'variable as network key' => ['${NET}', 'key'],
]);
+
+test('validateDockerComposeForInjection accepts network names that mix variables and text', function (string $name) {
+ $compose = "services:\n app:\n image: nginx:latest\nnetworks:\n shared:\n name: ".json_encode($name)."\n";
+
+ expect(fn () => validateDockerComposeForInjection($compose))->not->toThrow(Exception::class);
+})->with([
+ 'prefix and variable' => ['prefix_${NET}'],
+ 'project default network' => ['${COMPOSE_PROJECT_NAME}_default'],
+ 'variable with default inside text' => ['app-${APP_ENV:-prod}-net'],
+ 'bare variable' => ['$PREFIX.edge'],
+]);