Merge remote-tracking branch 'origin/next' into api-sensitive-data-scrubber

This commit is contained in:
Andras Bacsai committed 2026-07-02 15:57:43 +02:00
commit 13172849e1
117 files changed
+5114 -1799

No files matched your search

@@ -3,6 +3,8 @@
use App\Exceptions\DeploymentException;
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use App\Models\ApplicationSetting;
use App\Models\EnvironmentVariable;
use Illuminate\Support\Collection;
use Tests\TestCase;
@@ -236,10 +238,15 @@ it('builds railpack docker command with matching env and secret flags for all ra
],
);
// Build-time variables are interpolated by sourcing the build-time .env file before
// the build, so user/Coolify variables must NOT be forwarded inline as literals.
expect($command)->toContain('set -a && source /artifacts/build-time.env && set +a');
expect($command)->toContain("env 'RAILPACK_NODE_VERSION=22'");
expect($command)->toContain("'RAILPACK_INSTALL_CMD=npm ci && npm run postinstall'");
expect($command)->toContain("'RAILPACK_DEPLOY_APT_PACKAGES=curl wget'");
expect($command)->toContain("'SECRET_JSON={\"token\":\"abc\"}'");
// SECRET_JSON is not a buildpack control variable, so it is provided via the sourced
// build-time .env file (which supports $VAR interpolation) rather than inline `env`.
expect($command)->not->toContain("'SECRET_JSON={\"token\":\"abc\"}'");
expect($command)->toContain("--secret 'id=RAILPACK_NODE_VERSION,env=RAILPACK_NODE_VERSION'");
expect($command)->toContain("--secret 'id=RAILPACK_INSTALL_CMD,env=RAILPACK_INSTALL_CMD'");
expect($command)->toContain("--secret 'id=RAILPACK_DEPLOY_APT_PACKAGES,env=RAILPACK_DEPLOY_APT_PACKAGES'");
@@ -247,3 +254,69 @@ it('builds railpack docker command with matching env and secret flags for all ra
expect($command)->toContain(' --build-arg secrets-hash=');
expect($command)->toContain('--build-arg BUILDKIT_SYNTAX="ghcr.io/railwayapp/railpack-frontend:v'.config('constants.coolify.railpack_version').'"');
});
it('interpolates build-time variable references for railpack by sourcing the build-time env file', function () {
[$job, $reflection] = makeRailpackDeploymentJob([
'uuid' => 'application-uuid',
]);
// Mirrors the issue: BETTER_AUTH_URL=$COOLIFY_URL must be interpolated at build time.
$command = invokeRailpackMethod(
$job,
$reflection,
'railpack_build_command',
[
'coollabsio/coolify:test',
collect([
'BETTER_AUTH_URL' => '$COOLIFY_URL',
'COOLIFY_URL' => 'https://sapere-10.bobman.dev',
]),
],
);
// The literal `$COOLIFY_URL` must NOT be forwarded inline; it is resolved by the shell
// after sourcing the build-time .env file, then read through the build secret.
expect($command)->toContain('set -a && source /artifacts/build-time.env && set +a');
expect($command)->not->toContain("'BETTER_AUTH_URL=\$COOLIFY_URL'");
expect($command)->not->toContain("env 'BETTER_AUTH_URL");
expect($command)->toContain("--secret 'id=BETTER_AUTH_URL,env=BETTER_AUTH_URL'");
expect($command)->toContain("--secret 'id=COOLIFY_URL,env=COOLIFY_URL'");
});
it('creates an empty build-time env file for railpack when there are no generated build-time variables', function () {
[$job, $reflection] = makeRailpackDeploymentJob([
'build_pack' => 'railpack',
'compose_parsing_version' => '3',
]);
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$application = $applicationProperty->getValue($job);
$application->setRelation('settings', new ApplicationSetting([
'include_source_commit_in_build' => false,
'is_env_sorting_enabled' => false,
]));
$application->setRelation('environment_variables', collect([
new EnvironmentVariable(['key' => 'COOLIFY_FQDN']),
new EnvironmentVariable(['key' => 'COOLIFY_URL']),
new EnvironmentVariable(['key' => 'COOLIFY_BRANCH']),
new EnvironmentVariable(['key' => 'COOLIFY_RESOURCE_UUID']),
]));
foreach ([
'application_deployment_queue' => new class
{
public function addLogEntry(string $message, string $type = 'info', bool $hidden = false): void {}
},
'build_pack' => 'railpack',
'pull_request_id' => 0,
] as $property => $value) {
$reflectionProperty = $reflection->getProperty($property);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($job, $value);
}
invokeRailpackMethod($job, $reflection, 'save_buildtime_environment_variables');
expect(collect($job->recordedCommands)->flatten()->implode(' '))->toContain('touch /artifacts/build-time.env');
});
+1 -1
View File
@@ -182,7 +182,7 @@ test('escapeshellarg neutralizes command injection in mariadb password', functio
$escaped = escapeshellarg($maliciousPassword);
// Single quotes in the value get escaped as '\''
expect($escaped)->toBe("'pass'\\'''; whoami; echo '\\'''");
expect($escaped)->toBe("'pass'\\''; whoami; echo '\\'''");
$command = "docker exec container mariadb-dump -u root -p$escaped db";
// Verify the command doesn't contain an unescaped semicolon outside quotes
expect($command)->toContain("-p'pass'");
+87 -31
View File
@@ -4,11 +4,50 @@ use App\Models\Application;
use App\Models\ApplicationSetting;
use App\Models\GitlabApp;
use App\Models\PrivateKey;
use Illuminate\Support\Collection;
afterEach(function () {
Mockery::close();
});
function commandStrings(array|Collection|string $commands): Collection
{
if (is_string($commands)) {
return collect([$commands]);
}
return collect($commands)->map(fn ($command) => data_get($command, 'command') ?? $command[0] ?? $command);
}
function privateKeyMaterializationCommands(array|Collection|string $commands): Collection
{
if (is_string($commands)) {
$commands = [$commands];
}
return collect($commands)->filter(fn ($command) => str(commandStrings([$command])->first())->contains('base64 -d | tee /root/.ssh/id_rsa_coolify_'));
}
function expectCommandListToContain(array|Collection|string $commands, string $expected): void
{
expect(commandStrings($commands)->implode(' && '))->toContain($expected);
}
function expectCommandListNotToContain(array|Collection|string $commands, string $expected): void
{
expect(commandStrings($commands)->implode(' && '))->not->toContain($expected);
}
function expectPrivateKeyMaterializationCommandsSkipLogging(array|Collection|string $commands): void
{
$keyCommands = privateKeyMaterializationCommands($commands);
expect($keyCommands)->not->toBeEmpty();
$keyCommands->each(function ($command): void {
expect(data_get($command, 'skip_command_log'))->toBeTrue();
});
}
/**
* Git operations authenticate with the SSH key assigned in the UI. Coolify writes that key to a
* per-deployment path (/root/.ssh/id_rsa_coolify_<deployment_uuid>) instead of the shared
@@ -19,6 +58,24 @@ afterEach(function () {
*/
$keyPath = '/root/.ssh/id_rsa_coolify_test-deployment-uuid';
it('skips logging the docker deploy key materialization command before ls-remote', function () {
$source = file_get_contents(__DIR__.'/../../app/Jobs/ApplicationDeploymentJob.php');
$commandPosition = strpos($source, 'base64 -d | tee {$customSshKeyLocation}');
expect($commandPosition)->not->toBeFalse()
->and(substr($source, $commandPosition, 200))->toContain("'skip_command_log' => true");
});
it('supports skipping command log entries without adding a hidden command entry', function () {
$source = file_get_contents(__DIR__.'/../../app/Traits/ExecuteRemoteCommand.php');
expect($source)
->toContain('$skip_command_log = data_get($single_command, \'skip_command_log\', false);')
->toContain('if ($command_hidden && ! $skip_command_log && isset($this->application_deployment_queue))')
->toContain('use ($command, $hidden, $customType, $append, $command_hidden, $skip_command_log)')
->toContain('\'command\' => $skip_command_log || $command_hidden ? null : $this->redact_sensitive_info($command),');
});
it('writes a deploy key to a per-deployment path and cleans it up for ls-remote on the host', function () use ($keyPath) {
$privateKey = Mockery::mock(PrivateKey::class)->makePartial();
$privateKey->shouldReceive('getAttribute')->with('private_key')->andReturn('fake-private-key');
@@ -31,11 +88,11 @@ it('writes a deploy key to a per-deployment path and cleans it up for ls-remote
$result = $application->generateGitLsRemoteCommands('test-deployment-uuid', false);
expect($result['commands'])
->toContain("tee {$keyPath}")
->toContain("-i {$keyPath} -o IdentitiesOnly=yes")
->toContain("trap 'rm -f {$keyPath}' EXIT") // removed when the shell exits
->not->toContain('tee /root/.ssh/id_rsa >'); // never overwrites the host root's own key
expectCommandListToContain($result['commands'], "tee {$keyPath}");
expectCommandListToContain($result['commands'], "-i {$keyPath} -o IdentitiesOnly=yes");
expectCommandListToContain($result['commands'], "trap 'rm -f {$keyPath}' EXIT"); // removed when the shell exits
expectCommandListNotToContain($result['commands'], 'tee /root/.ssh/id_rsa >'); // never overwrites the host root's own key
expectPrivateKeyMaterializationCommandsSkipLogging($result['commands']);
});
it('writes a deploy key to a per-deployment path for ls-remote inside docker without a trap', function () use ($keyPath) {
@@ -50,11 +107,11 @@ it('writes a deploy key to a per-deployment path for ls-remote inside docker wit
$result = $application->generateGitLsRemoteCommands('test-deployment-uuid', true);
expect($result['commands'])
->toContain("tee {$keyPath}")
->toContain("-i {$keyPath} -o IdentitiesOnly=yes")
->not->toContain('trap ') // ephemeral container, no cleanup needed
->not->toContain('tee /root/.ssh/id_rsa >');
expectCommandListToContain($result['commands'], "tee {$keyPath}");
expectCommandListToContain($result['commands'], "-i {$keyPath} -o IdentitiesOnly=yes");
expectCommandListNotToContain($result['commands'], 'trap '); // ephemeral container, no cleanup needed
expectCommandListNotToContain($result['commands'], 'tee /root/.ssh/id_rsa >');
expectPrivateKeyMaterializationCommandsSkipLogging($result['commands']);
});
it('writes a GitLab source private key to a per-deployment path with cleanup on the host', function () use ($keyPath) {
@@ -77,11 +134,11 @@ it('writes a GitLab source private key to a per-deployment path with cleanup on
$result = $application->generateGitLsRemoteCommands('test-deployment-uuid', false);
expect($result['commands'])
->toContain("tee {$keyPath}")
->toContain("-i {$keyPath} -o IdentitiesOnly=yes")
->toContain("trap 'rm -f {$keyPath}' EXIT")
->not->toContain('tee /root/.ssh/id_rsa >');
expectCommandListToContain($result['commands'], "tee {$keyPath}");
expectCommandListToContain($result['commands'], "-i {$keyPath} -o IdentitiesOnly=yes");
expectCommandListToContain($result['commands'], "trap 'rm -f {$keyPath}' EXIT");
expectCommandListNotToContain($result['commands'], 'tee /root/.ssh/id_rsa >');
expectPrivateKeyMaterializationCommandsSkipLogging($result['commands']);
});
it('writes a deploy key to a per-deployment path and cleans it up when cloning on the host', function () use ($keyPath) {
@@ -104,11 +161,11 @@ it('writes a deploy key to a per-deployment path and cleans it up when cloning o
// exec_in_docker = false → the loadComposeFile / host clone path
$result = $application->generateGitImportCommands('test-deployment-uuid', 0, null, false);
expect($result['commands'])
->toContain("tee {$keyPath}")
->toContain("-i {$keyPath} -o IdentitiesOnly=yes")
->toContain("trap 'rm -f {$keyPath}' EXIT")
->not->toContain('tee /root/.ssh/id_rsa >');
expectCommandListToContain($result['commands'], "tee {$keyPath}");
expectCommandListToContain($result['commands'], "-i {$keyPath} -o IdentitiesOnly=yes");
expectCommandListToContain($result['commands'], "trap 'rm -f {$keyPath}' EXIT");
expectCommandListNotToContain($result['commands'], 'tee /root/.ssh/id_rsa >');
expectPrivateKeyMaterializationCommandsSkipLogging($result['commands']);
});
it('writes a GitLab source private key to a per-deployment path and cleans it up when cloning on the host', function () use ($keyPath) {
@@ -137,11 +194,11 @@ it('writes a GitLab source private key to a per-deployment path and cleans it up
$result = $application->generateGitImportCommands('test-deployment-uuid', 0, null, false);
expect($result['commands'])
->toContain("tee {$keyPath}")
->toContain("-i {$keyPath} -o IdentitiesOnly=yes")
->toContain("trap 'rm -f {$keyPath}' EXIT")
->not->toContain('tee /root/.ssh/id_rsa >');
expectCommandListToContain($result['commands'], "tee {$keyPath}");
expectCommandListToContain($result['commands'], "-i {$keyPath} -o IdentitiesOnly=yes");
expectCommandListToContain($result['commands'], "trap 'rm -f {$keyPath}' EXIT");
expectCommandListNotToContain($result['commands'], 'tee /root/.ssh/id_rsa >');
expectPrivateKeyMaterializationCommandsSkipLogging($result['commands']);
});
it('uses the per-deployment deploy key for pull request fetches', function () use ($keyPath) {
@@ -163,9 +220,9 @@ it('uses the per-deployment deploy key for pull request fetches', function () us
$result = $application->generateGitImportCommands('test-deployment-uuid', 123, 'github', false);
expect($result['commands'])
->toContain("GIT_SSH_COMMAND=\"ssh -o ConnectTimeout=30 -p 22 -o Port=22 -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i {$keyPath} -o IdentitiesOnly=yes\" git fetch origin pull/123/head:pr-123-coolify")
->not->toContain('GIT_SSH_COMMAND="ssh -o ConnectTimeout=30 -p 22 -o Port=22 -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /root/.ssh/id_rsa" git fetch origin pull/123/head:pr-123-coolify');
expectCommandListToContain($result['commands'], "GIT_SSH_COMMAND=\"ssh -o ConnectTimeout=30 -p 22 -o Port=22 -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i {$keyPath} -o IdentitiesOnly=yes\" git fetch origin pull/123/head:pr-123-coolify");
expectCommandListNotToContain($result['commands'], 'GIT_SSH_COMMAND="ssh -o ConnectTimeout=30 -p 22 -o Port=22 -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /root/.ssh/id_rsa" git fetch origin pull/123/head:pr-123-coolify');
expectPrivateKeyMaterializationCommandsSkipLogging($result['commands']);
});
it('does not force a missing per-deployment key for other repository pull request fetches', function () use ($keyPath) {
@@ -183,7 +240,6 @@ it('does not force a missing per-deployment key for other repository pull reques
$result = $application->generateGitImportCommands('test-deployment-uuid', 123, 'github', false);
expect($result['commands'])
->toContain('GIT_SSH_COMMAND="ssh -o ConnectTimeout=30 -p 22 -o Port=22 -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /root/.ssh/id_rsa" git fetch origin pull/123/head:pr-123-coolify')
->not->toContain($keyPath);
expectCommandListToContain($result['commands'], 'GIT_SSH_COMMAND="ssh -o ConnectTimeout=30 -p 22 -o Port=22 -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /root/.ssh/id_rsa" git fetch origin pull/123/head:pr-123-coolify');
expectCommandListNotToContain($result['commands'], $keyPath);
});
+74
View File
@@ -141,3 +141,77 @@ test('file storage accepts relative dot-prefixed paths', function () {
expect(fn () => validateShellSafePath('./data', 'storage path'))
->not->toThrow(Exception::class);
});
test('file mount path validator rejects parent segments and unsafe separators', function (string $path) {
expect(fn () => validateFileMountPath($path, 'file storage path'))
->toThrow(Exception::class);
})->with([
'parent segment to etc' => ['/../../etc/passwd'],
'embedded parent segment' => ['/foo/../bar'],
'parent segment' => ['/..'],
'double slash before parent segment' => ['/foo//../bar'],
'current directory segment' => ['/foo/./bar'],
'backslash parent segment' => ['\\..\\etc\\passwd'],
'null byte' => ["/app/config\0/../../etc/passwd"],
]);
test('file mount path validator accepts safe absolute container file paths', function (string $path, string $expected) {
expect(validateFileMountPath($path, 'file storage path'))->toBe($expected);
})->with([
'nginx config' => ['/etc/nginx/nginx.conf', '/etc/nginx/nginx.conf'],
'app env filename' => ['/app/.env', '/app/.env'],
'relative input becomes absolute' => ['config/app.yaml', '/config/app.yaml'],
'duplicate slashes collapse' => ['/opt//app///config.json', '/opt/app/config.json'],
]);
test('host file mount path validator accepts absolute host file paths', function () {
expect(validateHostFileMountPath('/etc/nginx/nginx.conf', 'host file path'))
->toBe('/etc/nginx/nginx.conf');
});
test('host file mount path validator rejects ambiguous or directory paths', function (string $path) {
expect(fn () => validateHostFileMountPath($path, 'host file path'))
->toThrow(Exception::class);
})->with([
'relative path' => ['etc/nginx/nginx.conf'],
'root directory' => ['/'],
'trailing slash' => ['/etc/nginx/'],
'parent segment' => ['/etc/../shadow'],
'current segment' => ['/etc/./nginx.conf'],
'backslash' => ['\\etc\\nginx.conf'],
]);
test('confined path resolver keeps file mounts inside their resource configuration root', function () {
expect(confineFileMountPath('/data/coolify/applications/app-uuid', '/etc/nginx/nginx.conf', 'file storage path'))
->toBe('/data/coolify/applications/app-uuid/etc/nginx/nginx.conf');
expect(confineFileMountPath('/data/coolify/databases/db-uuid/', 'postgres/postgresql.conf', 'file storage path'))
->toBe('/data/coolify/databases/db-uuid/postgres/postgresql.conf');
expect(confineFileMountPath('/data/coolify/services/service-uuid', '/config.yaml', 'file storage path'))
->toBe('/data/coolify/services/service-uuid/config.yaml');
});
test('confined path resolver rejects paths that escape the resource configuration root', function (string $base, string $path) {
expect(fn () => confineFileMountPath($base, $path, 'file storage path'))
->toThrow(Exception::class);
})->with([
'application parent segment' => ['/data/coolify/applications/app-uuid', '/../../etc/passwd'],
'database parent segment' => ['/data/coolify/databases/db-uuid', '/postgres/../../../etc/shadow'],
'service dot segment' => ['/data/coolify/services/service-uuid', '/./config.yaml'],
]);
test('local file volume write sink keeps saved managed file paths for compatibility', function () {
$source = file_get_contents(__DIR__.'/../../app/Models/LocalFileVolume.php');
expect($source)->not->toContain('confinePathToBase($workdir, $path->value(), \'storage path\')')
->and($source)->toContain('tee {$escapedPath}');
});
test('host file mounts are bind-only and skipped by server storage writes', function () {
$source = file_get_contents(__DIR__.'/../../app/Models/LocalFileVolume.php');
expect($source)->toContain('if ($this->is_host_file) {')
->and($source)->toContain('return;')
->and($source)->toContain('tee {$escapedPath}');
});
+47 -9
View File
@@ -3,11 +3,45 @@
use App\Models\Application;
use App\Models\GitlabApp;
use App\Models\PrivateKey;
use Illuminate\Support\Collection;
afterEach(function () {
Mockery::close();
});
function gitlabCommandStrings(array|Collection|string $commands): Collection
{
if (is_string($commands)) {
return collect([$commands]);
}
return collect($commands)->map(fn ($command) => data_get($command, 'command') ?? $command[0] ?? $command);
}
function expectGitlabCommandListToContain(array|Collection|string $commands, string $expected): void
{
expect(gitlabCommandStrings($commands)->implode(' && '))->toContain($expected);
}
function expectGitlabCommandListNotToContain(array|Collection|string $commands, string $expected): void
{
expect(gitlabCommandStrings($commands)->implode(' && '))->not->toContain($expected);
}
function expectGitlabPrivateKeyMaterializationCommandsSkipLogging(array|Collection|string $commands): void
{
if (is_string($commands)) {
$commands = [$commands];
}
$keyCommands = collect($commands)->filter(fn ($command) => str(data_get($command, 'command') ?? $command[0] ?? $command)->contains('base64 -d | tee /root/.ssh/id_rsa_coolify_'));
expect($keyCommands)->not->toBeEmpty();
$keyCommands->each(function ($command): void {
expect(data_get($command, 'skip_command_log'))->toBeTrue();
});
}
it('generates ls-remote commands for GitLab source with private key', function () {
$deploymentUuid = 'test-deployment-uuid';
@@ -15,7 +49,8 @@ it('generates ls-remote commands for GitLab source with private key', function (
$privateKey->shouldReceive('getAttribute')->with('private_key')->andReturn('fake-private-key');
$gitlabSource = Mockery::mock(GitlabApp::class)->makePartial();
$gitlabSource->shouldReceive('getMorphClass')->andReturn(\App\Models\GitlabApp::class);
$gitlabSource->shouldReceive('getMorphClass')->andReturn(GitlabApp::class);
$gitlabSource->shouldReceive('getAttribute')->with('html_url')->andReturn('https://gitlab.com');
$gitlabSource->shouldReceive('getAttribute')->with('privateKey')->andReturn($privateKey);
$gitlabSource->shouldReceive('getAttribute')->with('private_key_id')->andReturn(1);
$gitlabSource->shouldReceive('getAttribute')->with('custom_port')->andReturn(22);
@@ -34,16 +69,18 @@ it('generates ls-remote commands for GitLab source with private key', function (
expect($result)->toBeArray();
expect($result)->toHaveKey('commands');
expect($result['commands'])->toContain('git ls-remote');
expect($result['commands'])->toContain('id_rsa');
expect($result['commands'])->toContain('mkdir -p /root/.ssh');
expectGitlabCommandListToContain($result['commands'], 'git ls-remote');
expectGitlabCommandListToContain($result['commands'], 'id_rsa');
expectGitlabCommandListToContain($result['commands'], 'mkdir -p /root/.ssh');
expectGitlabPrivateKeyMaterializationCommandsSkipLogging($result['commands']);
});
it('generates ls-remote commands for GitLab source without private key', function () {
$deploymentUuid = 'test-deployment-uuid';
$gitlabSource = Mockery::mock(GitlabApp::class)->makePartial();
$gitlabSource->shouldReceive('getMorphClass')->andReturn(\App\Models\GitlabApp::class);
$gitlabSource->shouldReceive('getMorphClass')->andReturn(GitlabApp::class);
$gitlabSource->shouldReceive('getAttribute')->with('html_url')->andReturn('https://gitlab.com');
$gitlabSource->shouldReceive('getAttribute')->with('privateKey')->andReturn(null);
$gitlabSource->shouldReceive('getAttribute')->with('private_key_id')->andReturn(null);
@@ -61,17 +98,18 @@ it('generates ls-remote commands for GitLab source without private key', functio
expect($result)->toBeArray();
expect($result)->toHaveKey('commands');
expect($result['commands'])->toContain('git ls-remote');
expect($result['commands'])->toContain('https://gitlab.com/user/repo.git');
expectGitlabCommandListToContain($result['commands'], 'git ls-remote');
expectGitlabCommandListToContain($result['commands'], 'https://gitlab.com/user/repo.git');
// Should NOT contain SSH key setup
expect($result['commands'])->not->toContain('id_rsa');
expectGitlabCommandListNotToContain($result['commands'], 'id_rsa');
});
it('does not return null for GitLab source type', function () {
$deploymentUuid = 'test-deployment-uuid';
$gitlabSource = Mockery::mock(GitlabApp::class)->makePartial();
$gitlabSource->shouldReceive('getMorphClass')->andReturn(\App\Models\GitlabApp::class);
$gitlabSource->shouldReceive('getMorphClass')->andReturn(GitlabApp::class);
$gitlabSource->shouldReceive('getAttribute')->with('html_url')->andReturn('https://gitlab.com');
$gitlabSource->shouldReceive('getAttribute')->with('privateKey')->andReturn(null);
$gitlabSource->shouldReceive('getAttribute')->with('private_key_id')->andReturn(null);
@@ -34,7 +34,7 @@ test('buildRestoreCommand handles PostgreSQL with dumpAll', function () {
$result = $component->buildRestoreCommand('/tmp/test.dump');
expect($result)->toContain('gunzip -cf /tmp/test.dump');
expect($result)->toContain("gunzip -cf '/tmp/test.dump'");
expect($result)->toContain('psql -U ${POSTGRES_USER} -d ${POSTGRES_DB:-${POSTGRES_USER:-postgres}}');
});
@@ -46,7 +46,7 @@ test('buildRestoreCommand handles MySQL without dumpAll', function () {
$result = $component->buildRestoreCommand('/tmp/test.dump');
expect($result)->toContain('mysql -u $MYSQL_USER');
expect($result)->toContain('< /tmp/test.dump');
expect($result)->toContain("< '/tmp/test.dump'");
});
test('buildRestoreCommand handles MariaDB without dumpAll', function () {
@@ -57,7 +57,7 @@ test('buildRestoreCommand handles MariaDB without dumpAll', function () {
$result = $component->buildRestoreCommand('/tmp/test.dump');
expect($result)->toContain('mariadb -u $MARIADB_USER');
expect($result)->toContain('< /tmp/test.dump');
expect($result)->toContain("< '/tmp/test.dump'");
});
test('buildRestoreCommand always appends the MongoDB archive path', function (bool $dumpAll) {
@@ -68,5 +68,5 @@ test('buildRestoreCommand always appends the MongoDB archive path', function (bo
$result = $component->buildRestoreCommand('/tmp/test.dump');
expect($result)->toContain('mongorestore');
expect($result)->toContain('--archive=/tmp/test.dump');
expect($result)->toContain("--archive='/tmp/test.dump'");
})->with([false, true]);
@@ -0,0 +1,36 @@
<?php
use App\Jobs\SendMessageToDiscordJob;
use App\Jobs\SendMessageToSlackJob;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
uses(TestCase::class);
it('blocks queued Slack notifications to IPv4-mapped link-local URLs', function () {
Http::fake();
$job = new SendMessageToSlackJob(
new SlackMessage('Test', 'Description'),
'http://[::ffff:169.254.169.254]/'
);
$job->handle();
Http::assertNothingSent();
});
it('blocks queued Discord notifications to IPv4-mapped link-local URLs', function () {
Http::fake();
$job = new SendMessageToDiscordJob(
new DiscordMessage('Test', 'Description', DiscordMessage::infoColor()),
'http://[::ffff:169.254.169.254]/'
);
$job->handle();
Http::assertNothingSent();
});
+92
View File
@@ -0,0 +1,92 @@
<?php
use App\Models\Team;
use App\Models\User;
use App\Policies\TeamPolicy;
function teamPolicyUserWithTeams(array $teamIds): User
{
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn(collect(
array_map(fn (int $teamId): object => (object) ['id' => $teamId], $teamIds)
));
return $user;
}
function teamPolicyTeam(int $teamId): Team
{
$team = Mockery::mock(Team::class)->makePartial();
$team->shouldReceive('getAttribute')->with('id')->andReturn($teamId);
return $team;
}
it('allows any authenticated user to view any teams list', function () {
$user = Mockery::mock(User::class)->makePartial();
expect((new TeamPolicy)->viewAny($user))->toBeTrue();
});
it('allows authenticated users to create teams', function () {
$user = Mockery::mock(User::class)->makePartial();
expect((new TeamPolicy)->create($user))->toBeTrue();
});
it('allows target team members to view the team', function () {
$user = teamPolicyUserWithTeams([1]);
$team = teamPolicyTeam(1);
expect((new TeamPolicy)->view($user, $team))->toBeTrue();
});
it('denies non-members from viewing the team', function () {
$user = teamPolicyUserWithTeams([2]);
$team = teamPolicyTeam(1);
expect((new TeamPolicy)->view($user, $team))->toBeFalse();
});
it('allows target team admins to perform privileged team actions', function (string $ability) {
$user = teamPolicyUserWithTeams([1]);
$user->shouldReceive('isAdminOfTeam')->with(1)->andReturn(true);
$team = teamPolicyTeam(1);
expect((new TeamPolicy)->{$ability}($user, $team))->toBeTrue();
})->with([
'update',
'delete',
'manageMembers',
'viewAdmin',
'manageInvitations',
]);
it('denies target team members even when their current session role is admin elsewhere', function (string $ability) {
$user = teamPolicyUserWithTeams([1, 2]);
$user->shouldReceive('isAdmin')->andReturn(true);
$user->shouldReceive('isOwner')->andReturn(false);
$user->shouldReceive('isAdminOfTeam')->with(1)->andReturn(false);
$team = teamPolicyTeam(1);
expect((new TeamPolicy)->{$ability}($user, $team))->toBeFalse();
})->with([
'update',
'delete',
'manageMembers',
'viewAdmin',
'manageInvitations',
]);
it('denies non-members from privileged team actions', function (string $ability) {
$user = teamPolicyUserWithTeams([2]);
$team = teamPolicyTeam(1);
expect((new TeamPolicy)->{$ability}($user, $team))->toBeFalse();
})->with([
'update',
'delete',
'manageMembers',
'viewAdmin',
'manageInvitations',
]);
@@ -37,10 +37,8 @@ test('validateBucketName accepts valid bucket names', function () {
// Valid bucket names
expect($method->invoke($component, 'my-bucket'))->toBeTrue();
expect($method->invoke($component, 'my_bucket'))->toBeTrue();
expect($method->invoke($component, 'mybucket123'))->toBeTrue();
expect($method->invoke($component, 'my.bucket.name'))->toBeTrue();
expect($method->invoke($component, 'Bucket-Name_123'))->toBeTrue();
});
test('validateBucketName rejects invalid bucket names', function () {
@@ -55,6 +53,9 @@ test('validateBucketName rejects invalid bucket names', function () {
expect($method->invoke($component, 'bucket&ls'))->toBeFalse();
expect($method->invoke($component, "bucket\nid"))->toBeFalse();
expect($method->invoke($component, 'bucket name'))->toBeFalse(); // Space not allowed in bucket
expect($method->invoke($component, 'my_bucket'))->toBeFalse();
expect($method->invoke($component, 'Bucket-Name'))->toBeFalse();
expect($method->invoke($component, '192.168.1.1'))->toBeFalse();
});
test('validateS3Path accepts valid S3 paths', function () {
@@ -23,8 +23,9 @@ it('rejects SSRF payloads on the S3 endpoint', function (string $endpoint) {
expect($validator->fails())->toBeTrue("Expected rejection: {$endpoint}");
})->with([
'AWS IMDS' => 'http://169.254.169.254/latest/meta-data/',
'AWS IMDS bare' => 'http://169.254.169.254',
'link-local address' => 'http://169.254.169.254/',
'link-local address bare' => 'http://169.254.169.254',
'link-local address IPv4-mapped IPv6' => 'http://[::ffff:169.254.169.254]/',
'GCP metadata via link-local' => 'http://169.254.0.1',
'loopback v4' => 'http://127.0.0.1',
'loopback Redis' => 'http://127.0.0.1:6379',
@@ -87,5 +88,6 @@ it('blocks testConnection() for loopback endpoints', function (string $endpoint)
'http loopback' => 'http://127.0.0.1:6379',
'localhost' => 'http://localhost:9000',
'IPv6 loopback' => 'http://[::1]',
'IPv4-mapped IPv6 link-local' => 'http://[::ffff:169.254.169.254]',
'internal TLD' => 'http://backend.internal',
]);
+26
View File
@@ -53,6 +53,7 @@ test('S3Storage model fillable attributes are configured correctly', function ()
$s3Storage = new S3Storage;
expect($s3Storage->getFillable())->toBe([
'team_id',
'name',
'description',
'region',
@@ -74,6 +75,7 @@ test('S3Storage connection validation uses short s3 client timeouts', function (
->with(Mockery::on(function (array $config) {
expect($config['http']['connect_timeout'])->toBe(15);
expect($config['http']['timeout'])->toBe(15);
expect($config['http']['allow_redirects'])->toBeFalse();
return true;
}))
@@ -118,3 +120,27 @@ test('S3Storage connection validation returns friendly timeout error', function
expect($s3Storage->is_usable)->toBeFalse();
});
test('S3Storage testConnection rejects invalid bucket before building client', function (string $bucket) {
Storage::shouldReceive('build')->never();
$s3Storage = new S3Storage;
$s3Storage->setRawAttributes([
'name' => 'Test S3',
'region' => 'us-east-1',
'key' => 'AKIAEXAMPLE',
'secret' => 'secret',
'bucket' => $bucket,
'endpoint' => 'https://s3.amazonaws.com',
]);
expect(fn () => $s3Storage->testConnection())
->toThrow(RuntimeException::class, 'S3 bucket name is not allowed');
})->with([
'semicolon injection' => ['lab; id; #'],
'command substitution' => ['lab$(id)'],
'backticks' => ['lab`id`'],
'newline' => ["lab\nid"],
'underscore' => ['lab_bucket'],
'uppercase' => ['LabBucket'],
]);
+40 -1
View File
@@ -11,7 +11,7 @@ it('accepts valid public URLs', function () {
$validUrls = [
'https://api.github.com',
'https://github.example.com/api/v3',
'https://github.com/api/v3',
'https://example.com',
'http://example.com',
];
@@ -22,6 +22,14 @@ it('accepts valid public URLs', function () {
}
});
it('accepts custom external hostnames that resolve to public IPs', function () {
$rule = new SafeExternalUrl(fn (string $host): array => ['93.184.216.34']);
$validator = Validator::make(['url' => 'https://github.example.com/api/v3'], ['url' => $rule]);
expect($validator->passes())->toBeTrue('Expected valid custom external hostname');
});
it('rejects private IPv4 addresses', function (string $url) {
$rule = new SafeExternalUrl;
@@ -42,6 +50,34 @@ it('rejects cloud metadata IP', function () {
expect($validator->fails())->toBeTrue('Expected rejection: cloud metadata IP');
});
it('rejects hostnames that resolve to private or reserved addresses', function (string $url, array $resolvedIps) {
$rule = new SafeExternalUrl(fn (string $host): array => $resolvedIps);
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("Expected rejection after DNS resolution: {$url}");
})->with([
'hostname to link-local IP' => ['http://169.254.169.254.nip.io/', ['169.254.169.254']],
'hostname to loopback' => ['http://loopback.example.test/', ['127.0.0.1']],
'hostname to private IPv4' => ['http://private.example.test/', ['10.0.0.1']],
'hostname to IPv6 loopback' => ['http://ipv6-loopback.example.test/', ['::1']],
'hostname to IPv6 link-local' => ['http://ipv6-link-local.example.test/', ['fe80::1']],
'hostname to IPv6 ULA' => ['http://ipv6-ula.example.test/', ['fc00::1']],
'hostname to mapped private IPv4' => ['http://mapped-private.example.test/', ['::ffff:10.0.0.1']],
]);
it('rejects IPv4-mapped IPv6 literals for private or reserved IPv4 ranges', function (string $url) {
$rule = new SafeExternalUrl;
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("Expected rejection: {$url}");
})->with([
'mapped link-local IP' => 'http://[::ffff:169.254.169.254]/',
'mapped loopback' => 'http://[::ffff:127.0.0.1]/',
'mapped private' => 'http://[::ffff:10.0.0.1]/',
]);
it('rejects localhost and internal hostnames', function (string $url) {
$rule = new SafeExternalUrl;
@@ -50,9 +86,12 @@ it('rejects localhost and internal hostnames', function (string $url) {
})->with([
'localhost' => 'http://localhost',
'localhost with port' => 'http://localhost:8080',
'localhost with trailing dot' => 'http://localhost.',
'zero address' => 'http://0.0.0.0',
'.local domain' => 'http://myservice.local',
'.local domain with trailing dot' => 'http://myservice.local.',
'.internal domain' => 'http://myservice.internal',
'.internal domain with trailing dot' => 'http://myservice.internal.',
]);
it('rejects non-URL strings', function (string $value) {
+29
View File
@@ -59,6 +59,33 @@ it('rejects link-local range', function () {
expect($validator->fails())->toBeTrue('Expected rejection: link-local IP');
});
it('rejects hostnames that resolve to blocked addresses', function (string $url, array $resolvedIps) {
$rule = new SafeWebhookUrl(fn (string $host): array => $resolvedIps);
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("Expected rejection after DNS resolution: {$url}");
})->with([
'hostname to link-local IP' => ['http://169.254.169.254.nip.io/', ['169.254.169.254']],
'hostname to loopback' => ['http://loopback.example.test/', ['127.0.0.1']],
'hostname to IPv6 loopback' => ['http://ipv6-loopback.example.test/', ['::1']],
'hostname to IPv6 link-local' => ['http://ipv6-link-local.example.test/', ['fe80::1']],
'hostname to IPv6 ULA' => ['http://ipv6-ula.example.test/', ['fc00::1']],
'hostname to mapped link-local IP' => ['http://mapped-link-local.example.test/', ['::ffff:169.254.169.254']],
]);
it('rejects IPv4-mapped IPv6 literals for blocked IPv4 ranges', function (string $url) {
$rule = new SafeWebhookUrl;
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("Expected rejection: {$url}");
})->with([
'mapped link-local IP' => 'http://[::ffff:169.254.169.254]/',
'mapped loopback' => 'http://[::ffff:127.0.0.1]/',
'mapped zero' => 'http://[::ffff:0.0.0.0]/',
]);
it('rejects localhost and internal hostnames', function (string $url) {
$rule = new SafeWebhookUrl;
@@ -67,7 +94,9 @@ it('rejects localhost and internal hostnames', function (string $url) {
})->with([
'localhost' => 'http://localhost',
'localhost with port' => 'http://localhost:8080',
'localhost with trailing dot' => 'http://localhost.',
'.internal domain' => 'http://myservice.internal',
'.internal domain with trailing dot' => 'http://myservice.internal.',
]);
it('rejects non-http schemes', function (string $value) {
+14 -17
View File
@@ -2,7 +2,6 @@
use App\Jobs\SendWebhookJob;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Tests\TestCase;
uses(TestCase::class);
@@ -24,11 +23,6 @@ it('sends webhook to valid URLs', function () {
it('blocks webhook to loopback address', function () {
Http::fake();
Log::shouldReceive('warning')
->once()
->withArgs(function ($message) {
return str_contains($message, 'blocked unsafe webhook URL');
});
$job = new SendWebhookJob(
payload: ['event' => 'test'],
@@ -42,15 +36,23 @@ it('blocks webhook to loopback address', function () {
it('blocks webhook to cloud metadata endpoint', function () {
Http::fake();
Log::shouldReceive('warning')
->once()
->withArgs(function ($message) {
return str_contains($message, 'blocked unsafe webhook URL');
});
$job = new SendWebhookJob(
payload: ['event' => 'test'],
webhookUrl: 'http://169.254.169.254/latest/meta-data/'
webhookUrl: 'http://169.254.169.254/'
);
$job->handle();
Http::assertNothingSent();
});
it('blocks webhook to IPv4-mapped IPv6 link-local endpoint', function () {
Http::fake();
$job = new SendWebhookJob(
payload: ['event' => 'test'],
webhookUrl: 'http://[::ffff:169.254.169.254]/'
);
$job->handle();
@@ -60,11 +62,6 @@ it('blocks webhook to cloud metadata endpoint', function () {
it('blocks webhook to localhost', function () {
Http::fake();
Log::shouldReceive('warning')
->once()
->withArgs(function ($message) {
return str_contains($message, 'blocked unsafe webhook URL');
});
$job = new SendWebhookJob(
payload: ['event' => 'test'],
@@ -0,0 +1,24 @@
<?php
use App\Livewire\Storage\Create;
use App\Livewire\Storage\Form;
use App\Rules\ValidS3BucketName;
function storageRulesFor(string $componentClass): array
{
$component = new $componentClass;
$method = new ReflectionMethod($component, 'rules');
$method->setAccessible(true);
return $method->invoke($component);
}
it('uses the shared S3 bucket rule in storage create and edit forms', function (string $componentClass) {
$bucketRules = storageRulesFor($componentClass)['bucket'];
expect($bucketRules)->toContain('required')
->and(collect($bucketRules)->contains(fn ($rule) => $rule instanceof ValidS3BucketName))->toBeTrue();
})->with([
'create form' => [Create::class],
'edit form' => [Form::class],
]);
+48
View File
@@ -0,0 +1,48 @@
<?php
use App\Rules\ValidS3BucketName;
function validS3BucketNameRulePasses(string $bucket): bool
{
$failed = false;
(new ValidS3BucketName)->validate('bucket', $bucket, function () use (&$failed) {
$failed = true;
});
return ! $failed;
}
it('accepts valid s3 bucket names', function (string $bucket) {
expect(validS3BucketNameRulePasses($bucket))->toBeTrue("Expected accepted: {$bucket}");
})->with([
'short' => ['abc'],
'simple' => ['coolify-backups'],
'dots' => ['coolify.backups'],
'digits' => ['backup-123'],
'max length' => [str_repeat('a', 63)],
]);
it('rejects invalid s3 bucket names and injection payloads', function (string $bucket) {
expect(validS3BucketNameRulePasses($bucket))->toBeFalse("Expected rejected: {$bucket}");
})->with([
'too short' => ['ab'],
'too long' => [str_repeat('a', 64)],
'uppercase' => ['CoolifyBackups'],
'underscore' => ['coolify_backups'],
'leading hyphen' => ['-coolify-backups'],
'trailing hyphen' => ['coolify-backups-'],
'leading dot' => ['.coolify-backups'],
'trailing dot' => ['coolify-backups.'],
'consecutive dots' => ['coolify..backups'],
'dot hyphen' => ['coolify.-backups'],
'hyphen dot' => ['coolify-.backups'],
'ipv4 address' => ['192.168.1.1'],
'semicolon injection' => ['lab; id; #'],
'command substitution' => ['lab$(id)'],
'backticks' => ['lab`id`'],
'pipe' => ['lab|id'],
'ampersand' => ['lab&id'],
'space' => ['lab bucket'],
'newline' => ["lab\nid"],
]);
+15 -8
View File
@@ -132,24 +132,31 @@ it('generates nullable dockerNetworkRules when not required', function () {
->not->toContain('required');
});
it('accepts Docker-compatible environment variable keys', function (string $key) {
it('accepts shell-safe environment variable keys', function (string $key) {
expect(ValidationPatterns::isValidEnvironmentVariableKey($key))->toBeTrue();
})->with([
'letters' => 'APP_ENV',
'leading underscore' => '_TOKEN',
'railpack control variable' => 'RAILPACK_NODE_VERSION',
'digits after first character' => 'NODE_VERSION_20',
'starts with digit' => '1BAD',
'hyphen' => 'BAD-KEY',
'dot' => 'node.name',
'lowercase' => 'node_version',
'dot notation' => 'node.name',
'uppercase dots' => 'XPACK.SECURITY.ENABLED',
'semicolon' => 'BAD;KEY',
'space' => 'BAD KEY',
]);
it('rejects environment variable keys Docker cannot represent', function (string $key) {
it('rejects invalid environment variable keys', function (string $key) {
expect(ValidationPatterns::isValidEnvironmentVariableKey($key))->toBeFalse();
})->with([
'starts with digit' => '1BAD',
'hyphen' => 'BAD-KEY',
'semicolon' => 'BAD;KEY',
'space' => 'BAD KEY',
'command substitution' => 'BAD$(id)',
'backticks' => 'BAD`id`',
'pipe' => 'BAD|id',
'ampersand' => 'BAD&id',
'newline' => 'BAD
KEY',
'equals' => 'BAD=KEY',
'empty' => '',
]);
@@ -164,7 +171,7 @@ it('generates environment variable key rules with correct defaults', function ()
});
it('normalizes environment variable keys by trimming surrounding whitespace', function () {
expect(ValidationPatterns::normalizeEnvironmentVariableKey(' node.name '))->toBe('node.name');
expect(ValidationPatterns::normalizeEnvironmentVariableKey(' APP_ENV '))->toBe('APP_ENV');
});
it('normalizes environment variable keys before model validation', function () {