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: enforce remote output size limits

Andras Bacsai288dc98ca7bd
diff --git a/app/Actions/Proxy/GetProxyConfiguration.php b/app/Actions/Proxy/GetProxyConfiguration.php
index 7df16c52b4..d09aae802a 100644
--- a/app/Actions/Proxy/GetProxyConfiguration.php
+++ b/app/Actions/Proxy/GetProxyConfiguration.php
@@ -107,7 +107,7 @@ class GetProxyConfiguration
"if [ ! -f {$configurationPath} ]; then exit 0; elif [ \"$(wc -c < {$configurationPath})\" -gt ".self::MAX_CONFIGURATION_SIZE_BYTES." ]; then echo '__COOLIFY_PROXY_CONFIG_TOO_LARGE__'; else head -c {$readLimit} {$configurationPath}; fi",
], $server, false);
- if ($result === '__COOLIFY_PROXY_CONFIG_TOO_LARGE__') {
+ if ($result === '__COOLIFY_PROXY_CONFIG_TOO_LARGE__' || strlen($result ?? '') > self::MAX_CONFIGURATION_SIZE_BYTES) {
throw new \RuntimeException('Proxy configuration exceeds the 5 MiB size limit.');
}
diff --git a/app/Models/Application.php b/app/Models/Application.php
index a74941f023..fef76cd393 100644
--- a/app/Models/Application.php
+++ b/app/Models/Application.php
@@ -2161,7 +2161,7 @@ class Application extends BaseModel
}
try {
$composeFileContent = instant_remote_process($commands, $this->destination->server);
- if ($composeFileContent === '__COOLIFY_COMPOSE_TOO_LARGE__') {
+ if ($composeFileContent === '__COOLIFY_COMPOSE_TOO_LARGE__' || strlen($composeFileContent) > self::MAX_DOCKER_COMPOSE_SIZE_BYTES) {
throw new RuntimeException('Docker Compose file exceeds the 5 MiB size limit.');
}
} catch (\Exception $e) {
diff --git a/tests/Feature/GetLogsCommandInjectionTest.php b/tests/Feature/GetLogsCommandInjectionTest.php
index c920b94ede..2c86d73284 100644
--- a/tests/Feature/GetLogsCommandInjectionTest.php
+++ b/tests/Feature/GetLogsCommandInjectionTest.php
@@ -80,7 +80,7 @@ describe('GetLogs Livewire action validation', function () {
'is_usable' => true,
'force_disabled' => false,
])->save();
- $server = Server::with('settings')->find($this->server->id);
+ $server = Server::with('settings')->findOrFail($this->server->id);
$output = "\e[31m".str_repeat('a', GetLogs::MAX_DISPLAY_SIZE_BYTES - 4);
expect(strlen($output))->toBe(GetLogs::MAX_DISPLAY_SIZE_BYTES + 1);
@@ -114,7 +114,7 @@ describe('GetLogs Livewire action validation', function () {
'force_disabled' => false,
])->save();
// Reload server with fresh settings to ensure casted values
- $server = Server::with('settings')->find($this->server->id);
+ $server = Server::with('settings')->findOrFail($this->server->id);
Livewire::test(GetLogs::class, [
'server' => $server,
@@ -144,7 +144,7 @@ describe('GetLogs Livewire action validation', function () {
'is_usable' => true,
'force_disabled' => false,
])->save();
- $server = Server::with('settings')->find($this->server->id);
+ $server = Server::with('settings')->findOrFail($this->server->id);
Livewire::test(GetLogs::class, [
'server' => $server,
diff --git a/tests/Pest.php b/tests/Pest.php
index 7100bfaa72..25d9440108 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -27,6 +27,23 @@ uses(TestCase::class)->in('Feature', 'v4/Feature', 'v4/Browser', 'v5/Browser');
require_once __DIR__.'/Support/BrowserTestHelpers.php';
+function remoteOutputSource(string $path): string
+{
+ $fixturePath = dirname(__DIR__).'/'.$path;
+
+ if (! is_readable($fixturePath)) {
+ throw new RuntimeException("Unable to read source fixture: {$fixturePath}");
+ }
+
+ $source = file_get_contents($fixturePath);
+
+ if ($source === false) {
+ throw new RuntimeException("Unable to read source fixture: {$fixturePath}");
+ }
+
+ return $source;
+}
+
/*
|--------------------------------------------------------------------------
| Test Hooks
diff --git a/tests/Unit/LocalFileVolumeContentSizeTest.php b/tests/Unit/LocalFileVolumeContentSizeTest.php
index 1894bf4394..2a22234012 100644
--- a/tests/Unit/LocalFileVolumeContentSizeTest.php
+++ b/tests/Unit/LocalFileVolumeContentSizeTest.php
@@ -9,10 +9,18 @@
* payload, crashing the browser.
*/
+use App\Models\Application;
use App\Models\LocalFileVolume;
+use App\Models\PrivateKey;
+use App\Models\Server;
+use App\Models\User;
+use Illuminate\Database\Eloquent\Relations\MorphMany;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Process;
+use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
-uses(TestCase::class);
+uses(TestCase::class, RefreshDatabase::class);
it('exposes a 5 MiB content size limit', function () {
expect(LocalFileVolume::MAX_CONTENT_SIZE)->toBe(5_242_880);
@@ -66,31 +74,50 @@ it('exposes the too-large flag via toArray for Livewire serialization', function
});
it('does not read regular bind-mounted file contents while loading service settings', function () {
- $helpers = file_get_contents(base_path('bootstrap/helpers/services.php'));
- $filesystemSync = str($helpers)
- ->after('function getFilesystemVolumesFromServer')
- ->before('function updateCompose');
-
- expect($filesystemSync->value())
- ->not->toContain('instant_remote_process(["cat $fileLocation"]');
- expect($filesystemSync->value())
- ->toContain('if ($fileVolume->is_based_on_git)')
- ->toContain('$fileVolume->loadStorageOnServer();');
-});
-
-it('marks git-based file volumes as files before refreshing their content', function () {
- $helpers = file_get_contents(base_path('bootstrap/helpers/services.php'));
- $fileBranch = str($helpers)
- ->after("if (\$isFile === 'OK') {")
- ->before("} elseif (\$isDir === 'OK') {");
-
- expect($fileBranch->value())->toMatch(
- '/\$fileVolume->is_directory = false;\s+\$fileVolume->save\(\);\s+if \(\$fileVolume->is_based_on_git\) \{/'
- );
+ $user = User::factory()->create();
+ $privateKey = PrivateKey::factory()->create(['team_id' => $user->teams()->first()->id]);
+ Storage::fake('ssh-keys');
+ $server = Server::factory()->create([
+ 'team_id' => $user->teams()->first()->id,
+ 'private_key_id' => $privateKey->id,
+ ]);
+
+ $volume = Mockery::mock(LocalFileVolume::class)->makePartial();
+ $volume->fs_path = '/data/large.bin';
+ $volume->is_based_on_git = false;
+ $volume->shouldReceive('save')->once();
+ $volume->shouldNotReceive('loadStorageOnServer');
+
+ $fileStorages = Mockery::mock(MorphMany::class);
+ $fileStorages->shouldReceive('get')->once()->andReturn(collect([$volume]));
+
+ $application = Mockery::mock(Application::class)->makePartial();
+ $application->shouldReceive('getMorphClass')->andReturn(Application::class);
+ $application->shouldReceive('workdir')->once()->andReturn('/data/application');
+ $application->shouldReceive('fileStorages')->once()->andReturn($fileStorages);
+ $application->setRelation('destination', (object) ['server' => $server]);
+
+ Process::fake(function ($process) {
+ if (str_contains($process->command, 'test -f /data/large.bin')) {
+ return Process::result(output: 'OK');
+ }
+
+ if (str_contains($process->command, 'test -d /data/large.bin')) {
+ return Process::result(output: 'NOK');
+ }
+
+ return Process::result();
+ });
+
+ getFilesystemVolumesFromServer($application);
+
+ expect($volume->is_directory)->toBeFalse();
+ Process::assertRan(fn ($process) => str_contains($process->command, 'test -f /data/large.bin'));
+ Process::assertNotRan(fn ($process) => str_contains($process->command, 'cat /data/large.bin') || str_contains($process->command, 'head -c'));
});
it('bounds the remote file read itself to prevent a size-check race', function () {
- $source = file_get_contents(app_path('Models/LocalFileVolume.php'));
+ $source = remoteOutputSource('app/Models/LocalFileVolume.php');
$loadStorage = str($source)
->after('public function loadStorageOnServer()')
->before('public function deleteStorageOnServer()');
@@ -101,7 +128,7 @@ it('bounds the remote file read itself to prevent a size-check race', function (
});
it('bounds directory-to-file conflict reads the same way', function () {
- $source = file_get_contents(app_path('Models/LocalFileVolume.php'));
+ $source = remoteOutputSource('app/Models/LocalFileVolume.php');
$saveStorage = str($source)
->after('public function saveStorageOnServer()')
->before('protected function plainMountPath');
@@ -118,8 +145,12 @@ it('treats a bounded remote read that exceeds the limit as too large', function
});
it('keeps a bounded remote read that fits the limit', function () {
+ $maximumSizedContent = str_repeat('a', LocalFileVolume::MAX_CONTENT_SIZE);
+
expect(LocalFileVolume::contentFromBoundedRead('hello'))
->toBe('hello')
+ ->and(LocalFileVolume::contentFromBoundedRead($maximumSizedContent))
+ ->toBe($maximumSizedContent)
->and(LocalFileVolume::contentFromBoundedRead(null))
->toBe('');
});
diff --git a/tests/Unit/RemoteOutputSizeLimitsTest.php b/tests/Unit/RemoteOutputSizeLimitsTest.php
index 3660e88284..dda82a0fb1 100644
--- a/tests/Unit/RemoteOutputSizeLimitsTest.php
+++ b/tests/Unit/RemoteOutputSizeLimitsTest.php
@@ -5,27 +5,65 @@ use App\Jobs\ScheduledTaskJob;
use App\Livewire\Project\Shared\GetLogs;
use App\Livewire\Server\Proxy\DynamicConfigurations;
use App\Models\Application;
+use App\Models\PrivateKey;
use App\Models\Server;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Process;
+use Illuminate\Support\Facades\Storage;
+use Spatie\SchemalessAttributes\SchemalessAttributes;
+use Tests\TestCase;
-function remoteOutputSource(string $path): string
+uses(TestCase::class, RefreshDatabase::class);
+
+function remoteOutputTestServer(): Server
{
- return file_get_contents(__DIR__.'/../../'.$path);
+ $user = User::factory()->create();
+ $team = $user->teams()->first();
+ $privateKey = PrivateKey::factory()->create(['team_id' => $team->id]);
+ Storage::fake('ssh-keys');
+
+ return Server::factory()->create([
+ 'team_id' => $team->id,
+ 'private_key_id' => $privateKey->id,
+ ]);
}
it('bounds dynamic proxy configuration files and their combined Livewire payload', function () {
- $source = remoteOutputSource('app/Livewire/Server/Proxy/DynamicConfigurations.php');
-
- expect($source)
- ->toContain('MAX_CONFIGURATION_FILE_SIZE_BYTES')
- ->toContain('MAX_TOTAL_CONFIGURATION_SIZE_BYTES')
- ->toContain('MAX_CONFIGURATION_FILES')
- ->toContain('head -c')
- ->toContain('$totalBytes');
-
- expect(DynamicConfigurations::MAX_CONFIGURATION_FILE_SIZE_BYTES)->toBe(1024 * 1024)
- ->and(DynamicConfigurations::MAX_TOTAL_CONFIGURATION_SIZE_BYTES)->toBe(5 * 1024 * 1024)
- ->and(DynamicConfigurations::MAX_CONFIGURATION_FILES)->toBe(100);
+ $server = Mockery::mock(remoteOutputTestServer())->makePartial();
+ $server->shouldReceive('proxyPath')->andReturn('/data/proxy');
+ $files = collect(range(1, 101))->map(fn (int $number) => sprintf('file%03d.yml', $number))->implode("\n");
+
+ Process::fake(function ($process) use ($files) {
+ if (str_contains($process->command, 'ls -1')) {
+ return Process::result(output: $files);
+ }
+
+ if (str_contains($process->command, 'file001.yml')) {
+ return Process::result(output: str_repeat('x', DynamicConfigurations::MAX_CONFIGURATION_FILE_SIZE_BYTES + 1));
+ }
+
+ if (preg_match('/file00[2-6]\.yml/', $process->command)) {
+ return Process::result(output: str_repeat('x', DynamicConfigurations::MAX_CONFIGURATION_FILE_SIZE_BYTES));
+ }
+
+ return Process::result(output: 'x');
+ });
+
+ $component = Mockery::mock(DynamicConfigurations::class)->makePartial();
+ $component->server = $server;
+ $component->shouldReceive('authorize')->once();
+ $component->shouldReceive('dispatch')->andReturnSelf();
+ $component->loadDynamicConfigurations();
+
+ expect($component->contents)->toHaveCount(5)
+ ->toHaveKeys(['file002|yml', 'file003|yml', 'file004|yml', 'file005|yml', 'file006|yml'])
+ ->not->toHaveKeys(['file001|yml', 'file007|yml', 'file101|yml']);
+ Process::assertNotRan(fn ($process) => str_contains($process->command, 'file101.yml'));
});
+it('fails explicitly when a source fixture cannot be read', function () {
+ remoteOutputSource('missing-source-fixture.php');
+})->throws(RuntimeException::class, 'Unable to read source fixture:');
it('bounds regular log viewer output before it reaches PHP', function () {
$source = remoteOutputSource('app/Livewire/Project/Shared/GetLogs.php');
@@ -42,17 +80,34 @@ it('bounds regular log viewer output before it reaches PHP', function () {
->and($command)->toBe('(docker logs example) 2>&1 | head -c 101');
});
-it('bounds docker compose files loaded from git before parsing', function () {
- $source = remoteOutputSource('app/Models/Application.php');
-
- expect($source)
- ->toContain('MAX_DOCKER_COMPOSE_SIZE_BYTES')
- ->toContain('MAX_DOCKER_COMPOSE_SIZE_BYTES + 1')
- ->toContain('head -c');
-
- expect(Application::MAX_DOCKER_COMPOSE_SIZE_BYTES)->toBe(5 * 1024 * 1024);
+it('rejects oversized docker compose files loaded from git before parsing', function () {
+ $server = remoteOutputTestServer();
+
+ $application = Mockery::mock(Application::class)->makePartial();
+ $application->base_directory = '/';
+ $application->docker_compose_location = '/docker-compose.yml';
+ $application->setRelation('destination', (object) ['server' => $server]);
+ $application->shouldReceive('generateGitImportCommands')->andReturn(['commands' => collect(['git clone example checkout'])]);
+ $application->shouldReceive('getGitRemoteStatus')->andReturn(['is_accessible' => true]);
+ $application->shouldReceive('save')->once();
+
+ Process::fake(function ($process) {
+ if (str_contains($process->command, 'git --version')) {
+ return Process::result(output: 'git version 2.40.0');
+ }
+
+ if (str_contains($process->command, 'wc -c')) {
+ return Process::result(output: '__COOLIFY_COMPOSE_TOO_LARGE__');
+ }
+
+ return Process::result();
+ });
+
+ expect(fn () => $application->loadComposeFile())
+ ->toThrow(RuntimeException::class, 'Docker Compose file exceeds the 5 MiB size limit.');
+ expect($application->docker_compose_raw)->toBeNull();
+ Process::assertRan(fn ($process) => str_contains($process->command, 'head -c '.(Application::MAX_DOCKER_COMPOSE_SIZE_BYTES + 1)));
});
-
it('bounds scheduled task output before storing or notifying', function () {
$source = remoteOutputSource('app/Jobs/ScheduledTaskJob.php');
@@ -97,8 +152,7 @@ it('does not pass the scheduled task output wrapper through the sudo rewriter',
$reflection = new ReflectionClass(ScheduledTaskJob::class);
$method = $reflection->getMethod('boundedTaskCommand');
$command = $method->invoke($reflection->newInstanceWithoutConstructor(), 'sudo docker exec example true');
- $server = Mockery::mock(Server::class)->makePartial();
- $server->shouldReceive('getAttribute')->with('user')->andReturn('ubuntu');
+ $server = new Server(['user' => 'ubuntu']);
$rewrittenCommand = parseCommandsByLineForSudo(collect([$command]), $server)[0];
exec('bash -n -c '.escapeshellarg($command), $output, $exitCode);
@@ -111,14 +165,19 @@ it('does not pass the scheduled task output wrapper through the sudo rewriter',
->and($rewrittenExitCode)->not->toBe(0);
});
-it('bounds proxy configuration backfill before storing it', function () {
- $source = remoteOutputSource('app/Actions/Proxy/GetProxyConfiguration.php');
+it('rejects oversized proxy configuration backfill before persistence', function () {
+ $proxy = Mockery::mock(SchemalessAttributes::class);
+ $proxy->shouldNotReceive('set');
+ $server = Mockery::mock(remoteOutputTestServer())->makePartial();
+ $server->shouldReceive('proxyPath')->andReturn('/data/proxy');
+ $server->shouldReceive('getAttribute')->with('proxy')->andReturn($proxy);
+ $server->shouldNotReceive('save');
- expect($source)
- ->toContain('MAX_CONFIGURATION_SIZE_BYTES')
- ->toContain('MAX_CONFIGURATION_SIZE_BYTES + 1')
- ->toContain('head -c')
- ->toContain('Proxy configuration exceeds');
+ Process::fake(['*' => Process::result(output: '__COOLIFY_PROXY_CONFIG_TOO_LARGE__')]);
+
+ $method = new ReflectionMethod(GetProxyConfiguration::class, 'backfillFromDisk');
- expect(GetProxyConfiguration::MAX_CONFIGURATION_SIZE_BYTES)->toBe(5 * 1024 * 1024);
+ expect(fn () => $method->invoke(new GetProxyConfiguration, $server))
+ ->toThrow(RuntimeException::class, 'Proxy configuration exceeds the 5 MiB size limit.');
+ Process::assertRan(fn ($process) => str_contains($process->command, 'head -c '.(GetProxyConfiguration::MAX_CONFIGURATION_SIZE_BYTES + 1)));
});