Merge remote-tracking branch 'origin/next' into audit-policies

This commit is contained in:
Andras Bacsai committed 2026-05-11 21:13:57 +02:00
commit c175d3d282
259 files changed
+12779 -3172

No files matched your search

+71
View File
@@ -446,3 +446,74 @@ describe('POST /api/v1/servers/hetzner', function () {
$response->assertStatus(401);
});
});
describe('error responses do not leak exception details', function () {
test('locations endpoint returns generic 500 message on upstream failure', function () {
Http::fake([
'https://api.hetzner.cloud/v1/locations*' => Http::response([
'error' => ['message' => 'INTERNAL_LEAK_TOKEN_abc /var/secret/path'],
], 500),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/locations?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(500);
$response->assertExactJson(['message' => 'Failed to fetch Hetzner locations.']);
expect($response->getContent())->not->toContain('INTERNAL_LEAK_TOKEN_abc');
expect($response->getContent())->not->toContain('/var/secret/path');
});
test('server-types endpoint returns generic 500 message on upstream failure', function () {
Http::fake([
'https://api.hetzner.cloud/v1/server_types*' => Http::response([
'error' => ['message' => 'INTERNAL_LEAK_TOKEN_abc'],
], 500),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/server-types?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(500);
$response->assertExactJson(['message' => 'Failed to fetch Hetzner server types.']);
expect($response->getContent())->not->toContain('INTERNAL_LEAK_TOKEN_abc');
});
test('images endpoint returns generic 500 message on upstream failure', function () {
Http::fake([
'https://api.hetzner.cloud/v1/images*' => Http::response([
'error' => ['message' => 'INTERNAL_LEAK_TOKEN_abc'],
], 500),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/images?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(500);
$response->assertExactJson(['message' => 'Failed to fetch Hetzner images.']);
expect($response->getContent())->not->toContain('INTERNAL_LEAK_TOKEN_abc');
});
test('ssh-keys endpoint returns generic 500 message on upstream failure', function () {
Http::fake([
'https://api.hetzner.cloud/v1/ssh_keys*' => Http::response([
'error' => ['message' => 'INTERNAL_LEAK_TOKEN_abc'],
], 500),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/ssh-keys?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(500);
$response->assertExactJson(['message' => 'Failed to fetch Hetzner SSH keys.']);
expect($response->getContent())->not->toContain('INTERNAL_LEAK_TOKEN_abc');
});
});
+345
View File
@@ -0,0 +1,345 @@
<?php
use App\Models\Application;
use App\Models\Environment;
use App\Models\InstanceSettings;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
uses(RefreshDatabase::class);
beforeEach(function () {
InstanceSettings::unguarded(fn () => InstanceSettings::firstOrCreate(['id' => 0]));
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
session(['currentTeam' => $this->team]);
$plainTextToken = Str::random(40);
$token = $this->user->tokens()->create([
'name' => 'railpack-api-test-'.Str::random(6),
'token' => hash('sha256', $plainTextToken),
'abilities' => ['*'],
'team_id' => $this->team->id,
]);
$this->bearerToken = $token->getKey().'|'.$plainTextToken;
$this->server = Server::factory()->create(['team_id' => $this->team->id]);
$this->destination = StandaloneDocker::where('server_id', $this->server->id)->first();
$this->project = Project::factory()->create(['team_id' => $this->team->id]);
$this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
});
function railpackApiHeaders(string $bearerToken): array
{
return [
'Authorization' => 'Bearer '.$bearerToken,
'Content-Type' => 'application/json',
];
}
function makeRailpackApp(array $overrides = []): Application
{
return Application::factory()->create(array_merge([
'environment_id' => test()->environment->id,
'destination_id' => test()->destination->id,
'destination_type' => test()->destination->getMorphClass(),
'build_pack' => 'railpack',
], $overrides));
}
describe('PATCH /api/v1/applications/{uuid} build_pack=railpack', function () {
test('rejects unsupported build_pack at controller layer', function () {
$app = makeRailpackApp();
$response = $this->withHeaders(railpackApiHeaders($this->bearerToken))
->patchJson("/api/v1/applications/{$app->uuid}", [
'build_pack' => 'totally-bogus',
]);
$response->assertStatus(422);
});
test('switching from dockerfile to railpack clears dockerfile fields', function () {
$app = makeRailpackApp([
'build_pack' => 'dockerfile',
'dockerfile' => 'FROM node:20',
'dockerfile_location' => '/Dockerfile',
'dockerfile_target_build' => 'production',
'custom_healthcheck_found' => true,
]);
$response = $this->withHeaders(railpackApiHeaders($this->bearerToken))
->patchJson("/api/v1/applications/{$app->uuid}", [
'build_pack' => 'railpack',
]);
$response->assertOk();
$app->refresh();
expect($app->build_pack)->toBe('railpack');
expect($app->dockerfile)->toBeNull();
// NOTE: dockerfile_location is normalized to '/Dockerfile' by the model
// mutator when set to null, so we cannot assert it becomes null here.
expect($app->dockerfile_target_build)->toBeNull();
expect((bool) $app->custom_healthcheck_found)->toBeFalse();
});
test('switching from dockercompose to railpack clears compose fields and SERVICE_* envs', function () {
$app = makeRailpackApp([
'build_pack' => 'dockercompose',
'docker_compose_domains' => '{"app": "example.com"}',
'docker_compose_raw' => "version: '3'\nservices:\n app:\n image: nginx",
]);
$app->environment_variables()->createMany([
['key' => 'SERVICE_FQDN_APP', 'value' => 'app.example.com', 'is_buildtime' => false, 'is_preview' => false],
['key' => 'SERVICE_URL_APP', 'value' => 'http://app.example.com', 'is_buildtime' => false, 'is_preview' => false],
['key' => 'REGULAR_VAR', 'value' => 'keep_me', 'is_buildtime' => false, 'is_preview' => false],
]);
$response = $this->withHeaders(railpackApiHeaders($this->bearerToken))
->patchJson("/api/v1/applications/{$app->uuid}", [
'build_pack' => 'railpack',
]);
$response->assertOk();
$app->refresh();
expect($app->build_pack)->toBe('railpack');
expect($app->docker_compose_domains)->toBeNull();
expect($app->docker_compose_raw)->toBeNull();
expect($app->environment_variables()->where('key', 'SERVICE_FQDN_APP')->count())->toBe(0);
expect($app->environment_variables()->where('key', 'SERVICE_URL_APP')->count())->toBe(0);
expect($app->environment_variables()->where('key', 'REGULAR_VAR')->count())->toBe(1);
});
test('install/build/start commands persist for railpack apps', function () {
$app = makeRailpackApp();
$response = $this->withHeaders(railpackApiHeaders($this->bearerToken))
->patchJson("/api/v1/applications/{$app->uuid}", [
'install_command' => 'npm ci',
'build_command' => 'npm run build',
'start_command' => 'node server.js',
]);
$response->assertOk();
$app->refresh();
expect($app->install_command)->toBe('npm ci');
expect($app->build_command)->toBe('npm run build');
expect($app->start_command)->toBe('node server.js');
});
});
describe('POST /api/v1/applications/{uuid}/envs RAILPACK_* handling', function () {
test('adding RAILPACK_NODE_VERSION via API surfaces in railpack_environment_variables only', function () {
$app = makeRailpackApp();
$response = $this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'RAILPACK_NODE_VERSION',
'value' => '20',
'is_buildtime' => true,
'is_runtime' => false,
'is_preview' => false,
]);
$response->assertCreated();
$app->refresh();
expect($app->railpack_environment_variables)->toHaveCount(1);
expect($app->railpack_environment_variables->first()->key)->toBe('RAILPACK_NODE_VERSION');
expect($app->runtime_environment_variables->where('key', 'RAILPACK_NODE_VERSION'))->toHaveCount(0);
});
test('runtime envs added via API surface in runtime_environment_variables but not railpack_*', function () {
$app = makeRailpackApp();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'APP_ENV',
'value' => 'production',
'is_runtime' => true,
'is_buildtime' => false,
'is_preview' => false,
])->assertCreated();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '18',
'is_buildtime' => true,
'is_runtime' => false,
'is_preview' => false,
])->assertCreated();
$app->refresh();
$runtime = $app->runtime_environment_variables;
expect($runtime->pluck('key')->all())->toBe(['APP_ENV']);
expect($app->railpack_environment_variables)->toHaveCount(0);
});
test('preview RAILPACK_* envs surface in railpack_environment_variables_preview only', function () {
$app = makeRailpackApp();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'RAILPACK_BUILD_CMD',
'value' => 'npm run build',
'is_buildtime' => true,
'is_runtime' => false,
'is_preview' => true,
])->assertCreated();
$app->refresh();
expect($app->railpack_environment_variables_preview)->toHaveCount(1);
expect($app->railpack_environment_variables)->toHaveCount(0);
});
test('buildtime-only env has is_buildtime=true and is_runtime=false', function () {
$app = makeRailpackApp();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'API_KEY',
'value' => 'sekret',
'is_buildtime' => true,
'is_runtime' => false,
'is_preview' => false,
])->assertCreated();
$app->refresh();
$env = $app->environment_variables()->where('key', 'API_KEY')->first();
expect($env)->not->toBeNull();
expect((bool) $env->is_buildtime)->toBeTrue();
expect((bool) $env->is_runtime)->toBeFalse();
// Buildtime-only non-RAILPACK_ var: visible to runtime relation (it's not a buildpack-control var)
// but is_runtime flag is false; consumers gate runtime via is_runtime, not via the relation alone.
expect($env->resourceable_id)->toBe($app->id);
});
test('runtime-only env has is_runtime=true and is_buildtime=false', function () {
$app = makeRailpackApp();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'LOG_LEVEL',
'value' => 'debug',
'is_buildtime' => false,
'is_runtime' => true,
'is_preview' => false,
])->assertCreated();
$app->refresh();
$env = $app->environment_variables()->where('key', 'LOG_LEVEL')->first();
expect((bool) $env->is_buildtime)->toBeFalse();
expect((bool) $env->is_runtime)->toBeTrue();
});
test('railpack build variables collection includes only is_buildtime=true entries', function () {
// Sanity check the underlying query used by the deploy job: railpack_build_variables()
// pulls $application->environment_variables()->where('is_buildtime', true)->get()
// (see ApplicationDeploymentJob::railpack_build_variables).
$app = makeRailpackApp();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'BUILD_ARG',
'value' => 'in-build',
'is_buildtime' => true,
'is_runtime' => false,
'is_preview' => false,
])->assertCreated();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'RUNTIME_ARG',
'value' => 'in-runtime',
'is_buildtime' => false,
'is_runtime' => true,
'is_preview' => false,
])->assertCreated();
$app->refresh();
$buildtime = $app->environment_variables()->where('is_buildtime', true)->pluck('key')->all();
expect($buildtime)->toContain('BUILD_ARG');
expect($buildtime)->not->toContain('RUNTIME_ARG');
});
test('user-defined COOLIFY_FQDN takes precedence over auto-generated', function () {
// Documents generate_coolify_env_variables() override behavior:
// it skips generation when application->environment_variables already has the key.
$app = makeRailpackApp();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'COOLIFY_FQDN',
'value' => 'overridden.example.com',
'is_buildtime' => true,
'is_runtime' => true,
'is_preview' => false,
])->assertCreated();
$app->refresh();
$env = $app->environment_variables()->where('key', 'COOLIFY_FQDN')->first();
expect($env)->not->toBeNull();
expect($env->value)->toBe('overridden.example.com');
// Confirm the model relation used by override-skip logic finds it
expect($app->environment_variables->where('key', 'COOLIFY_FQDN')->isEmpty())->toBeFalse();
});
test('is_literal flag persists on create', function () {
$app = makeRailpackApp();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'RAILPACK_LITERAL_FLAG',
'value' => '$NOT_INTERPOLATED',
'is_buildtime' => true,
'is_runtime' => false,
'is_preview' => false,
'is_literal' => true,
])->assertCreated();
$app->refresh();
$env = $app->environment_variables()->where('key', 'RAILPACK_LITERAL_FLAG')->first();
expect((bool) $env->is_literal)->toBeTrue();
});
test('PATCH env updates buildtime/runtime flags', function () {
$app = makeRailpackApp();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->postJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'TOGGLE_VAR',
'value' => 'v1',
'is_buildtime' => true,
'is_runtime' => true,
'is_preview' => false,
])->assertCreated();
$this->withHeaders(railpackApiHeaders($this->bearerToken))
->patchJson("/api/v1/applications/{$app->uuid}/envs", [
'key' => 'TOGGLE_VAR',
'value' => 'v2',
'is_buildtime' => false,
'is_runtime' => true,
'is_multiline' => false,
'is_shown_once' => false,
])->assertStatus(201);
$app->refresh();
$env = $app->environment_variables()->where('key', 'TOGGLE_VAR')->first();
expect($env->value)->toBe('v2');
expect((bool) $env->is_buildtime)->toBeFalse();
expect((bool) $env->is_runtime)->toBeTrue();
});
});
+81
View File
@@ -0,0 +1,81 @@
<?php
use App\Livewire\Security\ApiTokens;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
session(['currentTeam' => $this->team]);
$this->actingAs($this->user);
});
describe('token creation with expiration', function () {
test('livewire component stores expires_at when expiresInDays set', function () {
Livewire::test(ApiTokens::class)
->set('description', 'test-token')
->set('expiresInDays', 7)
->set('permissions', ['read'])
->call('addNewToken')
->assertHasNoErrors();
$token = $this->user->tokens()->latest()->first();
expect($token)->not->toBeNull()
->and($token->expires_at)->not->toBeNull()
->and($token->expires_at->diffInDays(now()))->toBeGreaterThanOrEqual(6)
->and($token->expires_at->diffInDays(now()))->toBeLessThanOrEqual(7);
});
test('livewire component stores null expires_at when expiresInDays null (Never)', function () {
Livewire::test(ApiTokens::class)
->set('description', 'never-token')
->set('expiresInDays', null)
->set('permissions', ['read'])
->call('addNewToken')
->assertHasNoErrors();
$token = $this->user->tokens()->latest()->first();
expect($token)->not->toBeNull()
->and($token->expires_at)->toBeNull();
});
test('livewire component rejects invalid expiresInDays value', function () {
Livewire::test(ApiTokens::class)
->set('description', 'bad-token')
->set('expiresInDays', 42)
->set('permissions', ['read'])
->call('addNewToken')
->assertHasErrors('expiresInDays');
});
});
describe('expired token rejected on API', function () {
test('request with expired token returns 401', function () {
$token = $this->user->createToken('expired', ['read'], now()->subDay());
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token->plainTextToken,
])->getJson('/api/v1/projects');
$response->assertStatus(401);
});
test('request with non-expired token works', function () {
$token = $this->user->createToken('valid', ['read'], now()->addDay());
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token->plainTextToken,
])->getJson('/api/v1/projects');
$response->assertStatus(200);
});
});
@@ -0,0 +1,83 @@
<?php
use App\Jobs\ApiTokenExpirationWarningJob;
use App\Models\PersonalAccessToken;
use App\Models\Team;
use App\Models\User;
use App\Notifications\ApiTokenExpiringNotification;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Notification;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
$this->team->emailNotificationSettings()->update(['use_instance_email_settings' => true]);
$this->team->discordNotificationSettings()->update([
'discord_enabled' => true,
'discord_webhook_url' => 'https://discord.com/api/webhooks/fake/fake',
]);
session(['currentTeam' => $this->team]);
$this->actingAs($this->user);
Cache::flush();
Notification::fake();
});
function createTokenExpiring(User $user, Team $team, ?Carbon $expiresAt): PersonalAccessToken
{
$plain = $user->createToken('t-'.uniqid(), ['read'], $expiresAt);
$token = $plain->accessToken;
$token->team_id = $team->id;
$token->save();
return $token->fresh();
}
describe('ApiTokenExpirationWarningJob', function () {
test('notifies team when token expires within 24h', function () {
createTokenExpiring($this->user, $this->team, now()->addHours(23));
(new ApiTokenExpirationWarningJob)->handle();
Notification::assertSentTo($this->team, ApiTokenExpiringNotification::class);
});
test('rate limiter prevents duplicate warnings on repeat runs', function () {
createTokenExpiring($this->user, $this->team, now()->addHours(12));
(new ApiTokenExpirationWarningJob)->handle();
(new ApiTokenExpirationWarningJob)->handle();
Notification::assertSentToTimes($this->team, ApiTokenExpiringNotification::class, 1);
});
test('skips tokens expiring more than 24h out', function () {
createTokenExpiring($this->user, $this->team, now()->addDays(3));
(new ApiTokenExpirationWarningJob)->handle();
Notification::assertNothingSent();
});
test('skips already-expired tokens', function () {
createTokenExpiring($this->user, $this->team, now()->subHour());
(new ApiTokenExpirationWarningJob)->handle();
Notification::assertNothingSent();
});
test('skips tokens with null expires_at', function () {
createTokenExpiring($this->user, $this->team, null);
(new ApiTokenExpirationWarningJob)->handle();
Notification::assertNothingSent();
});
});
@@ -78,26 +78,29 @@ describe('Application Model Buildpack Cleanup', function () {
// Add environment variables that should be deleted
EnvironmentVariable::create([
'application_id' => $application->id,
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'SERVICE_FQDN_APP',
'value' => 'app.example.com',
'is_build_time' => false,
'is_buildtime' => false,
'is_preview' => false,
]);
EnvironmentVariable::create([
'application_id' => $application->id,
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'SERVICE_URL_APP',
'value' => 'http://app.example.com',
'is_build_time' => false,
'is_buildtime' => false,
'is_preview' => false,
]);
EnvironmentVariable::create([
'application_id' => $application->id,
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'REGULAR_VAR',
'value' => 'should_remain',
'is_build_time' => false,
'is_buildtime' => false,
'is_preview' => false,
]);
@@ -117,6 +120,87 @@ describe('Application Model Buildpack Cleanup', function () {
expect($application->environment_variables()->where('key', 'REGULAR_VAR')->count())->toBe(1);
});
test('model clears dockerfile fields when build_pack changes from dockerfile to railpack', function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$environment = Environment::factory()->create(['project_id' => $project->id]);
$application = Application::factory()->create([
'environment_id' => $environment->id,
'build_pack' => 'dockerfile',
'dockerfile' => 'FROM node:18',
'dockerfile_location' => '/Dockerfile',
'dockerfile_target_build' => 'production',
'custom_healthcheck_found' => true,
]);
$application->build_pack = 'railpack';
$application->save();
$application->refresh();
expect($application->build_pack)->toBe('railpack');
expect($application->dockerfile)->toBeNull();
expect($application->dockerfile_location)->toBeNull();
expect($application->dockerfile_target_build)->toBeNull();
expect($application->custom_healthcheck_found)->toBeFalse();
});
test('model clears dockercompose fields when build_pack changes from dockercompose to railpack', function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$environment = Environment::factory()->create(['project_id' => $project->id]);
$application = Application::factory()->create([
'environment_id' => $environment->id,
'build_pack' => 'dockercompose',
'docker_compose_domains' => '{"app": "example.com"}',
'docker_compose_raw' => 'version: "3.8"\nservices:\n app:\n image: nginx',
]);
// Add environment variables that should be deleted
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'SERVICE_FQDN_APP',
'value' => 'app.example.com',
'is_buildtime' => false,
'is_preview' => false,
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'SERVICE_URL_APP',
'value' => 'http://app.example.com',
'is_buildtime' => false,
'is_preview' => false,
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'REGULAR_VAR',
'value' => 'should_remain',
'is_buildtime' => false,
'is_preview' => false,
]);
$application->build_pack = 'railpack';
$application->save();
$application->refresh();
expect($application->build_pack)->toBe('railpack');
expect($application->docker_compose_domains)->toBeNull();
expect($application->docker_compose_raw)->toBeNull();
// Verify SERVICE_FQDN_* and SERVICE_URL_* were deleted
expect($application->environment_variables()->where('key', 'SERVICE_FQDN_APP')->count())->toBe(0);
expect($application->environment_variables()->where('key', 'SERVICE_URL_APP')->count())->toBe(0);
// Verify regular variables remain
expect($application->environment_variables()->where('key', 'REGULAR_VAR')->count())->toBe(1);
});
test('model does not clear dockerfile fields when switching to dockerfile', function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
@@ -111,6 +111,29 @@ describe('Buildpack Switching Cleanup', function () {
expect($application->dockerfile)->toBeNull();
});
test('clears dockerfile fields when switching from dockerfile to railpack', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'dockerfile',
'dockerfile' => 'FROM node:18',
'dockerfile_location' => '/Dockerfile',
'dockerfile_target_build' => 'production',
'custom_healthcheck_found' => true,
]);
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->set('buildPack', 'railpack')
->call('updatedBuildPack');
$application->refresh();
expect($application->build_pack)->toBe('railpack');
expect($application->dockerfile)->toBeNull();
expect($application->dockerfile_location)->toBeNull();
expect($application->dockerfile_target_build)->toBeNull();
expect($application->custom_healthcheck_found)->toBeFalse();
});
test('clears dockerfile fields when switching from dockerfile to dockercompose', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
@@ -0,0 +1,388 @@
<?php
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\ApplicationPreview;
use App\Models\Environment;
use App\Models\EnvironmentVariable;
use App\Models\Project;
use App\Models\Server;
use App\Models\Team;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Collection;
uses(RefreshDatabase::class);
class TestableControlVarFilteringDeploymentJob extends ApplicationDeploymentJob
{
public array $recordedCommands = [];
public ?string $writtenDockerfile = null;
public function __construct() {}
public function execute_remote_command(...$commands)
{
$this->recordedCommands[] = $commands;
foreach ($commands as $command) {
$commandString = is_array($command) ? ($command['command'] ?? $command[0] ?? null) : $command;
if (! is_string($commandString)) {
continue;
}
if (preg_match('/echo .*?([A-Za-z0-9+\\/=]{16,}).*?\\| base64 -d \\| tee \\/artifacts\\/test-app\\/Dockerfile > \\/dev\\/null/', $commandString, $matches) === 1) {
$this->writtenDockerfile = base64_decode($matches[1]) ?: null;
}
}
}
}
function makeDeploymentControlVarFixture(array $applicationAttributes = []): array
{
$team = Team::create([
'name' => 'Control Var Team',
'description' => 'Team for deployment control var tests.',
'personal_team' => false,
'show_boarding' => false,
]);
$project = Project::create([
'name' => 'Control Var Project',
'team_id' => $team->id,
]);
$environment = Environment::where('project_id', $project->id)->firstOrFail();
$server = Server::factory()->create([
'team_id' => $team->id,
]);
$application = Application::factory()->create([
'environment_id' => $environment->id,
'build_pack' => 'dockerfile',
...$applicationAttributes,
]);
$application->settings()->update([
'inject_build_args_to_dockerfile' => true,
'include_source_commit_in_build' => false,
'is_env_sorting_enabled' => false,
]);
return [$application->fresh(), $server];
}
function createApplicationEnvironmentVariable(Application $application, array $attributes): EnvironmentVariable
{
return EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'is_preview' => false,
'is_runtime' => true,
'is_buildtime' => true,
'is_multiline' => false,
'is_literal' => false,
...$attributes,
]);
}
function makeControlVarFilteringJob(Application $application, Server $server, array $overrides = []): array
{
$job = new TestableControlVarFilteringDeploymentJob;
$reflection = new ReflectionClass(ApplicationDeploymentJob::class);
$queue = Mockery::mock(ApplicationDeploymentQueue::class);
$queue->shouldReceive('addLogEntry')->andReturnNull();
$properties = [
'application' => $application->fresh(),
'application_deployment_queue' => $queue,
'build_pack' => $application->build_pack,
'mainServer' => $server,
'pull_request_id' => 0,
'commit' => 'HEAD',
'workdir' => '/artifacts/test-app',
'deployment_uuid' => 'deployment-uuid',
'dockerfile_location' => '/Dockerfile',
'container_name' => 'control-var-app',
'coolify_variables' => null,
'dockerSecretsSupported' => false,
];
$mergedProperties = array_merge($properties, $overrides);
$mergedProperties['saved_outputs'] = new Collection($overrides['saved_outputs'] ?? []);
if (($mergedProperties['pull_request_id'] ?? 0) !== 0 && ! array_key_exists('preview', $mergedProperties)) {
$mergedProperties['preview'] = ApplicationPreview::create([
'application_id' => $application->id,
'pull_request_id' => $mergedProperties['pull_request_id'],
'pull_request_html_url' => 'https://example.com/pr/'.$mergedProperties['pull_request_id'],
'fqdn' => 'https://preview.example.com',
]);
}
foreach ($mergedProperties as $property => $value) {
$reflectionProperty = $reflection->getProperty($property);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($job, $value);
}
return [$job, $reflection];
}
function invokeDeploymentJobMethod(object $job, ReflectionClass $reflection, string $method): mixed
{
$reflectionMethod = $reflection->getMethod($method);
$reflectionMethod->setAccessible(true);
return $reflectionMethod->invoke($job);
}
function readDeploymentJobProperty(object $job, ReflectionClass $reflection, string $property): mixed
{
$reflectionProperty = $reflection->getProperty($property);
$reflectionProperty->setAccessible(true);
return $reflectionProperty->getValue($job);
}
it('filters buildpack control vars from generic build args', function () {
[$application, $server] = makeDeploymentControlVarFixture();
createApplicationEnvironmentVariable($application, [
'key' => 'APP_ENV',
'value' => 'production',
]);
createApplicationEnvironmentVariable($application, [
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '22',
]);
createApplicationEnvironmentVariable($application, [
'key' => 'RAILPACK_NODE_VERSION',
'value' => '20',
]);
[$job, $reflection] = makeControlVarFilteringJob($application, $server);
invokeDeploymentJobMethod($job, $reflection, 'generate_env_variables');
/** @var Collection $envArgs */
$envArgs = readDeploymentJobProperty($job, $reflection, 'env_args');
expect($envArgs->get('APP_ENV'))->toBe('production');
expect($envArgs->has('NIXPACKS_NODE_VERSION'))->toBeFalse();
expect($envArgs->has('RAILPACK_NODE_VERSION'))->toBeFalse();
});
it('filters buildpack control vars from preview build-time env files', function () {
[$application, $server] = makeDeploymentControlVarFixture();
createApplicationEnvironmentVariable($application, [
'key' => 'APP_ENV',
'value' => 'production',
'is_preview' => true,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '22',
'is_preview' => true,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'RAILPACK_NODE_VERSION',
'value' => '20',
'is_preview' => true,
]);
[$job, $reflection] = makeControlVarFilteringJob($application, $server, [
'pull_request_id' => 42,
]);
/** @var Collection $buildtimeEnvs */
$buildtimeEnvs = invokeDeploymentJobMethod($job, $reflection, 'generate_buildtime_environment_variables');
expect($buildtimeEnvs->contains(fn (string $env) => str($env)->startsWith('APP_ENV=')))->toBeTrue();
expect($buildtimeEnvs->contains(fn (string $env) => str($env)->startsWith('NIXPACKS_NODE_VERSION=')))->toBeFalse();
expect($buildtimeEnvs->contains(fn (string $env) => str($env)->startsWith('RAILPACK_NODE_VERSION=')))->toBeFalse();
});
it('filters buildpack control vars from preview runtime env fallback', function () {
[$application, $server] = makeDeploymentControlVarFixture();
createApplicationEnvironmentVariable($application, [
'key' => 'APP_NAME',
'value' => 'coolify',
'is_runtime' => true,
'is_buildtime' => false,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '22',
'is_runtime' => true,
'is_buildtime' => false,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'RAILPACK_NODE_VERSION',
'value' => '20',
'is_runtime' => true,
'is_buildtime' => false,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'PREVIEW_FLAG',
'value' => 'enabled',
'is_preview' => true,
'is_runtime' => true,
'is_buildtime' => false,
]);
$application->environment_variables_preview()
->whereIn('key', ['APP_NAME', 'NIXPACKS_NODE_VERSION', 'RAILPACK_NODE_VERSION'])
->delete();
[$job, $reflection] = makeControlVarFilteringJob($application, $server, [
'pull_request_id' => 99,
]);
/** @var Collection $runtimeEnvs */
$runtimeEnvs = invokeDeploymentJobMethod($job, $reflection, 'generate_runtime_environment_variables');
expect($runtimeEnvs->contains(fn (string $env) => str($env)->startsWith('APP_NAME=')))->toBeTrue();
expect($runtimeEnvs->contains(fn (string $env) => str($env)->startsWith('PREVIEW_FLAG=')))->toBeTrue();
expect($runtimeEnvs->contains(fn (string $env) => str($env)->startsWith('NIXPACKS_NODE_VERSION=')))->toBeFalse();
expect($runtimeEnvs->contains(fn (string $env) => str($env)->startsWith('RAILPACK_NODE_VERSION=')))->toBeFalse();
});
it('filters buildpack control vars from dockerfile arg injection', function () {
[$application, $server] = makeDeploymentControlVarFixture();
createApplicationEnvironmentVariable($application, [
'key' => 'APP_ENV',
'value' => 'production',
'is_runtime' => false,
'is_buildtime' => true,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '22',
'is_runtime' => false,
'is_buildtime' => true,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'RAILPACK_NODE_VERSION',
'value' => '20',
'is_runtime' => false,
'is_buildtime' => true,
]);
[$job, $reflection] = makeControlVarFilteringJob($application, $server, [
'saved_outputs' => [
'dockerfile' => "FROM php:8.4-cli\nRUN php -v",
],
]);
invokeDeploymentJobMethod($job, $reflection, 'add_build_env_variables_to_dockerfile');
expect($job->writtenDockerfile)->toContain('ARG APP_ENV=production');
expect($job->writtenDockerfile)->not->toContain('ARG NIXPACKS_NODE_VERSION=');
expect($job->writtenDockerfile)->not->toContain('ARG RAILPACK_NODE_VERSION=');
});
it('builds railpack variables from generic buildtime vars railpack vars and coolify vars only', function () {
[$application, $server] = makeDeploymentControlVarFixture([
'build_pack' => 'railpack',
'fqdn' => 'https://railpack.example.com',
'install_command' => 'pnpm install --frozen-lockfile',
]);
createApplicationEnvironmentVariable($application, [
'key' => 'APP_ENV',
'value' => 'production',
'is_runtime' => false,
'is_buildtime' => true,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'RUNTIME_ONLY',
'value' => 'runtime',
'is_runtime' => true,
'is_buildtime' => false,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '22',
'is_runtime' => false,
'is_buildtime' => true,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'RAILPACK_NODE_VERSION',
'value' => '20',
'is_runtime' => false,
'is_buildtime' => true,
]);
[$job, $reflection] = makeControlVarFilteringJob($application->fresh(), $server, [
'build_pack' => 'railpack',
'branch' => 'main',
]);
/** @var Collection $variables */
$variables = invokeDeploymentJobMethod($job, $reflection, 'railpack_build_variables');
expect($variables->get('APP_ENV'))->toBe('production');
expect($variables->get('RAILPACK_NODE_VERSION'))->toBe('20');
expect($variables->get('RAILPACK_INSTALL_CMD'))->toBe('pnpm install --frozen-lockfile');
expect($variables->get('RAILPACK_DEPLOY_APT_PACKAGES'))->toBe('curl wget');
expect($variables->get('COOLIFY_RESOURCE_UUID'))->toBe($application->uuid);
expect($variables->has('NIXPACKS_NODE_VERSION'))->toBeFalse();
expect($variables->has('RUNTIME_ONLY'))->toBeFalse();
});
it('builds preview railpack variables without leaking stale nixpacks vars', function () {
[$application, $server] = makeDeploymentControlVarFixture([
'build_pack' => 'railpack',
'fqdn' => 'https://railpack.example.com',
]);
createApplicationEnvironmentVariable($application, [
'key' => 'PREVIEW_BUILD_FLAG',
'value' => 'enabled',
'is_preview' => true,
'is_runtime' => false,
'is_buildtime' => true,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'PREVIEW_RUNTIME_ONLY',
'value' => 'runtime',
'is_preview' => true,
'is_runtime' => true,
'is_buildtime' => false,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '22',
'is_preview' => true,
'is_runtime' => false,
'is_buildtime' => true,
]);
createApplicationEnvironmentVariable($application, [
'key' => 'RAILPACK_NODE_VERSION',
'value' => '20',
'is_preview' => true,
'is_runtime' => false,
'is_buildtime' => true,
]);
[$job, $reflection] = makeControlVarFilteringJob($application->fresh(), $server, [
'build_pack' => 'railpack',
'branch' => 'feature/railpack',
'pull_request_id' => 123,
]);
/** @var Collection $variables */
$variables = invokeDeploymentJobMethod($job, $reflection, 'railpack_build_variables');
expect($variables->get('PREVIEW_BUILD_FLAG'))->toBe('enabled');
expect($variables->get('RAILPACK_NODE_VERSION'))->toBe('20');
expect($variables->get('RAILPACK_DEPLOY_APT_PACKAGES'))->toBe('curl wget');
expect($variables->get('COOLIFY_RESOURCE_UUID'))->toBe($application->uuid);
expect($variables->has('NIXPACKS_NODE_VERSION'))->toBeFalse();
expect($variables->has('PREVIEW_RUNTIME_ONLY'))->toBeFalse();
});
@@ -0,0 +1,86 @@
<?php
use App\Livewire\Project\Application\General;
use App\Models\Application;
use App\Models\Environment;
use App\Models\InstanceSettings;
use App\Models\PrivateKey;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
$this->actingAs($this->user);
session(['currentTeam' => $this->team]);
InstanceSettings::unguarded(function () {
InstanceSettings::updateOrCreate(['id' => 0], []);
});
$this->project = Project::factory()->create(['team_id' => $this->team->id]);
$this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
$this->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' => $this->team->id,
]);
$this->server = Server::factory()->create([
'team_id' => $this->team->id,
'private_key_id' => $this->privateKey->id,
]);
$this->destination = StandaloneDocker::where('server_id', $this->server->id)->first()
?? StandaloneDocker::factory()->create(['server_id' => $this->server->id, 'network' => 'coolify-test']);
});
test('existing application buildpack selector lists nixpacks before railpack', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'destination_id' => $this->destination->id,
'destination_type' => StandaloneDocker::class,
'build_pack' => 'nixpacks',
'static_image' => 'nginx:alpine',
'base_directory' => '/',
'is_http_basic_auth_enabled' => false,
'redirect' => 'no',
]);
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->assertSeeInOrder([
'<option value="nixpacks">Nixpacks</option>',
'<option value="railpack">Railpack (Beta)</option>',
], false);
});
test('existing application shows railpack beta badge in build helper copy', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'destination_id' => $this->destination->id,
'destination_type' => StandaloneDocker::class,
'build_pack' => 'railpack',
'static_image' => 'nginx:alpine',
'base_directory' => '/',
'is_http_basic_auth_enabled' => false,
'redirect' => 'no',
]);
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->assertSee('Railpack')
->assertSee('Beta');
});
+150
View File
@@ -0,0 +1,150 @@
<?php
use App\Models\Application;
use App\Models\Environment;
use App\Models\EnvironmentVariable;
use App\Models\Project;
use App\Models\Team;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
describe('Application Railpack Support', function () {
beforeEach(function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$this->environment = Environment::factory()->create(['project_id' => $project->id]);
});
test('could_set_build_commands returns true for railpack', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'railpack',
]);
expect($application->could_set_build_commands())->toBeTrue();
});
test('could_set_build_commands returns true for nixpacks', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'nixpacks',
]);
expect($application->could_set_build_commands())->toBeTrue();
});
test('could_set_build_commands returns false for dockerfile', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'dockerfile',
]);
expect($application->could_set_build_commands())->toBeFalse();
});
test('railpack_environment_variables returns only RAILPACK_ prefixed vars', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'railpack',
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'RAILPACK_NODE_VERSION',
'value' => '20',
'is_buildtime' => true,
'is_preview' => false,
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'REGULAR_VAR',
'value' => 'value',
'is_buildtime' => false,
'is_preview' => false,
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '18',
'is_buildtime' => true,
'is_preview' => false,
]);
$railpackVars = $application->railpack_environment_variables;
expect($railpackVars)->toHaveCount(1);
expect($railpackVars->first()->key)->toBe('RAILPACK_NODE_VERSION');
});
test('runtime_environment_variables excludes RAILPACK_ and NIXPACKS_ prefixed vars', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'railpack',
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'RAILPACK_NODE_VERSION',
'value' => '20',
'is_buildtime' => true,
'is_preview' => false,
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'NIXPACKS_NODE_VERSION',
'value' => '18',
'is_buildtime' => true,
'is_preview' => false,
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'APP_ENV',
'value' => 'production',
'is_buildtime' => false,
'is_preview' => false,
]);
$runtimeVars = $application->runtime_environment_variables;
expect($runtimeVars)->toHaveCount(1);
expect($runtimeVars->first()->key)->toBe('APP_ENV');
});
test('railpack_environment_variables_preview returns only RAILPACK_ prefixed preview vars', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'railpack',
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'RAILPACK_BUILD_CMD',
'value' => 'npm run build',
'is_buildtime' => true,
'is_preview' => true,
]);
EnvironmentVariable::create([
'resourceable_type' => Application::class,
'resourceable_id' => $application->id,
'key' => 'REGULAR_VAR',
'value' => 'value',
'is_buildtime' => false,
'is_preview' => true,
]);
$previewVars = $application->railpack_environment_variables_preview;
expect($previewVars)->toHaveCount(1);
expect($previewVars->first()->key)->toBe('RAILPACK_BUILD_CMD');
});
});
+51
View File
@@ -0,0 +1,51 @@
<?php
use App\Models\Application;
use Database\Seeders\ApplicationSeeder;
use Database\Seeders\GithubAppSeeder;
use Database\Seeders\PrivateKeySeeder;
use Database\Seeders\ProjectSeeder;
use Database\Seeders\ServerSeeder;
use Database\Seeders\StandaloneDockerSeeder;
use Database\Seeders\TeamSeeder;
use Database\Seeders\UserSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('seeds a railpack nodejs fastify example alongside the existing nixpacks example', function () {
$this->seed([
UserSeeder::class,
TeamSeeder::class,
PrivateKeySeeder::class,
ServerSeeder::class,
ProjectSeeder::class,
StandaloneDockerSeeder::class,
GithubAppSeeder::class,
ApplicationSeeder::class,
]);
$nixpacksExample = Application::where('uuid', 'nodejs')->first();
$railpackExample = Application::where('uuid', 'railpack-nodejs')->first();
expect($nixpacksExample)
->not->toBeNull()
->and($nixpacksExample->name)->toBe('NodeJS Fastify Example')
->and($nixpacksExample->build_pack)->toBe('nixpacks')
->and($nixpacksExample->base_directory)->toBe('/nodejs')
->and($nixpacksExample->ports_exposes)->toBe('3000');
expect($railpackExample)
->not->toBeNull()
->and($railpackExample->name)->toBe('Railpack NodeJS Fastify Example')
->and($railpackExample->fqdn)->toBe('http://railpack-nodejs.127.0.0.1.sslip.io')
->and($railpackExample->repository_project_id)->toBe(603035348)
->and($railpackExample->git_repository)->toBe('coollabsio/coolify-examples')
->and($railpackExample->git_branch)->toBe('v4.x')
->and($railpackExample->base_directory)->toBe('/nodejs')
->and($railpackExample->build_pack)->toBe('railpack')
->and($railpackExample->ports_exposes)->toBe('3000')
->and($railpackExample->environment_id)->toBe(1)
->and($railpackExample->destination_id)->toBe(0)
->and($railpackExample->source_id)->toBe(1);
});
@@ -1,15 +1,19 @@
<?php
use App\Enums\ApplicationDeploymentStatus;
use App\Livewire\Boarding\Index as BoardingIndex;
use App\Livewire\GlobalSearch;
use App\Livewire\Project\CloneMe;
use App\Livewire\Project\DeleteProject;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\Team;
use App\Models\User;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
@@ -39,7 +43,7 @@ beforeEach(function () {
session(['currentTeam' => $this->teamA]);
});
describe('Boarding Server IDOR (GHSA-qfcc-2fm3-9q42)', function () {
describe('Boarding Server IDOR', function () {
test('boarding mount cannot load server from another team via selectedExistingServer', function () {
$component = Livewire::test(BoardingIndex::class, [
'selectedServerType' => 'remote',
@@ -62,7 +66,7 @@ describe('Boarding Server IDOR (GHSA-qfcc-2fm3-9q42)', function () {
});
});
describe('Boarding Project IDOR (GHSA-qfcc-2fm3-9q42)', function () {
describe('Boarding Project IDOR', function () {
test('boarding mount cannot load project from another team via selectedProject', function () {
$component = Livewire::test(BoardingIndex::class, [
'selectedProject' => $this->projectB->id,
@@ -91,7 +95,7 @@ describe('Boarding Project IDOR (GHSA-qfcc-2fm3-9q42)', function () {
});
});
describe('GlobalSearch Server IDOR (GHSA-qfcc-2fm3-9q42)', function () {
describe('GlobalSearch Server IDOR', function () {
test('loadDestinations cannot access server from another team', function () {
$component = Livewire::test(GlobalSearch::class)
->set('selectedServerId', $this->serverB->id)
@@ -102,7 +106,7 @@ describe('GlobalSearch Server IDOR (GHSA-qfcc-2fm3-9q42)', function () {
});
});
describe('GlobalSearch Project IDOR (GHSA-qfcc-2fm3-9q42)', function () {
describe('GlobalSearch Project IDOR', function () {
test('loadEnvironments cannot access project from another team', function () {
$component = Livewire::test(GlobalSearch::class)
->set('selectedProjectUuid', $this->projectB->uuid)
@@ -113,11 +117,11 @@ describe('GlobalSearch Project IDOR (GHSA-qfcc-2fm3-9q42)', function () {
});
});
describe('DeleteProject IDOR (GHSA-qfcc-2fm3-9q42)', function () {
describe('DeleteProject IDOR', function () {
test('cannot mount DeleteProject with project from another team', function () {
// Should throw ModelNotFoundException (404) because team-scoped query won't find it
Livewire::test(DeleteProject::class, ['project_id' => $this->projectB->id]);
})->throws(\Illuminate\Database\Eloquent\ModelNotFoundException::class);
})->throws(ModelNotFoundException::class);
test('can mount DeleteProject with own team project', function () {
$component = Livewire::test(DeleteProject::class, ['project_id' => $this->projectA->id]);
@@ -126,14 +130,14 @@ describe('DeleteProject IDOR (GHSA-qfcc-2fm3-9q42)', function () {
});
});
describe('CloneMe Project IDOR (GHSA-qfcc-2fm3-9q42)', function () {
describe('CloneMe Project IDOR', function () {
test('cannot mount CloneMe with project UUID from another team', function () {
// Should throw ModelNotFoundException because team-scoped query won't find it
Livewire::test(CloneMe::class, [
'project_uuid' => $this->projectB->uuid,
'environment_uuid' => $this->environmentB->uuid,
]);
})->throws(\Illuminate\Database\Eloquent\ModelNotFoundException::class);
})->throws(ModelNotFoundException::class);
test('can mount CloneMe with own team project UUID', function () {
$component = Livewire::test(CloneMe::class, [
@@ -145,21 +149,21 @@ describe('CloneMe Project IDOR (GHSA-qfcc-2fm3-9q42)', function () {
});
});
describe('DeployController API Server IDOR (GHSA-qfcc-2fm3-9q42)', function () {
describe('DeployController API Server IDOR', function () {
test('deploy cancel API cannot access build server from another team', function () {
// Create a deployment queue entry that references Team B's server as build_server
$application = \App\Models\Application::factory()->create([
$application = Application::factory()->create([
'environment_id' => $this->environmentA->id,
'destination_id' => StandaloneDocker::factory()->create(['server_id' => $this->serverA->id])->id,
'destination_type' => StandaloneDocker::class,
]);
$deployment = \App\Models\ApplicationDeploymentQueue::create([
$deployment = ApplicationDeploymentQueue::create([
'application_id' => $application->id,
'deployment_uuid' => 'test-deploy-'.fake()->uuid(),
'server_id' => $this->serverA->id,
'build_server_id' => $this->serverB->id, // Cross-team build server
'status' => \App\Enums\ApplicationDeploymentStatus::IN_PROGRESS->value,
'status' => ApplicationDeploymentStatus::IN_PROGRESS->value,
]);
$token = $this->userA->createToken('test-token', ['*']);
@@ -176,7 +180,7 @@ describe('DeployController API Server IDOR (GHSA-qfcc-2fm3-9q42)', function () {
// Verify the deployment was cancelled
$deployment->refresh();
expect($deployment->status)->toBe(
\App\Enums\ApplicationDeploymentStatus::CANCELLED_BY_USER->value
ApplicationDeploymentStatus::CANCELLED_BY_USER->value
);
});
});
@@ -0,0 +1,62 @@
<?php
use App\Http\Controllers\UploadController;
function invokeHasAllowedExtension(string $name): bool
{
$method = new ReflectionMethod(UploadController::class, 'hasAllowedExtension');
$method->setAccessible(true);
return $method->invoke(null, $name);
}
test('hasAllowedExtension accepts supported extensions', function (string $name) {
expect(invokeHasAllowedExtension($name))->toBeTrue();
})->with([
'plain sql' => ['backup.sql'],
'uppercase sql' => ['BACKUP.SQL'],
'compound sql.gz' => ['backup.sql.gz'],
'compound tar.gz' => ['backup.tar.gz'],
'tgz' => ['archive.tgz'],
'zip' => ['dump.zip'],
'tar' => ['dump.tar'],
'gz' => ['data.gz'],
'dump' => ['data.dump'],
'bak' => ['data.bak'],
'bson' => ['data.bson'],
'bson.gz' => ['data.bson.gz'],
'archive' => ['data.archive'],
'archive.gz' => ['data.archive.gz'],
'bz2' => ['data.bz2'],
'xz' => ['data.xz'],
]);
test('hasAllowedExtension rejects unsupported or empty stems', function (string $name) {
expect(invokeHasAllowedExtension($name))->toBeFalse();
})->with([
'php' => ['shell.php'],
'phtml' => ['shell.phtml'],
'sh' => ['run.sh'],
'exe' => ['malware.exe'],
'elf binary no ext' => ['payload'],
'html' => ['index.html'],
'bare compound without stem' => ['.sql.gz'],
'bare extension' => ['.sql'],
'empty string' => [''],
'misleading double ext' => ['shell.php.sql-evil'],
]);
test('MAX_BYTES constant is 10 GiB', function () {
$constant = (new ReflectionClass(UploadController::class))->getConstant('MAX_BYTES');
expect($constant)->toBe(10 * 1024 * 1024 * 1024);
});
test('ALLOWED_EXTENSIONS does not include executable formats', function () {
$constant = (new ReflectionClass(UploadController::class))->getConstant('ALLOWED_EXTENSIONS');
expect($constant)->toBeArray();
$forbidden = ['php', 'phtml', 'php5', 'sh', 'bash', 'exe', 'js', 'html', 'htm', 'pl', 'py'];
foreach ($forbidden as $bad) {
expect($constant)->not->toContain($bad);
}
});
@@ -0,0 +1,18 @@
<?php
it('positions the deployments indicator from the sidebar collapsed state', function () {
$indicatorView = file_get_contents(resource_path('views/livewire/deployments-indicator.blade.php'));
$layoutView = file_get_contents(resource_path('views/layouts/app.blade.php'));
expect($indicatorView)
->toContain('transition-[left] duration-200')
->toContain(":class=\"collapsed ? 'lg:left-16' : 'lg:left-56'\"")
->not->toContain('fixed bottom-0 z-60 mb-4 left-0 lg:left-56 ml-4');
expect($layoutView)
->toContain('<div x-data="{')
->toContain('<livewire:deployments-indicator />');
expect(strpos($layoutView, '<div x-data="{'))
->toBeLessThan(strpos($layoutView, '<livewire:deployments-indicator />'));
});
@@ -0,0 +1,22 @@
<?php
use App\Http\Controllers\Api\ServicesController;
use Illuminate\Support\Facades\Route;
test('deprecated docker compose application endpoint is not registered', function () {
$routes = collect(Route::getRoutes()->getRoutes())
->filter(fn ($route) => in_array('POST', $route->methods(), true))
->filter(fn ($route) => $route->uri() === 'api/v1/applications/dockercompose');
expect($routes)->toBeEmpty();
$this->postJson('/api/v1/applications/dockercompose')->assertNotFound();
});
test('custom docker compose services endpoint remains registered', function () {
$route = collect(Route::getRoutes()->getRoutes())
->first(fn ($route) => in_array('POST', $route->methods(), true) && $route->uri() === 'api/v1/services');
expect($route)->not->toBeNull()
->and($route->getActionName())->toBe(ServicesController::class.'@create_service');
});
@@ -0,0 +1,90 @@
<?php
use App\Livewire\Settings\Index;
use App\Models\InstanceSettings;
use App\Models\Server;
use App\Models\Team;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Once;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
Model::unguarded(function () {
$this->rootTeam = Team::find(0) ?? Team::create(['id' => 0, 'name' => 'Root Team', 'personal_team' => false]);
if (! Server::find(0)) {
Server::factory()->create(['id' => 0, 'team_id' => $this->rootTeam->id]);
}
if (! InstanceSettings::find(0)) {
InstanceSettings::create(['id' => 0]);
}
});
Once::flush();
$this->user = User::factory()->create();
$this->rootTeam->members()->attach($this->user->id, ['role' => 'admin']);
$this->actingAs($this->user);
session(['currentTeam' => ['id' => $this->rootTeam->id]]);
});
test('dev_helper_version rejects values outside Docker tag grammar on save', function () {
$invalid = [
'latest with spaces',
'a$b',
'a`b',
'a|b',
'a;b',
'a&b',
'a>b',
'a<b',
"a\nb",
'.bad',
'-rm',
];
foreach ($invalid as $payload) {
Livewire::test(Index::class)
->set('dev_helper_version', $payload)
->call('instantSave')
->assertHasErrors(['dev_helper_version']);
}
expect(InstanceSettings::find(0)->dev_helper_version)->toBeNull();
});
test('dev_helper_version accepts valid docker tag formats', function () {
$valid = ['1.0.12', 'latest', 'dev', 'dev-branch_2', 'v1.2.3-rc1', '1_0_0'];
foreach ($valid as $tag) {
Livewire::test(Index::class)
->set('dev_helper_version', $tag)
->call('instantSave')
->assertHasNoErrors(['dev_helper_version']);
expect(InstanceSettings::find(0)->fresh()->dev_helper_version)->toBe($tag);
}
});
test('buildHelperImage refuses when non-dev environment', function () {
config(['app.env' => 'production']);
Livewire::test(Index::class)
->set('dev_helper_version', 'latest')
->call('buildHelperImage')
->assertDispatched('error');
});
test('buildHelperImage refuses previously stored invalid version', function () {
config(['app.env' => 'local']);
$settings = InstanceSettings::find(0);
$settings->forceFill(['dev_helper_version' => 'bad value'])->saveQuietly();
Livewire::test(Index::class)
->call('buildHelperImage')
->assertDispatched('error');
});
@@ -0,0 +1,141 @@
<?php
use App\Models\Application;
use App\Models\GithubApp;
use App\Models\PrivateKey;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\Team;
use Database\Seeders\DevelopmentRailpackExamplesSeeder;
use Database\Seeders\GithubAppSeeder;
use Database\Seeders\PrivateKeySeeder;
use Database\Seeders\ProjectSeeder;
use Database\Seeders\ServerSeeder;
use Database\Seeders\StandaloneDockerSeeder;
use Database\Seeders\TeamSeeder;
use Database\Seeders\UserSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
function seedRailpackExamplePrerequisites(): void
{
test()->seed([
UserSeeder::class,
TeamSeeder::class,
PrivateKeySeeder::class,
ServerSeeder::class,
ProjectSeeder::class,
StandaloneDockerSeeder::class,
GithubAppSeeder::class,
]);
}
it('can seed the railpack examples directly on a clean development database', function () {
config()->set('app.env', 'local');
$this->seed(DevelopmentRailpackExamplesSeeder::class);
expect(Team::query()->find(0))->not->toBeNull();
expect(PrivateKey::query()->find(1))->not->toBeNull();
expect(Server::query()->find(0))->not->toBeNull();
expect(StandaloneDocker::query()->find(0))->not->toBeNull();
expect(GithubApp::query()->find(0))->not->toBeNull();
expect(Project::query()->where('uuid', DevelopmentRailpackExamplesSeeder::PROJECT_UUID)->exists())->toBeTrue();
expect(Application::query()->count())->toBe(count(DevelopmentRailpackExamplesSeeder::examples()));
});
it('seeds the railpack examples in development mode', function () {
config()->set('app.env', 'local');
seedRailpackExamplePrerequisites();
$this->seed(DevelopmentRailpackExamplesSeeder::class);
$project = Project::query()
->where('uuid', DevelopmentRailpackExamplesSeeder::PROJECT_UUID)
->first();
expect($project)
->not->toBeNull()
->and($project->name)->toBe('Railpack Examples')
->and($project->environments)->toHaveCount(1)
->and($project->environments->first()->uuid)->toBe(DevelopmentRailpackExamplesSeeder::ENVIRONMENT_UUID);
$applications = $project->applications()->with('settings')->orderBy('uuid')->get();
expect($applications)->toHaveCount(count(DevelopmentRailpackExamplesSeeder::examples()));
expect($applications->every(fn (Application $application) => $application->build_pack === 'railpack'))->toBeTrue();
expect($applications->every(fn (Application $application) => $application->git_repository === DevelopmentRailpackExamplesSeeder::GIT_REPOSITORY))->toBeTrue();
$examples = collect(DevelopmentRailpackExamplesSeeder::examples())->keyBy('uuid');
expect($applications->every(
fn (Application $application) => $application->git_branch === ($examples->get($application->uuid)['git_branch'] ?? DevelopmentRailpackExamplesSeeder::GIT_BRANCH)
))->toBeTrue();
$nestjs = $applications->firstWhere('uuid', 'railpack-nestjs');
$angularStatic = $applications->firstWhere('uuid', 'railpack-angular-static');
$eleventyStatic = $applications->firstWhere('uuid', 'railpack-eleventy-static');
$pythonFlask = $applications->firstWhere('uuid', 'railpack-python-flask');
$goGin = $applications->firstWhere('uuid', 'railpack-go-gin');
$rust = $applications->firstWhere('uuid', 'railpack-rust');
expect($nestjs)
->not->toBeNull()
->and($nestjs->base_directory)->toBe('/node/nestjs')
->and($nestjs->ports_exposes)->toBe('3000')
->and($nestjs->build_command)->toBe('npm run build')
->and($nestjs->start_command)->toBe('npm run start:prod')
->and($nestjs->settings->is_static)->toBeFalse();
expect($angularStatic)
->not->toBeNull()
->and($angularStatic->publish_directory)->toBe('/dist/static/browser')
->and($angularStatic->ports_exposes)->toBe('80')
->and($angularStatic->settings->is_static)->toBeTrue()
->and($angularStatic->settings->is_spa)->toBeTrue();
expect($eleventyStatic)
->not->toBeNull()
->and($eleventyStatic->publish_directory)->toBe('/_site')
->and($eleventyStatic->settings->is_static)->toBeTrue()
->and($eleventyStatic->settings->is_spa)->toBeFalse();
expect($pythonFlask)
->not->toBeNull()
->and($pythonFlask->ports_exposes)->toBe('5000')
->and($pythonFlask->start_command)->toBe('flask run --host=0.0.0.0 --port=5000');
expect($goGin)
->not->toBeNull()
->and($goGin->ports_exposes)->toBe('3000');
expect($rust)
->not->toBeNull()
->and($rust->ports_exposes)->toBe('8000');
});
it('skips the railpack examples outside development mode', function () {
config()->set('app.env', 'testing');
seedRailpackExamplePrerequisites();
$this->seed(DevelopmentRailpackExamplesSeeder::class);
expect(Project::query()->where('uuid', DevelopmentRailpackExamplesSeeder::PROJECT_UUID)->exists())->toBeFalse();
expect(Application::query()->where('uuid', 'railpack-nextjs-ssr')->exists())->toBeFalse();
});
it('is idempotent when run multiple times', function () {
config()->set('app.env', 'local');
seedRailpackExamplePrerequisites();
$this->seed(DevelopmentRailpackExamplesSeeder::class);
$this->seed(DevelopmentRailpackExamplesSeeder::class);
$project = Project::query()
->where('uuid', DevelopmentRailpackExamplesSeeder::PROJECT_UUID)
->first();
expect($project)->not->toBeNull();
expect($project->applications()->count())->toBe(count(DevelopmentRailpackExamplesSeeder::examples()));
});
@@ -0,0 +1,73 @@
<?php
use App\Http\Middleware\CheckForcePasswordReset;
use App\Http\Middleware\DecideWhatToDoWithUser;
use App\Models\InstanceSettings;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Once;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->withoutMiddleware([DecideWhatToDoWithUser::class, CheckForcePasswordReset::class]);
Once::flush();
if (! InstanceSettings::find(0)) {
$settings = new InstanceSettings;
$settings->id = 0;
$settings->saveQuietly();
}
});
describe('email verification hash', function () {
test('sha256 hash is accepted and marks the user verified', function () {
$user = User::factory()->create([
'email' => 'verify-me@example.com',
'email_verified_at' => null,
]);
$url = URL::temporarySignedRoute('verify.verify', now()->addHour(), [
'id' => $user->getKey(),
'hash' => hash('sha256', $user->getEmailForVerification()),
]);
$this->actingAs($user)->get($url)->assertRedirect();
$user->refresh();
expect($user->email_verified_at)->not->toBeNull();
});
test('legacy sha1 hash is rejected', function () {
$user = User::factory()->create([
'email' => 'legacy-sha1@example.com',
'email_verified_at' => null,
]);
$url = URL::temporarySignedRoute('verify.verify', now()->addHour(), [
'id' => $user->getKey(),
'hash' => sha1($user->getEmailForVerification()),
]);
$this->actingAs($user)->get($url)->assertStatus(403);
$user->refresh();
expect($user->email_verified_at)->toBeNull();
});
test('tampered signature is rejected', function () {
$user = User::factory()->create([
'email' => 'tampered@example.com',
'email_verified_at' => null,
]);
$url = URL::temporarySignedRoute('verify.verify', now()->addHour(), [
'id' => $user->getKey(),
'hash' => hash('sha256', $user->getEmailForVerification()),
]);
$tampered = $url.'x';
$this->actingAs($user)->get($tampered)->assertStatus(403);
});
});
@@ -0,0 +1,39 @@
<?php
use App\Livewire\Project\Shared\EnvironmentVariable\Add;
use Livewire\Livewire;
it('rejects environment variable keys Docker cannot represent in the add form', function () {
Livewire::test(Add::class)
->set('key', 'BAD=KEY')
->set('value', 'value')
->call('submit')
->assertHasErrors(['key' => 'regex']);
});
it('allows Docker-compatible environment variable keys in the add form', function (string $key) {
Livewire::test(Add::class)
->set('key', $key)
->set('value', 'value')
->call('submit')
->assertHasNoErrors()
->assertDispatched('saveKey', function ($event, array $data) use ($key) {
return data_get($data, 'key') === $key || data_get($data, '0.key') === $key;
});
})->with([
'starts with digit' => '1BAD',
'hyphen' => 'BAD-KEY',
'dot' => 'node.name',
'uppercase dots' => 'XPACK.SECURITY.ENABLED',
]);
it('trims surrounding whitespace in environment variable keys in the add form', function () {
Livewire::test(Add::class)
->set('key', ' node.name ')
->set('value', 'value')
->call('submit')
->assertHasNoErrors()
->assertDispatched('saveKey', function ($event, array $data) {
return data_get($data, 'key') === 'node.name' || data_get($data, '0.key') === 'node.name';
});
});
@@ -0,0 +1,60 @@
<?php
use App\Http\Middleware\CheckForcePasswordReset;
use App\Http\Middleware\DecideWhatToDoWithUser;
use App\Models\InstanceSettings;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Once;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->withoutMiddleware([DecideWhatToDoWithUser::class, CheckForcePasswordReset::class]);
Once::flush();
if (! InstanceSettings::find(0)) {
$settings = new InstanceSettings;
$settings->id = 0;
$settings->saveQuietly();
}
});
describe('invitation link login', function () {
test('does not auto-verify the email address', function () {
$team = Team::factory()->create();
$password = 'test-password-123';
$user = User::factory()->create([
'email' => 'invitee@example.com',
'password' => Hash::make($password),
'email_verified_at' => null,
]);
$user->teams()->attach($team->id, ['role' => 'member']);
$token = Crypt::encryptString("{$user->email}@@@{$password}");
$this->get(route('auth.link', ['token' => $token]));
$user->refresh();
expect($user->email_verified_at)->toBeNull();
});
test('still logs the user in', function () {
$team = Team::factory()->create();
$password = 'test-password-123';
$user = User::factory()->create([
'email' => 'invitee2@example.com',
'password' => Hash::make($password),
'email_verified_at' => null,
]);
$user->teams()->attach($team->id, ['role' => 'member']);
$token = Crypt::encryptString("{$user->email}@@@{$password}");
$this->get(route('auth.link', ['token' => $token]));
expect(auth()->id())->toBe($user->id);
});
});
@@ -0,0 +1,121 @@
<?php
use App\Livewire\Project\Application\General;
use App\Livewire\Project\New\PublicGitRepository;
use App\Models\Application;
use App\Models\Environment;
use App\Models\InstanceSettings;
use App\Models\PrivateKey;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
$this->actingAs($this->user);
session(['currentTeam' => $this->team]);
InstanceSettings::unguarded(function () {
InstanceSettings::updateOrCreate(['id' => 0], []);
});
$this->project = Project::factory()->create(['team_id' => $this->team->id]);
$this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
});
describe('PublicGitRepository port handling for railpack', function () {
test('switching to railpack resets port to 3000 when not static', function () {
Livewire::test(PublicGitRepository::class, ['type' => 'public'])
->set('build_pack', 'dockerfile')
->assertSet('port', 3000)
->set('build_pack', 'railpack')
->assertSet('port', 3000);
});
test('switching to railpack preserves port when isStatic is true', function () {
$component = Livewire::test(PublicGitRepository::class, ['type' => 'public'])
->set('isStatic', true)
->call('instantSave');
// After instantSave with isStatic=true, port becomes 80
$component->assertSet('port', 80);
// Switching from nixpacks to railpack should NOT clobber port back to 3000
$component->set('build_pack', 'railpack')
->assertSet('port', 80);
});
test('switching to static sets port to 80 and disables show_is_static', function () {
Livewire::test(PublicGitRepository::class, ['type' => 'public'])
->set('build_pack', 'static')
->assertSet('port', 80)
->assertSet('isStatic', false)
->assertSet('show_is_static', false);
});
});
describe('General view railpack helper text', function () {
beforeEach(function () {
$this->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' => $this->team->id,
]);
$this->server = Server::factory()->create([
'team_id' => $this->team->id,
'private_key_id' => $this->privateKey->id,
]);
$this->destination = StandaloneDocker::where('server_id', $this->server->id)->first()
?? StandaloneDocker::factory()->create(['server_id' => $this->server->id, 'network' => 'coolify-test']);
});
test('railpack app shows railpack.json helper text and not nixpacks.toml', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'destination_id' => $this->destination->id,
'destination_type' => StandaloneDocker::class,
'build_pack' => 'railpack',
'static_image' => 'nginx:alpine',
'base_directory' => '/',
'is_http_basic_auth_enabled' => false,
'redirect' => 'no',
]);
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->assertSee('railpack.json')
->assertDontSee('nixpacks.toml');
});
test('nixpacks app shows nixpacks.toml helper text and not railpack.json', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'destination_id' => $this->destination->id,
'destination_type' => StandaloneDocker::class,
'build_pack' => 'nixpacks',
'static_image' => 'nginx:alpine',
'base_directory' => '/',
'is_http_basic_auth_enabled' => false,
'redirect' => 'no',
]);
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->assertSee('nixpacks.toml')
->assertDontSee('railpack.json');
});
});
+194
View File
@@ -0,0 +1,194 @@
<?php
use App\Models\InstanceSettings;
use App\Models\Project;
use App\Models\Server;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Once;
uses(RefreshDatabase::class);
beforeEach(function () {
InstanceSettings::query()->where('id', 0)->delete();
InstanceSettings::query()->delete();
$settings = new InstanceSettings(['is_mcp_server_enabled' => true]);
$settings->id = 0;
$settings->save();
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
session(['currentTeam' => $this->team]);
});
function mcpPost(array $payload, ?string $token = null)
{
$headers = [
'Content-Type' => 'application/json',
'Accept' => 'application/json, text/event-stream',
];
if ($token) {
$headers['Authorization'] = 'Bearer '.$token;
}
return test()->withHeaders($headers)->postJson('/mcp', $payload);
}
function mcpListTools(string $token)
{
return mcpPost([
'jsonrpc' => '2.0',
'id' => 1,
'method' => 'tools/list',
'params' => (object) [],
], $token);
}
function mcpCallTool(string $token, string $name, array $arguments = [])
{
return mcpPost([
'jsonrpc' => '2.0',
'id' => 1,
'method' => 'tools/call',
'params' => [
'name' => $name,
'arguments' => (object) $arguments,
],
], $token);
}
function mcpToolJson($response): array
{
return json_decode($response->json('result.content.0.text'), true);
}
test('MCP endpoint returns 404 when the instance setting is disabled', function () {
InstanceSettings::query()->where('id', 0)->update(['is_mcp_server_enabled' => false]);
Once::flush();
$response = mcpPost(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/list']);
$response->assertStatus(404);
});
test('MCP endpoint rejects unauthenticated requests', function () {
$response = mcpPost(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/list']);
$response->assertStatus(401);
});
test('MCP endpoint lists tools for an authenticated token', function () {
$token = $this->user->createToken('mcp-read', ['read'])->plainTextToken;
$response = mcpListTools($token);
$response->assertOk();
$toolNames = collect($response->json('result.tools'))->pluck('name')->all();
expect($toolNames)->toContain(
'get_infrastructure_overview',
'list_servers',
'get_server',
'list_projects',
'list_applications',
'get_application',
'list_databases',
'get_database',
'list_services',
'get_service',
);
expect($toolNames)->not->toContain('get_resource_status');
});
test('list_projects returns summary + pagination scoped to the token team', function () {
$project = Project::create(['name' => 'Mine', 'team_id' => $this->team->id]);
$otherTeam = Team::factory()->create();
Project::create(['name' => 'Theirs', 'team_id' => $otherTeam->id]);
$token = $this->user->createToken('mcp-read', ['read'])->plainTextToken;
$response = mcpCallTool($token, 'list_projects');
$response->assertOk();
$body = mcpToolJson($response);
expect($body)->toHaveKey('data');
expect($body)->toHaveKey('_pagination');
expect($body['_pagination']['total'])->toBe(1);
expect($body['_pagination']['per_page'])->toBe(50);
expect($body['_pagination'])->not->toHaveKey('next');
$uuids = collect($body['data'])->pluck('uuid')->all();
$names = collect($body['data'])->pluck('name')->all();
expect($uuids)->toContain($project->uuid);
expect($names)->not->toContain('Theirs');
expect($body['data'][0])->toHaveKeys(['uuid', 'name', 'description']);
});
test('list_projects paginates with per_page cap at 100', function () {
for ($i = 0; $i < 3; $i++) {
Project::create(['name' => "P{$i}", 'team_id' => $this->team->id]);
}
$token = $this->user->createToken('mcp-read', ['read'])->plainTextToken;
$response = mcpCallTool($token, 'list_projects', ['per_page' => 2, 'page' => 1]);
$body = mcpToolJson($response);
expect($body['_pagination']['total'])->toBe(3);
expect($body['_pagination']['total_pages'])->toBe(2);
expect($body['_pagination']['next']['args'])->toMatchArray(['page' => 2, 'per_page' => 2]);
expect($body['data'])->toHaveCount(2);
// Verify max cap
$capped = mcpCallTool($token, 'list_projects', ['per_page' => 500]);
$cappedBody = mcpToolJson($capped);
expect($cappedBody['_pagination']['per_page'])->toBe(100);
});
test('get_infrastructure_overview returns counts', function () {
Project::create(['name' => 'One', 'team_id' => $this->team->id]);
Project::create(['name' => 'Two', 'team_id' => $this->team->id]);
$token = $this->user->createToken('mcp-read', ['read'])->plainTextToken;
$response = mcpCallTool($token, 'get_infrastructure_overview');
$response->assertOk();
$body = mcpToolJson($response);
expect($body)->toHaveKey('data');
expect($body['data'])->toHaveKeys(['coolify_version', 'servers', 'projects', 'counts']);
expect($body['data']['counts']['projects'])->toBe(2);
expect($body['data']['projects'])->toHaveCount(2);
expect($body['data']['projects'][0])->toHaveKey('counts');
});
test('get_server scrubs sensitive nested data and exposes connection_timeout', function () {
$server = Server::factory()->create(['team_id' => $this->team->id]);
// creating hook auto-generates a sentinel_token; bump connection_timeout
// via saveQuietly to avoid triggering restartSentinel.
$server->settings->forceFill(['connection_timeout' => 42])->saveQuietly();
$token = $this->user->createToken('mcp-read', ['read'])->plainTextToken;
$response = mcpCallTool($token, 'get_server', ['uuid' => $server->uuid]);
$response->assertOk();
$body = mcpToolJson($response);
$raw = json_encode($body);
expect($raw)->not->toContain('sentinel_token');
expect($raw)->not->toContain('"team_id"');
expect($raw)->not->toContain('"private_key_id"');
expect($body['data']['connection_timeout'])->toBe(42);
expect($body['data']['uuid'])->toBe($server->uuid);
});
test('tool calls fail when the token lacks the read ability', function () {
$token = $this->user->createToken('mcp-no-abilities', [])->plainTextToken;
$response = mcpCallTool($token, 'list_projects');
$response->assertOk();
expect($response->json('result.isError'))->toBeTrue();
expect($response->json('result.content.0.text'))->toContain('Missing required permissions');
});
+107
View File
@@ -0,0 +1,107 @@
<?php
use App\Models\InstanceSettings;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
uses(RefreshDatabase::class);
beforeEach(function () {
InstanceSettings::query()->delete();
$settings = new InstanceSettings([
'is_mcp_server_enabled' => false,
'is_api_enabled' => true,
]);
$settings->id = 0;
$settings->save();
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
session(['currentTeam' => $this->team]);
});
function makeRootMcpToken(User $user): string
{
$token = $user->createToken('mcp-root', ['root']);
DB::table('personal_access_tokens')
->where('id', $token->accessToken->id)
->update(['team_id' => '0']);
return $token->plainTextToken;
}
function makeNonRootMcpToken(User $user, Team $team, array $abilities = ['write']): string
{
$token = $user->createToken('mcp-write', $abilities);
DB::table('personal_access_tokens')
->where('id', $token->accessToken->id)
->update(['team_id' => (string) $team->id]);
return $token->plainTextToken;
}
test('POST /api/v1/mcp/enable enables MCP server with root token', function () {
$token = makeRootMcpToken($this->user);
$response = test()->withHeaders([
'Authorization' => 'Bearer '.$token,
])->postJson('/api/v1/mcp/enable');
$response->assertOk();
$response->assertJson(['message' => 'MCP server enabled.']);
expect(InstanceSettings::find(0)->is_mcp_server_enabled)->toBeTrue();
});
test('POST /api/v1/mcp/disable disables MCP server with root token', function () {
InstanceSettings::query()->where('id', 0)->update(['is_mcp_server_enabled' => true]);
$token = makeRootMcpToken($this->user);
$response = test()->withHeaders([
'Authorization' => 'Bearer '.$token,
])->postJson('/api/v1/mcp/disable');
$response->assertOk();
$response->assertJson(['message' => 'MCP server disabled.']);
expect(InstanceSettings::find(0)->is_mcp_server_enabled)->toBeFalse();
});
test('non-root token cannot enable MCP server', function () {
$token = makeNonRootMcpToken($this->user, $this->team);
$response = test()->withHeaders([
'Authorization' => 'Bearer '.$token,
])->postJson('/api/v1/mcp/enable');
$response->assertStatus(403);
expect(InstanceSettings::find(0)->is_mcp_server_enabled)->toBeFalse();
});
test('non-root token cannot disable MCP server', function () {
InstanceSettings::query()->where('id', 0)->update(['is_mcp_server_enabled' => true]);
$token = makeNonRootMcpToken($this->user, $this->team);
$response = test()->withHeaders([
'Authorization' => 'Bearer '.$token,
])->postJson('/api/v1/mcp/disable');
$response->assertStatus(403);
expect(InstanceSettings::find(0)->is_mcp_server_enabled)->toBeTrue();
});
test('unauthenticated request to /api/v1/mcp/enable returns 401', function () {
$response = test()->postJson('/api/v1/mcp/enable');
$response->assertStatus(401);
});
test('read-only token cannot toggle MCP server (lacks write ability)', function () {
$token = makeNonRootMcpToken($this->user, $this->team, ['read']);
$response = test()->withHeaders([
'Authorization' => 'Bearer '.$token,
])->postJson('/api/v1/mcp/enable');
$response->assertStatus(403);
});
@@ -0,0 +1,51 @@
<?php
use App\Livewire\Project\New\GithubPrivateRepository;
use App\Livewire\Project\New\GithubPrivateRepositoryDeployKey;
use App\Livewire\Project\New\PublicGitRepository;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
$this->actingAs($this->user);
session(['currentTeam' => $this->team]);
});
describe('new application buildpack defaults', function () {
test('github app repository flow defaults to nixpacks', function () {
Livewire::test(GithubPrivateRepository::class, ['type' => 'private-gh-app'])
->assertSet('build_pack', 'nixpacks');
});
test('deploy key repository flow defaults to nixpacks', function () {
Livewire::test(GithubPrivateRepositoryDeployKey::class, ['type' => 'private-deploy-key'])
->assertSet('build_pack', 'nixpacks');
});
test('public repository flow defaults to nixpacks and lists railpack second', function () {
Livewire::test(PublicGitRepository::class, ['type' => 'public'])
->assertSet('build_pack', 'nixpacks');
});
test('public repository flow keeps railpack available after branch lookup', function () {
Livewire::test(PublicGitRepository::class, ['type' => 'public'])
->set('branchFound', true)
->assertSeeInOrder(['Nixpacks', 'Railpack (Beta)'])
->assertSee('Beta');
});
test('deploy key repository flow shows railpack beta label in build pack selector', function () {
Livewire::test(GithubPrivateRepositoryDeployKey::class, ['type' => 'private-deploy-key'])
->set('current_step', 'repository')
->assertSee('Railpack (Beta)')
->assertSee('Beta');
});
});
+79
View File
@@ -0,0 +1,79 @@
<?php
use App\Models\InstanceSettings;
use App\Models\OauthSetting;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Socialite\Facades\Socialite;
uses(RefreshDatabase::class);
beforeEach(function () {
InstanceSettings::create([
'id' => 0,
'is_registration_enabled' => false,
]);
OauthSetting::create([
'provider' => 'google',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'redirect_uri' => 'https://coolify.example.com/auth/google/callback',
'tenant' => 'example.com',
]);
});
it('logs in an existing user when the oauth provider returns a mixed-case email', function () {
config()->set('app.maintenance.driver', 'file');
$user = User::factory()->create([
'email' => 'username@example.edu',
]);
$provider = \Mockery::mock();
$provider->shouldReceive('setConfig')->once()->andReturnSelf();
$provider->shouldReceive('with')->once()->with(['hd' => 'example.com'])->andReturnSelf();
$provider->shouldReceive('user')->once()->andReturn((object) [
'email' => 'UserName@example.edu',
'name' => 'Example User',
'id' => 'google-user-id',
]);
Socialite::shouldReceive('driver')->once()->with('google')->andReturn($provider);
$response = $this->get(route('auth.callback', 'google'));
$response->assertRedirect('/');
$this->assertAuthenticatedAs($user);
expect(User::count())->toBe(1);
});
it('rejects oauth logins when the provider does not return an email address', function (?string $providerEmail) {
config()->set('app.maintenance.driver', 'file');
InstanceSettings::firstOrCreate([
'id' => 0,
], [
'is_registration_enabled' => false,
])->update([
'is_registration_enabled' => true,
]);
$provider = \Mockery::mock();
$provider->shouldReceive('setConfig')->once()->andReturnSelf();
$provider->shouldReceive('with')->once()->with(['hd' => 'example.com'])->andReturnSelf();
$provider->shouldReceive('user')->once()->andReturn((object) [
'email' => $providerEmail,
'name' => 'Example User',
'id' => 'google-user-id',
]);
Socialite::shouldReceive('driver')->once()->with('google')->andReturn($provider);
$response = $this->from('/login')->get(route('auth.callback', 'google'));
$response->assertRedirect('/login');
expect(User::count())->toBe(0);
})->with([
'null email' => [null],
'blank email' => [' '],
]);
@@ -0,0 +1,70 @@
<?php
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);
beforeEach(function () {
$this->teamA = Team::factory()->create();
$this->teamB = Team::factory()->create();
$this->serverA = Server::factory()->create(['team_id' => $this->teamA->id]);
$this->destinationA = StandaloneDocker::where('server_id', $this->serverA->id)->first();
$this->projectA = Project::factory()->create(['team_id' => $this->teamA->id]);
$this->envA = Environment::factory()->create(['project_id' => $this->projectA->id]);
});
test('queryDatabaseByUuidWithinTeam returns database when team owns it', function () {
$database = StandalonePostgresql::create([
'name' => 'pg-team-a',
'image' => 'postgres:15-alpine',
'postgres_user' => 'postgres',
'postgres_password' => 'password',
'postgres_db' => 'postgres',
'environment_id' => $this->envA->id,
'destination_id' => $this->destinationA->id,
'destination_type' => $this->destinationA->getMorphClass(),
]);
$found = queryDatabaseByUuidWithinTeam($database->uuid, (string) $this->teamA->id);
expect($found)->not->toBeNull();
expect($found->uuid)->toBe($database->uuid);
expect($found)->toBeInstanceOf(StandalonePostgresql::class);
});
test('queryDatabaseByUuidWithinTeam returns null when team does not own the database', function () {
$database = StandalonePostgresql::create([
'name' => 'pg-team-a',
'image' => 'postgres:15-alpine',
'postgres_user' => 'postgres',
'postgres_password' => 'password',
'postgres_db' => 'postgres',
'environment_id' => $this->envA->id,
'destination_id' => $this->destinationA->id,
'destination_type' => $this->destinationA->getMorphClass(),
]);
$found = queryDatabaseByUuidWithinTeam($database->uuid, (string) $this->teamB->id);
expect($found)->toBeNull();
});
test('queryDatabaseByUuidWithinTeam returns null for unknown uuid', function () {
$found = queryDatabaseByUuidWithinTeam('does-not-exist', (string) $this->teamA->id);
expect($found)->toBeNull();
});
test('queryDatabaseByUuidWithinTeam can query every registered standalone database type without error', function () {
foreach (STANDALONE_DATABASE_MODELS as $slug => $modelClass) {
$count = $modelClass::query()->whereUuid('non-existent-uuid')->count();
expect($count)->toBe(0, "{$modelClass} ({$slug}) failed whereUuid() smoke query");
}
});
@@ -0,0 +1,107 @@
<?php
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\Team;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
uses(RefreshDatabase::class);
beforeEach(function () {
Bus::fake([ApplicationDeploymentJob::class]);
$this->team = Team::factory()->create();
$this->server = Server::factory()->create(['team_id' => $this->team->id]);
$this->destination = StandaloneDocker::factory()->create([
'server_id' => $this->server->id,
'network' => 'test-network-'.fake()->unique()->word(),
]);
$this->project = Project::factory()->create(['team_id' => $this->team->id]);
$this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
});
function makeApplication(int $environmentId, int $destinationId, ?string $gitCommitSha): Application
{
$attributes = [
'environment_id' => $environmentId,
'destination_id' => $destinationId,
'destination_type' => StandaloneDocker::class,
];
if ($gitCommitSha !== null) {
$attributes['git_commit_sha'] = $gitCommitSha;
}
return Application::factory()->create($attributes);
}
describe('queue_application_deployment commit resolution', function () {
test('uses application git_commit_sha when commit parameter omitted', function () {
$pinnedSha = 'abc123def456abc123def456abc123def456abc1';
$application = makeApplication($this->environment->id, $this->destination->id, $pinnedSha);
$result = queue_application_deployment(
application: $application,
deployment_uuid: 'test-deploy-uuid-1',
);
expect($result['status'])->toBe('queued');
$deployment = ApplicationDeploymentQueue::where('deployment_uuid', 'test-deploy-uuid-1')->first();
expect($deployment)->not->toBeNull();
expect($deployment->commit)->toBe($pinnedSha);
});
test('falls back to HEAD when both commit parameter and git_commit_sha are unset', function () {
$application = makeApplication($this->environment->id, $this->destination->id, 'HEAD');
$result = queue_application_deployment(
application: $application,
deployment_uuid: 'test-deploy-uuid-2',
);
expect($result['status'])->toBe('queued');
$deployment = ApplicationDeploymentQueue::where('deployment_uuid', 'test-deploy-uuid-2')->first();
expect($deployment->commit)->toBe('HEAD');
});
test('explicit commit parameter overrides application git_commit_sha', function () {
$pinnedSha = 'abc123def456abc123def456abc123def456abc1';
$webhookSha = '111222333444555666777888999000aaabbbccc1';
$application = makeApplication($this->environment->id, $this->destination->id, $pinnedSha);
$result = queue_application_deployment(
application: $application,
deployment_uuid: 'test-deploy-uuid-3',
commit: $webhookSha,
);
expect($result['status'])->toBe('queued');
$deployment = ApplicationDeploymentQueue::where('deployment_uuid', 'test-deploy-uuid-3')->first();
expect($deployment->commit)->toBe($webhookSha);
});
test('treats empty string commit parameter as unset and uses git_commit_sha', function () {
$pinnedSha = 'abc123def456abc123def456abc123def456abc1';
$application = makeApplication($this->environment->id, $this->destination->id, $pinnedSha);
$result = queue_application_deployment(
application: $application,
deployment_uuid: 'test-deploy-uuid-4',
commit: '',
);
expect($result['status'])->toBe('queued');
$deployment = ApplicationDeploymentQueue::where('deployment_uuid', 'test-deploy-uuid-4')->first();
expect($deployment->commit)->toBe($pinnedSha);
});
});
@@ -32,3 +32,75 @@ it('keeps realtime terminal server logging restricted to development environment
->toContain('if (!terminalDebugEnabled) {')
->not->toContain("console.log('Coolify realtime terminal server listening on port 6002. Let the hacking begin!');");
});
it('configures a server-initiated WebSocket heartbeat to survive proxy idle timeouts', function () {
$terminalServer = file_get_contents(base_path('docker/coolify-realtime/terminal-server.js'));
expect($terminalServer)
->toContain('ws.isAlive = true;')
->toContain("ws.on('pong'")
->toContain('ws.ping();')
->toContain('ws.terminate();')
->toContain('HEARTBEAT_INTERVAL_MS');
});
it('removes the keepalive short-circuit that fired when the tab was hidden', function () {
$terminalClient = file_get_contents(base_path('resources/js/terminal.js'));
expect($terminalClient)
->not->toContain('// Skip keepalive when document is hidden to prevent unnecessary disconnects');
});
it('uses a fast probe timeout when the tab regains visibility', function () {
$terminalClient = file_get_contents(base_path('resources/js/terminal.js'));
expect($terminalClient)
->toContain("'Visibility-resume timeout'");
});
it('closes idle terminal sessions after 30 minutes on the server', function () {
$terminalServer = file_get_contents(base_path('docker/coolify-realtime/terminal-server.js'));
expect($terminalServer)
->toContain('IDLE_TIMEOUT_MS = 30 * 60 * 1000')
->toContain('lastActivityAt')
->toContain("ws.send('idle-timeout');")
->toContain("ws.close(1000, 'Idle timeout');");
});
it('reacts to idle-timeout sentinel on the client and shows a user-facing error', function () {
$terminalClient = file_get_contents(base_path('resources/js/terminal.js'));
expect($terminalClient)
->toContain("event.data === 'idle-timeout'")
->toContain('Terminal closed after 30 minutes of inactivity.');
});
it('replays the last command on reconnect so the PTY respawns automatically', function () {
$terminalClient = file_get_contents(base_path('resources/js/terminal.js'));
expect($terminalClient)
->toContain('lastSentCommand')
->toContain('Replaying last command after reconnect.')
->toContain('this.lastSentCommand = null;');
});
it('buffers messages received before the realtime server finishes auth so the replay is not lost', function () {
$terminalServer = file_get_contents(base_path('docker/coolify-realtime/terminal-server.js'));
expect($terminalServer)
->toContain('authReady: false')
->toContain('pendingMessages: []')
->toContain('userSession.pendingMessages.push(message)')
->toContain('userSession.authReady = true');
});
it('preserves terminal scrollback across transient reconnects', function () {
$terminalClient = file_get_contents(base_path('resources/js/terminal.js'));
expect($terminalClient)
->toContain('── Connection lost at')
->toContain('── Reconnected at')
// resetTerminal must NOT call term.reset()/term.clear() any more — those wipe scrollback.
->not->toContain("this.term.reset();\n this.term.clear();");
});
@@ -0,0 +1,35 @@
<?php
use App\Console\Commands\ViewScheduledLogs;
use App\Http\Middleware\CheckForcePasswordReset;
use App\Http\Middleware\DecideWhatToDoWithUser;
use App\Models\InstanceSettings;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Once;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->withoutMiddleware([DecideWhatToDoWithUser::class, CheckForcePasswordReset::class]);
Once::flush();
if (! InstanceSettings::find(0)) {
$settings = new InstanceSettings;
$settings->id = 0;
$settings->saveQuietly();
}
});
describe('logs:scheduled --date option', function () {
test('rejects a malformed date and exits before touching the shell', function () {
$this->artisan('logs:scheduled', ['--date' => '2025-01-01; touch /tmp/pwn'])
->expectsOutputToContain('Invalid date format')
->assertExitCode(ViewScheduledLogs::INVALID);
expect(file_exists('/tmp/pwn'))->toBeFalse();
});
test('accepts a well-formed date', function () {
$this->artisan('logs:scheduled', ['--date' => '2025-01-01'])
->assertExitCode(0);
});
});
+66
View File
@@ -0,0 +1,66 @@
<?php
use App\Models\Application;
use App\Models\Project;
use App\Models\ScheduledTask;
use App\Models\Server;
use App\Models\Service;
use App\Models\StandaloneDocker;
use App\Models\Team;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->team = Team::factory()->create();
$this->server = Server::factory()->create(['team_id' => $this->team->id]);
$this->destination = StandaloneDocker::where('server_id', $this->server->id)->first();
$this->project = Project::factory()->create(['team_id' => $this->team->id]);
$this->environment = $this->project->environments()->first();
});
it('returns null when neither application nor service is set', function () {
$task = ScheduledTask::factory()->create([
'team_id' => $this->team->id,
]);
expect($task->server())->toBeNull();
});
it('does not throw when accessing dynamic properties on a parentless task', function () {
$task = ScheduledTask::factory()->create([
'team_id' => $this->team->id,
]);
expect(fn () => $task->server())->not->toThrow(Exception::class);
});
it('resolves server via application destination', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'destination_id' => $this->destination->id,
'destination_type' => $this->destination->getMorphClass(),
]);
$task = ScheduledTask::factory()->create([
'application_id' => $application->id,
'team_id' => $this->team->id,
]);
expect($task->server()?->id)->toBe($this->server->id);
});
it('resolves server via service destination', function () {
$service = Service::factory()->create([
'environment_id' => $this->environment->id,
'destination_id' => $this->destination->id,
'destination_type' => $this->destination->getMorphClass(),
]);
$task = ScheduledTask::factory()->create([
'service_id' => $service->id,
'team_id' => $this->team->id,
]);
expect($task->server()?->id)->toBe($this->server->id);
});
+445
View File
@@ -0,0 +1,445 @@
<?php
use App\Models\Application;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Server;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
uses(RefreshDatabase::class);
function makeAuditTeamUser(): array
{
$team = Team::factory()->create();
$user = User::factory()->create();
$team->members()->attach($user->id, ['role' => 'owner']);
session(['currentTeam' => $team]);
test()->actingAs($user);
return [$team, $user];
}
function makeAuditApiToken(User $user, Team $team, array $abilities = ['root']): string
{
$token = $user->createToken('audit-test', $abilities);
DB::table('personal_access_tokens')->where('id', $token->accessToken->id)->update([
'team_id' => $team->id,
]);
return $token->plainTextToken;
}
function makeAuditApplication(string $repo = 'test-org/test-repo'): Application
{
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$environment = Environment::factory()->create(['project_id' => $project->id]);
$server = Server::factory()->create(['team_id' => $team->id]);
$destination = $server->standaloneDockers()->firstOrFail();
return Application::create([
'name' => 'audit-test-app',
'git_repository' => "https://github.com/{$repo}",
'git_branch' => 'main',
'build_pack' => 'nixpacks',
'ports_exposes' => '3000',
'environment_id' => $environment->id,
'destination_id' => $destination->id,
'destination_type' => $destination->getMorphClass(),
]);
}
describe('audit channel helper', function () {
test('auditLog writes structured payload to audit channel', function () {
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('info')
->once()
->with('test.event', Mockery::on(function ($context) {
return $context['event'] === 'test.event'
&& $context['custom_field'] === 'value'
&& array_key_exists('ip', $context)
&& array_key_exists('user_id', $context);
}));
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
auditLog('test.event', ['custom_field' => 'value']);
});
test('auditLog warning level routes correctly', function () {
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')->once()->with('test.failed', Mockery::any());
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
auditLog('test.failed', [], 'warning');
});
test('auditLogWebhookFailure logs warning with provider tag', function () {
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->once()
->with('webhook.github.signature_failed', Mockery::on(function ($context) {
return $context['reason'] === 'invalid_signature'
&& $context['event'] === 'webhook.github.signature_failed'
&& array_key_exists('ip', $context);
}));
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
auditLogWebhookFailure('github', 'invalid_signature', ['extra' => 'context']);
});
test('auditLog never includes raw secret keys in context', function () {
$captured = null;
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('info')
->once()
->with(Mockery::any(), Mockery::on(function ($context) use (&$captured) {
$captured = $context;
return true;
}));
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
auditLog('test.private_key.created', [
'team_id' => '1',
'private_key_uuid' => 'abc',
'fingerprint' => 'SHA256:xyz',
]);
expect($captured)->toBeArray();
// Helper itself never injects secret-bearing keys.
$disallowed = ['private_key', 'password', 'token', 'webhook_secret', 'signature', 'client_secret'];
foreach (array_keys($captured) as $key) {
expect(in_array(strtolower($key), $disallowed, true))->toBeFalse();
}
});
});
describe('webhook signature failure logging', function () {
test('GitHub manual webhook with bad signature logs to audit channel', function () {
$app = makeAuditApplication();
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('webhook.github.signature_failed', Mockery::any());
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$payload = json_encode([
'ref' => 'refs/heads/main',
'repository' => ['full_name' => 'test-org/test-repo'],
'after' => 'abc123',
'commits' => [],
]);
$response = $this->call('POST', '/webhooks/source/github/events/manual', [], [], [], [
'HTTP_X-GitHub-Event' => 'push',
'HTTP_X-Hub-Signature-256' => 'sha256=forgedhashvalue',
'CONTENT_TYPE' => 'application/json',
], $payload);
$response->assertOk();
expect($response->getContent())->toContain('Invalid signature');
});
test('GitLab manual webhook with bad token logs to audit channel', function () {
$app = makeAuditApplication();
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('webhook.gitlab.signature_failed', Mockery::any());
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$response = $this->postJson('/webhooks/source/gitlab/events/manual', [
'object_kind' => 'push',
'ref' => 'refs/heads/main',
'project' => ['path_with_namespace' => 'test-org/test-repo'],
'after' => 'abc123',
'commits' => [],
], [
'X-Gitlab-Token' => 'wrong-token',
]);
$response->assertOk();
expect($response->getContent())->toContain('Invalid signature');
});
test('Bitbucket manual webhook with malformed signature logs to audit channel', function () {
$app = makeAuditApplication();
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('webhook.bitbucket.signature_failed', Mockery::any());
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$payload = json_encode([
'push' => ['changes' => [['new' => ['name' => 'main', 'target' => ['hash' => 'abc123']]]]],
'repository' => ['full_name' => 'test-org/test-repo'],
]);
$response = $this->call('POST', '/webhooks/source/bitbucket/events/manual', [], [], [], [
'HTTP_X-Event-Key' => 'repo:push',
'HTTP_X-Hub-Signature' => 'sha1=anyvalue',
'CONTENT_TYPE' => 'application/json',
], $payload);
$response->assertOk();
expect($response->getContent())->toContain('Invalid signature');
});
test('Gitea manual webhook with bad signature logs to audit channel', function () {
$app = makeAuditApplication();
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('webhook.gitea.signature_failed', Mockery::any());
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$payload = json_encode([
'ref' => 'refs/heads/main',
'repository' => ['full_name' => 'test-org/test-repo'],
'after' => 'abc123',
'commits' => [],
]);
$response = $this->call('POST', '/webhooks/source/gitea/events/manual', [], [], [], [
'HTTP_X-Gitea-Event' => 'push',
'HTTP_X-Hub-Signature-256' => 'sha256=forgedhashvalue',
'CONTENT_TYPE' => 'application/json',
], $payload);
$response->assertOk();
expect($response->getContent())->toContain('Invalid signature');
});
});
describe('API mutation audit logging', function () {
test('private key creation emits api.private_key.created audit event', function () {
[$team, $user] = makeAuditTeamUser();
$token = makeAuditApiToken($user, $team);
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('info')
->atLeast()
->once()
->with('api.private_key.created', Mockery::on(function ($context) {
return $context['event'] === 'api.private_key.created'
&& ! array_key_exists('private_key', $context);
}));
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
// Generate a valid OpenSSH-format private key for the test.
$opensshKey = "-----BEGIN OPENSSH PRIVATE KEY-----\n".
base64_encode(str_repeat('a', 256)).
"\n-----END OPENSSH PRIVATE KEY-----";
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token,
'Content-Type' => 'application/json',
])->postJson('/api/v1/security/keys', [
'name' => 'test-key',
'description' => 'audit test',
'private_key' => $opensshKey,
]);
// Either 201 or 422 acceptable depending on validation; the assertion above verifies log if 201.
expect($response->status())->toBeIn([201, 422]);
});
test('enable_api denial for non-root team emits warning audit event', function () {
[$team, $user] = makeAuditTeamUser();
$token = makeAuditApiToken($user, $team);
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('api.instance.enable_denied', Mockery::any());
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token,
])->getJson('/api/v1/enable');
$response->assertStatus(403);
});
test('project creation emits api.project.created audit event', function () {
[$team, $user] = makeAuditTeamUser();
$token = makeAuditApiToken($user, $team);
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('info')
->atLeast()
->once()
->with('api.project.created', Mockery::on(function ($context) {
return $context['event'] === 'api.project.created'
&& ! empty($context['project_uuid'])
&& $context['project_name'] === 'audit-project';
}));
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token,
'Content-Type' => 'application/json',
])->postJson('/api/v1/projects', [
'name' => 'audit-project',
'description' => 'audit',
]);
$response->assertStatus(201);
});
});
describe('threat-detection audit logging (Phase 2)', function () {
test('missing bearer token logs api.auth.unauthenticated', function () {
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('api.auth.unauthenticated', Mockery::any());
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$response = $this->getJson('/api/v1/projects');
$response->assertStatus(401);
});
test('expired bearer token logs api.auth.unauthenticated', function () {
[$team, $user] = makeAuditTeamUser();
$token = $user->createToken('expired-audit', ['read'], now()->subDay());
DB::table('personal_access_tokens')->where('id', $token->accessToken->id)->update([
'team_id' => $team->id,
]);
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('api.auth.unauthenticated', Mockery::any());
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token->plainTextToken,
])->getJson('/api/v1/projects');
$response->assertStatus(401);
});
test('read-only token hitting write endpoint logs api.auth.ability_denied', function () {
[$team, $user] = makeAuditTeamUser();
$readToken = makeAuditApiToken($user, $team, ['read']);
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('api.auth.ability_denied', Mockery::on(function ($ctx) {
return in_array('write', $ctx['required_abilities'] ?? [], true);
}));
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$readToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/projects', [
'name' => 'should-fail',
]);
$response->assertStatus(403);
});
test('sentinel push without Authorization logs token_missing', function () {
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('webhook.sentinel.signature_failed', Mockery::on(function ($ctx) {
return $ctx['reason'] === 'token_missing';
}));
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$response = $this->postJson('/api/v1/sentinel/push', []);
$response->assertStatus(401);
});
test('sentinel push with un-decryptable bearer logs decrypt_failed', function () {
$auditChannel = Mockery::mock();
$auditChannel->shouldReceive('warning')
->atLeast()
->once()
->with('webhook.sentinel.signature_failed', Mockery::on(function ($ctx) {
return $ctx['reason'] === 'decrypt_failed';
}));
Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
Log::shouldReceive('warning')->andReturnNull();
Log::shouldReceive('info')->andReturnNull();
Log::shouldReceive('error')->andReturnNull();
$response = $this->withHeaders([
'Authorization' => 'Bearer not-a-valid-encrypted-payload',
])->postJson('/api/v1/sentinel/push', []);
$response->assertStatus(401);
});
});
@@ -414,7 +414,7 @@ describe('docker_compose_custom_command validation', function () {
expect($validator->fails())->toBeTrue();
});
test('rejects single quotes in docker_compose_custom_start_command', function () {
test('allows single-quoted arguments in docker_compose_custom_start_command', function () {
$rules = sharedDataApplications();
$validator = validator(
@@ -422,7 +422,7 @@ describe('docker_compose_custom_command validation', function () {
['docker_compose_custom_start_command' => $rules['docker_compose_custom_start_command']]
);
expect($validator->fails())->toBeTrue();
expect($validator->fails())->toBeFalse();
});
test('allows double quotes in docker_compose_custom_start_command', function () {
@@ -474,6 +474,127 @@ describe('docker_compose_custom_command validation', function () {
expect($method->invoke($instance, 'docker compose up -d --build', 'docker_compose_custom_start_command'))
->toBe('docker compose up -d --build');
});
test('rejects bare ampersand PoC payload (GHSA-chg4-63hm-xv9x)', function () {
$rules = sharedDataApplications();
$payload = 'true & docker run --rm -v /:/h alpine sh -c "cp /h/etc/shadow /h/tmp/leak"';
$validator = validator(
['docker_compose_custom_start_command' => $payload],
['docker_compose_custom_start_command' => $rules['docker_compose_custom_start_command']]
);
expect($validator->fails())->toBeTrue();
});
test('rejects bare ampersand across every shell-safe field', function ($field) {
$rules = sharedDataApplications();
$validator = validator(
[$field => 'cmd1 & cmd2'],
[$field => $rules[$field]]
);
expect($validator->fails())->toBeTrue();
})->with([
'install_command',
'build_command',
'start_command',
'docker_compose_custom_build_command',
'docker_compose_custom_start_command',
'custom_docker_run_options',
]);
test('rejects command substitution inside double quotes', function ($payload) {
$rules = sharedDataApplications();
$validator = validator(
['build_command' => "echo $payload"],
['build_command' => $rules['build_command']]
);
expect($validator->fails())->toBeTrue();
})->with(['"$(whoami)"', '"`whoami`"']);
test('rejects unbalanced quotes', function ($payload) {
$rules = sharedDataApplications();
$validator = validator(
['build_command' => $payload],
['build_command' => $rules['build_command']]
);
expect($validator->fails())->toBeTrue();
})->with(['echo "unterminated', "echo 'unterminated"]);
test('rejects backslash anywhere', function ($payload) {
$rules = sharedDataApplications();
$validator = validator(
['build_command' => $payload],
['build_command' => $rules['build_command']]
);
expect($validator->fails())->toBeTrue();
})->with(['echo \\;', 'echo \\$HOME']);
test('runtime validateShellSafeCommand rejects bare ampersand payload', function () {
$job = new ReflectionClass(ApplicationDeploymentJob::class);
$method = $job->getMethod('validateShellSafeCommand');
$method->setAccessible(true);
$instance = $job->newInstanceWithoutConstructor();
expect(fn () => $method->invoke($instance, 'true & whoami', 'docker_compose_custom_start_command'))
->toThrow(RuntimeException::class, 'contains forbidden shell characters');
});
test('allows logical OR chaining', function ($cmd) {
$rules = sharedDataApplications();
$validator = validator(
['build_command' => $cmd],
['build_command' => $rules['build_command']]
);
expect($validator->fails())->toBeFalse();
})->with([
'make build || make clean',
'npm run build || npm run fallback',
'cmd-a || cmd-b && cmd-c',
]);
test('allows glob and bang tokens', function ($cmd) {
$rules = sharedDataApplications();
$validator = validator(
['build_command' => $cmd],
['build_command' => $rules['build_command']]
);
expect($validator->fails())->toBeFalse();
})->with([
'rm *.tmp',
'cp src/?.js dist/',
'! grep -q foo && echo missing',
'docker build --tag app-v1!',
]);
test('rejects bare pipe even though || is allowed', function ($cmd) {
$rules = sharedDataApplications();
$validator = validator(
['build_command' => $cmd],
['build_command' => $rules['build_command']]
);
expect($validator->fails())->toBeTrue();
})->with([
'cmd | cat',
'cmd|cat',
'a |b',
'a| b',
]);
});
describe('custom_docker_run_options validation', function () {
@@ -676,7 +797,7 @@ describe('API route middleware for deploy actions', function () {
});
});
describe('install/build/start command validation (GHSA-9pp4-wcmj-rq73)', function () {
describe('install/build/start command validation', function () {
test('rejects semicolon injection in install_command', function () {
$rules = sharedDataApplications();
@@ -4,6 +4,7 @@ use App\Models\Server;
use App\Models\ServerSetting;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
uses(RefreshDatabase::class);
@@ -78,11 +79,73 @@ describe('ServerSetting::isValidSentinelToken', function () {
expect(ServerSetting::isValidSentinelToken(''))->toBeFalse();
});
it('returns false for null sentinel token', function () {
expect(ServerSetting::isValidSentinelToken(null))->toBeFalse();
});
it('rejects the reported PoC payload', function () {
expect(ServerSetting::isValidSentinelToken('abc" ; id >/tmp/coolify_poc_sentinel ; echo "'))->toBeFalse();
});
});
describe('ServerSetting::ensureValidSentinelToken', function () {
it('regenerates empty sentinel token via ensureValidSentinelToken', function () {
$settings = $this->server->settings;
DB::table('server_settings')->where('id', $settings->id)->update(['sentinel_token' => '']);
$settings->refresh();
$token = $settings->ensureValidSentinelToken();
expect($token)->not->toBeEmpty();
expect(ServerSetting::isValidSentinelToken($token))->toBeTrue();
expect($settings->fresh()->sentinel_token)->toBe($token);
});
it('regenerates token when stored value cannot be decrypted', function () {
$settings = $this->server->settings;
DB::table('server_settings')->where('id', $settings->id)->update(['sentinel_token' => 'not-encrypted-junk']);
$settings->refresh();
$token = $settings->ensureValidSentinelToken();
expect(ServerSetting::isValidSentinelToken($token))->toBeTrue();
expect($settings->fresh()->sentinel_token)->toBe($token);
});
it('returns existing valid token without regenerating', function () {
$settings = $this->server->settings;
$original = $settings->sentinel_token;
$token = $settings->ensureValidSentinelToken();
expect($token)->toBe($original);
});
it('throws RuntimeException only when regeneration also fails', function () {
$settings = $this->server->settings;
DB::table('server_settings')->where('id', $settings->id)->update(['sentinel_token' => '']);
$stub = new class extends ServerSetting
{
protected $table = 'server_settings';
public function generateSentinelToken(bool $save = true, bool $ignoreEvent = false): string
{
DB::table('server_settings')->where('id', $this->id)->update([
'sentinel_token' => encrypt('invalid token with spaces!'),
]);
return '';
}
};
$stub->setRawAttributes($settings->fresh()->getAttributes(), true);
$stub->exists = true;
expect(fn () => $stub->ensureValidSentinelToken())
->toThrow(RuntimeException::class, 'Sentinel token invalid after regeneration');
});
});
describe('generated sentinel tokens are valid', function () {
it('generates tokens that pass format validation', function () {
$settings = $this->server->settings;
@@ -92,4 +155,11 @@ describe('generated sentinel tokens are valid', function () {
expect($token)->not->toBeEmpty();
expect(ServerSetting::isValidSentinelToken($token))->toBeTrue();
});
it('returns the same value the cast reads back', function () {
$settings = $this->server->settings;
$returned = $settings->generateSentinelToken(save: true, ignoreEvent: true);
expect($settings->fresh()->sentinel_token)->toBe($returned);
});
});
@@ -0,0 +1,74 @@
<?php
use App\Models\InstanceSettings;
use App\Models\Server;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
InstanceSettings::forceCreate(['id' => 0, 'is_api_enabled' => true]);
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
session(['currentTeam' => $this->team]);
$this->server = Server::factory()->create([
'team_id' => $this->team->id,
]);
$newToken = $this->user->createToken('write-token', ['write']);
$newToken->accessToken->forceFill(['team_id' => $this->team->id])->save();
$this->token = $newToken->plainTextToken;
});
it('PATCH updates connection_timeout via API', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->token,
'Content-Type' => 'application/json',
])->patchJson('/api/v1/servers/'.$this->server->uuid, [
'connection_timeout' => 45,
]);
$response->assertStatus(201);
expect($this->server->settings->fresh()->connection_timeout)->toBe(45);
});
it('PATCH rejects connection_timeout out of range', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->token,
'Content-Type' => 'application/json',
])->patchJson('/api/v1/servers/'.$this->server->uuid, [
'connection_timeout' => 0,
]);
$response->assertStatus(422);
$response->assertJsonStructure(['errors' => ['connection_timeout']]);
});
it('PATCH rejects connection_timeout above max', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->token,
'Content-Type' => 'application/json',
])->patchJson('/api/v1/servers/'.$this->server->uuid, [
'connection_timeout' => 999,
]);
$response->assertStatus(422);
$response->assertJsonStructure(['errors' => ['connection_timeout']]);
});
it('PATCH rejects non-integer connection_timeout', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->token,
'Content-Type' => 'application/json',
])->patchJson('/api/v1/servers/'.$this->server->uuid, [
'connection_timeout' => 'fast',
]);
$response->assertStatus(422);
$response->assertJsonStructure(['errors' => ['connection_timeout']]);
});
@@ -0,0 +1,43 @@
<?php
use App\Helpers\SshMultiplexingHelper;
use App\Models\Server;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$user = User::factory()->create();
$this->team = $user->teams()->first();
$this->server = Server::factory()->create([
'team_id' => $this->team->id,
]);
});
it('defaults connection_timeout to 10 seconds for new servers', function () {
expect($this->server->settings->connection_timeout)->toBe(10);
});
it('persists a custom connection_timeout value', function () {
$this->server->settings->connection_timeout = 30;
$this->server->settings->save();
expect($this->server->settings->fresh()->connection_timeout)->toBe(30);
});
it('returns the per-server connection_timeout from getConnectionTimeout', function () {
$this->server->settings->connection_timeout = 45;
$this->server->settings->save();
expect(SshMultiplexingHelper::getConnectionTimeout($this->server->fresh()))->toBe(45);
});
it('falls back to config default when connection_timeout is invalid', function () {
$this->server->settings->connection_timeout = 0;
$this->server->settings->saveQuietly();
$expected = (int) config('constants.ssh.connection_timeout');
expect(SshMultiplexingHelper::getConnectionTimeout($this->server->fresh()))->toBe($expected);
});
@@ -0,0 +1,105 @@
<?php
use App\Events\ServerReachabilityChanged;
use App\Models\Server;
use App\Models\Team;
use App\Notifications\Channels\EmailChannel;
use App\Notifications\Server\Reachable;
use App\Notifications\Server\Unreachable;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->team = Team::factory()->create();
$this->team->emailNotificationSettings()->update([
'use_instance_email_settings' => true,
'server_unreachable_email_notifications' => true,
'server_reachable_email_notifications' => true,
]);
$this->server = Server::factory()->create(['team_id' => $this->team->id]);
Notification::fake();
});
it('sends Unreachable notification when threshold reached and not yet notified', function () {
$this->server->settings()->update(['is_reachable' => false]);
$this->server->forceFill([
'unreachable_count' => 2,
'unreachable_notification_sent' => false,
])->save();
ServerReachabilityChanged::dispatch($this->server->fresh());
Notification::assertSentTo($this->team, Unreachable::class);
expect($this->server->fresh()->unreachable_notification_sent)->toBeTrue();
});
it('does not send Unreachable on first transient failure (count=1)', function () {
$this->server->settings()->update(['is_reachable' => false]);
$this->server->forceFill([
'unreachable_count' => 1,
'unreachable_notification_sent' => false,
])->save();
ServerReachabilityChanged::dispatch($this->server->fresh());
Notification::assertNothingSent();
});
it('does not send Unreachable when already notified', function () {
$this->server->settings()->update(['is_reachable' => false]);
$this->server->forceFill([
'unreachable_count' => 5,
'unreachable_notification_sent' => true,
])->save();
ServerReachabilityChanged::dispatch($this->server->fresh());
Notification::assertNothingSent();
});
it('sends Reachable notification on recovery when previously notified', function () {
$this->server->settings()->update(['is_reachable' => true]);
$this->server->forceFill([
'unreachable_count' => 0,
'unreachable_notification_sent' => true,
])->save();
$fresh = $this->server->fresh();
expect($fresh->unreachable_notification_sent)->toBeTrue();
expect((bool) $fresh->settings->is_reachable)->toBeTrue();
ServerReachabilityChanged::dispatch($fresh);
Notification::assertSentTo($this->team, Reachable::class);
expect($this->server->fresh()->unreachable_notification_sent)->toBeFalse();
});
it('does not send Reachable when never notified', function () {
$this->server->settings()->update(['is_reachable' => true]);
$this->server->forceFill([
'unreachable_count' => 0,
'unreachable_notification_sent' => false,
])->save();
ServerReachabilityChanged::dispatch($this->server->fresh());
Notification::assertNothingSent();
});
it('routes Unreachable notification through EmailChannel when email toggle is on', function () {
$this->server->settings()->update(['is_reachable' => false]);
$this->server->forceFill([
'unreachable_count' => 2,
'unreachable_notification_sent' => false,
])->save();
ServerReachabilityChanged::dispatch($this->server->fresh());
Notification::assertSentTo($this->team, Unreachable::class, function ($notification, $channels) {
return in_array(EmailChannel::class, $channels);
});
});
@@ -0,0 +1,71 @@
<?php
use App\Models\Environment;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDocker;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use App\Models\Team;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->team = Team::factory()->create();
$this->server = Server::factory()->create(['team_id' => $this->team->id]);
$this->destination = StandaloneDocker::where('server_id', $this->server->id)->first();
$this->project = Project::factory()->create(['team_id' => $this->team->id]);
$this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
});
function attachDb(string $modelClass, array $extra, $destination, $environment)
{
return $modelClass::create(array_merge([
'name' => 'test-'.strtolower(class_basename($modelClass)),
'environment_id' => $environment->id,
'destination_id' => $destination->id,
'destination_type' => $destination->getMorphClass(),
], $extra));
}
test('StandaloneDocker::databases() includes attached keydb', function () {
attachDb(StandaloneKeydb::class, ['keydb_password' => 'pw'], $this->destination, $this->environment);
expect($this->destination->databases()->count())->toBe(1);
expect($this->destination->attachedTo())->toBeTrue();
});
test('StandaloneDocker::databases() includes attached dragonfly', function () {
attachDb(StandaloneDragonfly::class, ['dragonfly_password' => 'pw'], $this->destination, $this->environment);
expect($this->destination->databases()->count())->toBe(1);
expect($this->destination->attachedTo())->toBeTrue();
});
test('StandaloneDocker::databases() includes attached clickhouse', function () {
attachDb(StandaloneClickhouse::class, ['clickhouse_admin_password' => 'pw'], $this->destination, $this->environment);
expect($this->destination->databases()->count())->toBe(1);
expect($this->destination->attachedTo())->toBeTrue();
});
test('StandaloneDocker::databases() includes all 8 standalone database types', function () {
attachDb(StandalonePostgresql::class, ['postgres_password' => 'pw'], $this->destination, $this->environment);
attachDb(StandaloneRedis::class, ['redis_password' => 'pw'], $this->destination, $this->environment);
attachDb(StandaloneMongodb::class, ['mongo_initdb_root_password' => 'pw'], $this->destination, $this->environment);
attachDb(StandaloneMysql::class, ['mysql_root_password' => 'pw', 'mysql_password' => 'pw'], $this->destination, $this->environment);
attachDb(StandaloneMariadb::class, ['mariadb_root_password' => 'pw', 'mariadb_password' => 'pw'], $this->destination, $this->environment);
attachDb(StandaloneKeydb::class, ['keydb_password' => 'pw'], $this->destination, $this->environment);
attachDb(StandaloneDragonfly::class, ['dragonfly_password' => 'pw'], $this->destination, $this->environment);
attachDb(StandaloneClickhouse::class, ['clickhouse_admin_password' => 'pw'], $this->destination, $this->environment);
expect($this->destination->databases()->count())->toBe(8);
expect($this->destination->attachedTo())->toBeTrue();
});
@@ -2,10 +2,14 @@
use App\Jobs\ServerLimitCheckJob;
use App\Jobs\StripeProcessJob;
use App\Jobs\SubscriptionInvoiceFailedJob;
use App\Jobs\VerifyStripeSubscriptionStatusJob;
use App\Models\Subscription;
use App\Models\Team;
use App\Models\User;
use App\Notifications\Internal\GeneralNotification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Queue;
uses(RefreshDatabase::class);
@@ -228,3 +232,65 @@ describe('ServerLimitCheckJob dispatch is guarded by team check', function () {
Queue::assertNotPushed(ServerLimitCheckJob::class);
});
});
describe('missing subscription Stripe webhooks are ignored', function () {
test('does not send internal notifications or queue follow-up jobs', function (array $event) {
Queue::fake();
$rootTeam = Team::factory()->create(['id' => 0]);
$rootTeam->discordNotificationSettings()->update(['discord_enabled' => true]);
Notification::fake();
$job = new StripeProcessJob($event);
$job->handle();
Notification::assertNothingSent();
Notification::assertNotSentTo($rootTeam, GeneralNotification::class);
Queue::assertNotPushed(SubscriptionInvoiceFailedJob::class);
Queue::assertNotPushed(VerifyStripeSubscriptionStatusJob::class);
})->with([
'invoice paid' => [[
'type' => 'invoice.paid',
'data' => [
'object' => [
'customer' => 'cus_missing_invoice_paid',
'amount_paid' => 1000,
'subscription' => 'sub_missing_invoice_paid',
'lines' => [
'data' => [[
'plan' => ['id' => 'price_dynamic_monthly'],
]],
],
],
],
]],
'invoice payment failed' => [[
'type' => 'invoice.payment_failed',
'data' => [
'object' => [
'customer' => 'cus_missing_invoice_payment_failed',
'id' => 'in_missing_invoice_payment_failed',
'payment_intent' => null,
],
],
]],
'payment intent payment failed' => [[
'type' => 'payment_intent.payment_failed',
'data' => [
'object' => [
'customer' => 'cus_missing_payment_intent_failed',
],
],
]],
'customer subscription deleted' => [[
'type' => 'customer.subscription.deleted',
'data' => [
'object' => [
'customer' => 'cus_missing_subscription_deleted',
'id' => 'sub_missing_subscription_deleted',
],
],
]],
]);
});
@@ -0,0 +1,65 @@
<?php
use App\Exceptions\DeploymentException;
use Illuminate\Contracts\Queue\Job;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Queue\TimeoutExceededException;
use Laravel\Horizon\Contracts\JobRepository;
use Mockery\MockInterface;
function fakeJob(string $uuid): Job
{
$job = Mockery::mock(Job::class)->shouldIgnoreMissing();
$job->shouldReceive('uuid')->andReturn($uuid);
$job->shouldReceive('getJobId')->andReturn($uuid);
return $job;
}
function fireJobFailed(Job $job, Throwable $exception): void
{
event(new JobFailed('redis', $job, $exception));
}
beforeEach(function () {
config(['constants.coolify.self_hosted' => false]);
});
test('scrubs Horizon failed entry for DeploymentException on cloud', function () {
$uuid = 'uuid-deployment-1';
$this->mock(JobRepository::class, function (MockInterface $mock) use ($uuid) {
$mock->shouldReceive('deleteFailed')->once()->with($uuid);
});
fireJobFailed(fakeJob($uuid), new DeploymentException('build failed'));
});
test('scrubs Horizon failed entry for TimeoutExceededException on cloud', function () {
$uuid = 'uuid-timeout-1';
$this->mock(JobRepository::class, function (MockInterface $mock) use ($uuid) {
$mock->shouldReceive('deleteFailed')->once()->with($uuid);
});
fireJobFailed(fakeJob($uuid), new TimeoutExceededException('worker timeout'));
});
test('does not scrub generic exceptions on cloud', function () {
$this->mock(JobRepository::class, function (MockInterface $mock) {
$mock->shouldNotReceive('deleteFailed');
});
fireJobFailed(fakeJob('uuid-generic-1'), new RuntimeException('boom'));
});
test('does not scrub when self-hosted even for filtered exceptions', function () {
config(['constants.coolify.self_hosted' => true]);
$this->mock(JobRepository::class, function (MockInterface $mock) {
$mock->shouldNotReceive('deleteFailed');
});
fireJobFailed(fakeJob('uuid-deployment-2'), new DeploymentException('build failed'));
fireJobFailed(fakeJob('uuid-timeout-2'), new TimeoutExceededException('worker timeout'));
});
@@ -0,0 +1,249 @@
<?php
use App\Exceptions\DeploymentException;
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use Illuminate\Support\Collection;
use Tests\TestCase;
uses(TestCase::class);
class TestableRailpackDeploymentJob extends ApplicationDeploymentJob
{
public array $recordedCommands = [];
public function __construct() {}
public function execute_remote_command(...$commands)
{
$this->recordedCommands[] = $commands;
}
}
function makeRailpackDeploymentJob(array $applicationAttributes = [], array $savedOutputs = []): array
{
$job = new TestableRailpackDeploymentJob;
$reflection = new ReflectionClass(ApplicationDeploymentJob::class);
$application = new Application($applicationAttributes);
foreach ([
'application' => $application,
'workdir' => '/artifacts/test-app',
'deployment_uuid' => 'deployment-uuid',
'saved_outputs' => new Collection($savedOutputs),
'env_railpack_args' => "--env 'RAILPACK_NODE_VERSION=22'",
'force_rebuild' => false,
'addHosts' => '',
'secrets_hash_key' => 'testing-app-key',
] as $property => $value) {
$reflectionProperty = $reflection->getProperty($property);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($job, $value);
}
return [$job, $reflection];
}
function invokeRailpackMethod(object $job, ReflectionClass $reflection, string $method, array $arguments = []): mixed
{
$reflectionMethod = $reflection->getMethod($method);
$reflectionMethod->setAccessible(true);
return $reflectionMethod->invokeArgs($job, $arguments);
}
it('deep merges repository railpack config with coolify overrides', function () {
$repositoryConfigJson = json_encode([
'$schema' => 'https://schema.railpack.com',
'packages' => [
'node' => '20',
],
'steps' => [
'build' => [
'inputs' => [['step' => 'install']],
'commands' => ['npm run build'],
],
],
'deploy' => [
'variables' => [
'NODE_ENV' => 'production',
],
'startCommand' => 'node index.js',
],
], JSON_THROW_ON_ERROR);
[$job, $reflection] = makeRailpackDeploymentJob(
[
'install_command' => 'npm ci',
'build_command' => 'npm run build:prod',
'start_command' => 'node server.js',
],
[
'railpack_config_exists' => 'exists',
'railpack_repository_config' => $repositoryConfigJson,
],
);
$repositoryConfig = invokeRailpackMethod(
$job,
$reflection,
'decode_railpack_config',
[$repositoryConfigJson, 'repository railpack.json'],
);
$overrides = [
'deploy' => [
'variables' => [
'APP_ENV' => 'production',
],
],
'packages' => [
'python' => '3.13',
],
];
$generatedConfig = invokeRailpackMethod($job, $reflection, 'merge_railpack_config', [$repositoryConfig, $overrides]);
expect($generatedConfig)->toMatchArray([
'$schema' => 'https://schema.railpack.com',
'packages' => [
'node' => '20',
'python' => '3.13',
],
'steps' => [
'build' => [
'inputs' => [['step' => 'install']],
'commands' => ['npm run build'],
],
],
'deploy' => [
'variables' => [
'NODE_ENV' => 'production',
'APP_ENV' => 'production',
],
'startCommand' => 'node index.js',
],
]);
});
it('writes a generated railpack config file when repository config exists', function () {
[$job, $reflection] = makeRailpackDeploymentJob(
['build_command' => 'npm run build'],
[
'railpack_config_exists' => 'exists',
'railpack_repository_config' => json_encode([
'$schema' => 'https://schema.railpack.com',
'steps' => [
'build' => [
'commands' => ['npm run build'],
],
],
], JSON_THROW_ON_ERROR),
],
);
$configPath = invokeRailpackMethod($job, $reflection, 'generate_railpack_config_file');
expect($configPath)->toBe('.coolify/railpack.generated.json');
expect($job->recordedCommands)->toHaveCount(3);
});
it('does not generate a railpack config file for command overrides alone', function () {
[$job, $reflection] = makeRailpackDeploymentJob([
'install_command' => 'npm ci',
'build_command' => 'npm run build',
'start_command' => 'node server.js',
]);
$configPath = invokeRailpackMethod($job, $reflection, 'generate_railpack_config_file');
expect($configPath)->toBeNull();
expect($job->recordedCommands)->toHaveCount(1);
});
it('fails fast when repository railpack config is invalid json', function () {
[$job, $reflection] = makeRailpackDeploymentJob(
['build_command' => 'npm run build'],
[
'railpack_config_exists' => 'exists',
'railpack_repository_config' => '{"steps":{"build":',
],
);
expect(fn () => invokeRailpackMethod($job, $reflection, 'generate_railpack_config_file'))
->toThrow(DeploymentException::class, 'Invalid repository railpack.json');
});
it('builds railpack prepare command using railpack env for install and cli flags for build/start overrides', function () {
[$job, $reflection] = makeRailpackDeploymentJob(
[
'install_command' => 'npm ci',
'build_command' => 'npm run build',
'start_command' => 'node server.js',
],
);
$envRailpackArgsProperty = $reflection->getProperty('env_railpack_args');
$envRailpackArgsProperty->setAccessible(true);
$envRailpackArgsProperty->setValue($job, "--env 'RAILPACK_NODE_VERSION=22' --env 'RAILPACK_INSTALL_CMD=npm ci'");
$command = invokeRailpackMethod(
$job,
$reflection,
'railpack_prepare_command',
['.coolify/railpack.generated.json'],
);
expect($command)->toContain('railpack prepare');
expect($command)->toContain("--env 'RAILPACK_NODE_VERSION=22'");
expect($command)->toContain("--env 'RAILPACK_INSTALL_CMD=npm ci'");
expect($command)->toContain('--build-cmd '.escapeshellarg('npm run build'));
expect($command)->toContain('--start-cmd '.escapeshellarg('node server.js'));
expect($command)->toContain('--config-file '.escapeshellarg('.coolify/railpack.generated.json'));
expect($command)->toContain('--plan-out /artifacts/railpack-plan.json /artifacts/test-app');
expect($command)->not->toContain("--env 'RAILPACK_BUILD_CMD=");
expect($command)->not->toContain("--env 'RAILPACK_START_CMD=");
expect($command)->not->toContain('RAILPACK_BUILD_CMD=');
expect($command)->not->toContain('RAILPACK_START_CMD=');
});
it('fails fast when docker buildx is unavailable for railpack builds', function () {
[$job, $reflection] = makeRailpackDeploymentJob();
$dockerBuildxAvailableProperty = $reflection->getProperty('dockerBuildxAvailable');
$dockerBuildxAvailableProperty->setAccessible(true);
$dockerBuildxAvailableProperty->setValue($job, false);
expect(fn () => invokeRailpackMethod($job, $reflection, 'ensure_docker_buildx_available_for_railpack'))
->toThrow(DeploymentException::class, 'Railpack deployments require the Docker buildx CLI plugin');
});
it('builds railpack docker command with matching env and secret flags for all railpack variables', function () {
[$job, $reflection] = makeRailpackDeploymentJob([
'uuid' => 'application-uuid',
]);
$command = invokeRailpackMethod(
$job,
$reflection,
'railpack_build_command',
[
'coollabsio/coolify:test',
collect([
'RAILPACK_NODE_VERSION' => '22',
'RAILPACK_INSTALL_CMD' => 'npm ci && npm run postinstall',
'RAILPACK_DEPLOY_APT_PACKAGES' => 'curl wget',
'SECRET_JSON' => '{"token":"abc"}',
]),
],
);
expect($command)->toContain("env 'RAILPACK_NODE_VERSION=22'");
expect($command)->toContain("'RAILPACK_INSTALL_CMD=npm ci && npm run postinstall'");
expect($command)->toContain("'RAILPACK_DEPLOY_APT_PACKAGES=curl wget'");
expect($command)->toContain("'SECRET_JSON={\"token\":\"abc\"}'");
expect($command)->toContain("--secret 'id=RAILPACK_NODE_VERSION,env=RAILPACK_NODE_VERSION'");
expect($command)->toContain("--secret 'id=RAILPACK_INSTALL_CMD,env=RAILPACK_INSTALL_CMD'");
expect($command)->toContain("--secret 'id=RAILPACK_DEPLOY_APT_PACKAGES,env=RAILPACK_DEPLOY_APT_PACKAGES'");
expect($command)->toContain("--secret 'id=SECRET_JSON,env=SECRET_JSON'");
expect($command)->toContain(' --build-arg secrets-hash=');
expect($command)->toContain('--build-arg BUILDKIT_SYNTAX="ghcr.io/railwayapp/railpack-frontend:v'.config('constants.coolify.railpack_version').'"');
});
@@ -0,0 +1,267 @@
<?php
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use App\Models\EnvironmentVariable;
use App\Models\Server;
it('generates escaped railpack env args from resolved values and includes install command', function () {
$application = Mockery::mock(Application::class);
$application->shouldReceive('getAttribute')->with('install_command')->andReturn('npm ci && npm run postinstall');
$nodeVersion = Mockery::mock(EnvironmentVariable::class)->makePartial();
$nodeVersion->forceFill([
'key' => 'RAILPACK_NODE_VERSION',
'is_literal' => false,
'is_multiline' => false,
]);
$nodeVersion->shouldReceive('getResolvedValueWithServer')->once()->with(Mockery::type(Server::class))->andReturn('22');
$literalValue = Mockery::mock(EnvironmentVariable::class)->makePartial();
$literalValue->forceFill([
'key' => 'RAILPACK_CUSTOM_FLAG',
'is_literal' => true,
'is_multiline' => false,
]);
$literalValue->shouldReceive('getResolvedValueWithServer')->once()->with(Mockery::type(Server::class))->andReturn("'hello world'");
$jsonValue = Mockery::mock(EnvironmentVariable::class)->makePartial();
$jsonValue->forceFill([
'key' => 'RAILPACK_JSON',
'is_literal' => false,
'is_multiline' => false,
]);
$jsonValue->shouldReceive('getResolvedValueWithServer')->once()->with(Mockery::type(Server::class))->andReturn('{"token":"abc"}');
$nullValue = Mockery::mock(EnvironmentVariable::class)->makePartial();
$nullValue->forceFill([
'key' => 'RAILPACK_NULL',
'is_literal' => false,
'is_multiline' => false,
]);
$nullValue->shouldReceive('getResolvedValueWithServer')->once()->with(Mockery::type(Server::class))->andReturn(null);
$envQuery = Mockery::mock();
$envQuery->shouldReceive('withoutBuildpackControlVariables')->once()->andReturnSelf();
$envQuery->shouldReceive('where')->with('is_buildtime', true)->once()->andReturnSelf();
$envQuery->shouldReceive('get')->once()->andReturn(collect([]));
$application->shouldReceive('environment_variables')->once()->andReturn($envQuery);
$railpackQuery = Mockery::mock();
$railpackQuery->shouldReceive('get')->once()->andReturn(collect([$nodeVersion, $literalValue, $jsonValue, $nullValue]));
$application->shouldReceive('railpack_environment_variables')->once()->andReturn($railpackQuery);
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$job->shouldReceive('generate_coolify_env_variables')->andReturn(collect([]));
$reflection = new ReflectionClass(ApplicationDeploymentJob::class);
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $application);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 0);
$mainServerProperty = $reflection->getProperty('mainServer');
$mainServerProperty->setAccessible(true);
$mainServerProperty->setValue($job, Mockery::mock(Server::class));
$method = $reflection->getMethod('generate_railpack_env_variables');
$method->setAccessible(true);
$variables = $method->invoke($job);
$envArgsProperty = $reflection->getProperty('env_railpack_args');
$envArgsProperty->setAccessible(true);
$envArgs = $envArgsProperty->getValue($job);
expect($variables->all())->toBe([
'RAILPACK_NODE_VERSION' => '22',
'RAILPACK_CUSTOM_FLAG' => 'hello world',
'RAILPACK_JSON' => '{"token":"abc"}',
'RAILPACK_INSTALL_CMD' => 'npm ci && npm run postinstall',
'RAILPACK_DEPLOY_APT_PACKAGES' => 'curl wget',
]);
expect($envArgs)->toContain("--env 'RAILPACK_NODE_VERSION=22'");
expect($envArgs)->toContain("--env 'RAILPACK_CUSTOM_FLAG=hello world'");
expect($envArgs)->toContain("--env 'RAILPACK_JSON={\"token\":\"abc\"}'");
expect($envArgs)->toContain("--env 'RAILPACK_INSTALL_CMD=npm ci && npm run postinstall'");
expect($envArgs)->toContain("--env 'RAILPACK_DEPLOY_APT_PACKAGES=curl wget'");
expect($envArgs)->not->toContain('RAILPACK_NULL');
});
it('uses preview railpack environment variables for preview deployments', function () {
$application = Mockery::mock(Application::class);
$application->shouldReceive('getAttribute')->with('install_command')->andReturn(null);
$previewValue = Mockery::mock(EnvironmentVariable::class)->makePartial();
$previewValue->forceFill([
'key' => 'RAILPACK_PREVIEW_ONLY',
'is_literal' => false,
'is_multiline' => false,
]);
$previewValue->shouldReceive('getResolvedValueWithServer')->once()->with(Mockery::type(Server::class))->andReturn('preview-value');
$previewQuery = Mockery::mock();
$previewQuery->shouldReceive('withoutBuildpackControlVariables')->once()->andReturnSelf();
$previewQuery->shouldReceive('where')->with('is_buildtime', true)->once()->andReturnSelf();
$previewQuery->shouldReceive('get')->once()->andReturn(collect([]));
$application->shouldReceive('environment_variables_preview')->once()->andReturn($previewQuery);
$railpackPreviewQuery = Mockery::mock();
$railpackPreviewQuery->shouldReceive('get')->once()->andReturn(collect([$previewValue]));
$application->shouldReceive('railpack_environment_variables_preview')->once()->andReturn($railpackPreviewQuery);
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$job->shouldReceive('generate_coolify_env_variables')->andReturn(collect([]));
$reflection = new ReflectionClass(ApplicationDeploymentJob::class);
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $application);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 42);
$mainServerProperty = $reflection->getProperty('mainServer');
$mainServerProperty->setAccessible(true);
$mainServerProperty->setValue($job, Mockery::mock(Server::class));
$method = $reflection->getMethod('generate_railpack_env_variables');
$method->setAccessible(true);
$variables = $method->invoke($job);
expect($variables->all())->toBe([
'RAILPACK_PREVIEW_ONLY' => 'preview-value',
'RAILPACK_DEPLOY_APT_PACKAGES' => 'curl wget',
]);
});
it('merges coolify env variables into railpack build variables', function () {
$application = Mockery::mock(Application::class);
$application->shouldReceive('getAttribute')->with('install_command')->andReturn(null);
$userVar = Mockery::mock(EnvironmentVariable::class)->makePartial();
$userVar->forceFill([
'key' => 'MY_BUILD_VAR',
'is_literal' => false,
'is_multiline' => false,
]);
$userVar->shouldReceive('getResolvedValueWithServer')->once()->with(Mockery::type(Server::class))->andReturn('hello');
$envQuery = Mockery::mock();
$envQuery->shouldReceive('withoutBuildpackControlVariables')->once()->andReturnSelf();
$envQuery->shouldReceive('where')->with('is_buildtime', true)->once()->andReturnSelf();
$envQuery->shouldReceive('get')->once()->andReturn(collect([$userVar]));
$application->shouldReceive('environment_variables')->once()->andReturn($envQuery);
$railpackQuery = Mockery::mock();
$railpackQuery->shouldReceive('get')->once()->andReturn(collect([]));
$application->shouldReceive('railpack_environment_variables')->once()->andReturn($railpackQuery);
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$job->shouldReceive('generate_coolify_env_variables')
->with(true)
->andReturn(collect([
'COOLIFY_URL' => 'https://app.example.com',
'COOLIFY_FQDN' => 'app.example.com',
'COOLIFY_BRANCH' => 'main',
'COOLIFY_RESOURCE_UUID' => 'app-uuid',
'SOURCE_COMMIT' => 'abc123',
'EMPTY_VAR' => '',
'NULL_VAR' => null,
]));
$reflection = new ReflectionClass(ApplicationDeploymentJob::class);
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $application);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 0);
$mainServerProperty = $reflection->getProperty('mainServer');
$mainServerProperty->setAccessible(true);
$mainServerProperty->setValue($job, Mockery::mock(Server::class));
$method = $reflection->getMethod('generate_railpack_env_variables');
$method->setAccessible(true);
$variables = $method->invoke($job);
expect($variables->all())->toBe([
'MY_BUILD_VAR' => 'hello',
'RAILPACK_DEPLOY_APT_PACKAGES' => 'curl wget',
'COOLIFY_URL' => 'https://app.example.com',
'COOLIFY_FQDN' => 'app.example.com',
'COOLIFY_BRANCH' => 'main',
'COOLIFY_RESOURCE_UUID' => 'app-uuid',
'SOURCE_COMMIT' => 'abc123',
]);
$envArgsProperty = $reflection->getProperty('env_railpack_args');
$envArgsProperty->setAccessible(true);
$envArgs = $envArgsProperty->getValue($job);
expect($envArgs)->toContain("--env 'COOLIFY_URL=https://app.example.com'");
expect($envArgs)->toContain("--env 'SOURCE_COMMIT=abc123'");
expect($envArgs)->toContain("--env 'RAILPACK_DEPLOY_APT_PACKAGES=curl wget'");
expect($envArgs)->not->toContain('EMPTY_VAR');
expect($envArgs)->not->toContain('NULL_VAR');
});
it('preserves user railpack deploy apt packages while adding healthcheck tools once', function () {
$application = Mockery::mock(Application::class);
$application->shouldReceive('getAttribute')->with('install_command')->andReturn(null);
$deployPackages = Mockery::mock(EnvironmentVariable::class)->makePartial();
$deployPackages->forceFill([
'key' => 'RAILPACK_DEPLOY_APT_PACKAGES',
'is_literal' => false,
'is_multiline' => false,
]);
$deployPackages->shouldReceive('getResolvedValueWithServer')->once()->with(Mockery::type(Server::class))->andReturn('ffmpeg curl');
$envQuery = Mockery::mock();
$envQuery->shouldReceive('withoutBuildpackControlVariables')->once()->andReturnSelf();
$envQuery->shouldReceive('where')->with('is_buildtime', true)->once()->andReturnSelf();
$envQuery->shouldReceive('get')->once()->andReturn(collect([]));
$application->shouldReceive('environment_variables')->once()->andReturn($envQuery);
$railpackQuery = Mockery::mock();
$railpackQuery->shouldReceive('get')->once()->andReturn(collect([$deployPackages]));
$application->shouldReceive('railpack_environment_variables')->once()->andReturn($railpackQuery);
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$job->shouldReceive('generate_coolify_env_variables')->andReturn(collect([]));
$reflection = new ReflectionClass(ApplicationDeploymentJob::class);
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $application);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 0);
$mainServerProperty = $reflection->getProperty('mainServer');
$mainServerProperty->setAccessible(true);
$mainServerProperty->setValue($job, Mockery::mock(Server::class));
$method = $reflection->getMethod('generate_railpack_env_variables');
$method->setAccessible(true);
$variables = $method->invoke($job);
expect($variables->get('RAILPACK_DEPLOY_APT_PACKAGES'))->toBe('ffmpeg curl wget');
$envArgsProperty = $reflection->getProperty('env_railpack_args');
$envArgsProperty->setAccessible(true);
$envArgs = $envArgsProperty->getValue($job);
expect($envArgs)->toContain("--env 'RAILPACK_DEPLOY_APT_PACKAGES=ffmpeg curl wget'");
});
@@ -0,0 +1,87 @@
<?php
use App\Support\ValidationPatterns;
// ── databasePasswordRules ─────────────────────────────────────────────────────
it('databasePasswordRules includes regex rule by default', function () {
$rules = ValidationPatterns::databasePasswordRules();
$regexRules = array_filter($rules, fn ($rule) => str_starts_with($rule, 'regex:'));
expect($regexRules)->not->toBeEmpty();
});
it('databasePasswordRules includes regex rule when enforcePattern true', function () {
$rules = ValidationPatterns::databasePasswordRules(enforcePattern: true);
$regexRules = array_filter($rules, fn ($rule) => str_starts_with($rule, 'regex:'));
expect($regexRules)->not->toBeEmpty();
});
it('databasePasswordRules omits regex rule when enforcePattern false', function () {
$rules = ValidationPatterns::databasePasswordRules(enforcePattern: false);
$regexRules = array_filter($rules, fn ($rule) => str_starts_with($rule, 'regex:'));
expect($regexRules)->toBeEmpty();
});
it('databasePasswordRules keeps required, string, min and max when enforcePattern false', function () {
$rules = ValidationPatterns::databasePasswordRules(required: true, minLength: 1, maxLength: 128, enforcePattern: false);
expect($rules)->toContain('required');
expect($rules)->toContain('string');
expect($rules)->toContain('min:1');
expect($rules)->toContain('max:128');
});
it('databasePasswordRules keeps nullable and bounds when not required and enforcePattern false', function () {
$rules = ValidationPatterns::databasePasswordRules(required: false, minLength: 2, maxLength: 64, enforcePattern: false);
expect($rules)->toContain('nullable');
expect($rules)->toContain('string');
expect($rules)->toContain('min:2');
expect($rules)->toContain('max:64');
expect(array_filter($rules, fn ($rule) => str_starts_with($rule, 'regex:')))->toBeEmpty();
});
// ── databaseIdentifierRules ───────────────────────────────────────────────────
it('databaseIdentifierRules includes regex rule by default', function () {
$rules = ValidationPatterns::databaseIdentifierRules();
$regexRules = array_filter($rules, fn ($rule) => str_starts_with($rule, 'regex:'));
expect($regexRules)->not->toBeEmpty();
});
it('databaseIdentifierRules includes regex rule when enforcePattern true', function () {
$rules = ValidationPatterns::databaseIdentifierRules(enforcePattern: true);
$regexRules = array_filter($rules, fn ($rule) => str_starts_with($rule, 'regex:'));
expect($regexRules)->not->toBeEmpty();
});
it('databaseIdentifierRules omits regex rule when enforcePattern false', function () {
$rules = ValidationPatterns::databaseIdentifierRules(enforcePattern: false);
$regexRules = array_filter($rules, fn ($rule) => str_starts_with($rule, 'regex:'));
expect($regexRules)->toBeEmpty();
});
it('databaseIdentifierRules keeps required, string, min and max when enforcePattern false', function () {
$rules = ValidationPatterns::databaseIdentifierRules(required: true, minLength: 1, maxLength: 63, enforcePattern: false);
expect($rules)->toContain('required');
expect($rules)->toContain('string');
expect($rules)->toContain('min:1');
expect($rules)->toContain('max:63');
});
it('databaseIdentifierRules keeps nullable and bounds when not required and enforcePattern false', function () {
$rules = ValidationPatterns::databaseIdentifierRules(required: false, minLength: 1, maxLength: 30, enforcePattern: false);
expect($rules)->toContain('nullable');
expect($rules)->toContain('string');
expect($rules)->toContain('min:1');
expect($rules)->toContain('max:30');
expect(array_filter($rules, fn ($rule) => str_starts_with($rule, 'regex:')))->toBeEmpty();
});
@@ -0,0 +1,176 @@
<?php
use App\Support\ValidationPatterns;
use Illuminate\Support\Facades\Validator;
// ── DB_IDENTIFIER_PATTERN ─────────────────────────────────────────────────────
it('DB_IDENTIFIER_PATTERN accepts valid SQL identifiers', function (string $id) {
expect(preg_match(ValidationPatterns::DB_IDENTIFIER_PATTERN, $id))->toBe(1);
})->with([
'simple lowercase' => 'postgres',
'underscore prefix' => '_admin',
'mixed case' => 'MyDatabase',
'alphanumeric' => 'App_DB_1',
'single char' => 'a',
'all caps' => 'ROOT',
'numbers in middle' => 'db2user',
]);
it('DB_IDENTIFIER_PATTERN rejects shell-dangerous and invalid identifiers', function (string $id) {
expect(preg_match(ValidationPatterns::DB_IDENTIFIER_PATTERN, $id))->toBe(0);
})->with([
'semicolon' => 'user;id',
'pipe' => 'user|cat',
'ampersand' => 'user&rm',
'dollar sign' => 'user$x',
'backtick' => 'user`id`',
'subshell' => 'user$(id)',
'space' => 'user name',
'newline' => "user\nname",
'single quote' => "user'name",
'double quote' => 'user"name',
'backslash' => 'user\\name',
'less than' => 'user<name',
'greater than' => 'user>name',
'leading digit' => '1user',
'hyphen' => 'my-user',
'dot' => 'my.user',
'empty' => '',
'64 chars (over limit)' => str_repeat('a', 64),
'advisory poc payload' => 'root; touch /tmp/pwned_rce; #',
'subshell payload' => 'a$(touch /tmp/pwn)b',
]);
// ── DB_PASSWORD_PATTERN ───────────────────────────────────────────────────────
it('DB_PASSWORD_PATTERN accepts strong passwords without shell-dangerous chars', function (string $pw) {
expect(preg_match(ValidationPatterns::DB_PASSWORD_PATTERN, $pw))->toBe(1);
})->with([
'alphanumeric' => 'SecurePass123',
'with special safe chars' => 'P@ss!word#1',
'with brackets' => 'P{a}ss[word]',
'with slash' => 'Pass/word1',
'with dot comma' => 'Pass.word,1',
'with hyphen' => 'Pass-word1',
'with plus equals' => 'Pass+word=1',
'with tilde colon' => 'P~ass:word1',
'complex strong' => 'Str0ng!P@ss#word^123',
]);
it('DB_PASSWORD_PATTERN rejects shell-dangerous characters', function (string $pw) {
expect(preg_match(ValidationPatterns::DB_PASSWORD_PATTERN, $pw))->toBe(0);
})->with([
'backtick' => 'pass`word`',
'dollar sign' => 'pass$word',
'semicolon' => 'pass;word',
'pipe' => 'pass|word',
'ampersand' => 'pass&word',
'less than' => 'pass<word',
'greater than' => 'pass>word',
'backslash' => 'pass\\word',
'single quote' => "pass'word",
'double quote' => 'pass"word',
'space' => 'pass word',
'newline' => "pass\nword",
'carriage return' => "pass\rword",
'tab' => "pass\tword",
'empty' => '',
'command substitution' => '$(whoami)',
'rce payload' => 'root; touch /tmp/pwned; #',
]);
// ── Rule helpers ──────────────────────────────────────────────────────────────
it('databaseIdentifierRules returns required by default', function () {
$rules = ValidationPatterns::databaseIdentifierRules();
expect($rules)->toContain('required')
->toContain('string')
->toContain('min:1')
->toContain('max:63')
->toContain('regex:'.ValidationPatterns::DB_IDENTIFIER_PATTERN);
});
it('databaseIdentifierRules returns nullable when not required', function () {
$rules = ValidationPatterns::databaseIdentifierRules(required: false);
expect($rules)->toContain('nullable')
->not->toContain('required');
});
it('databasePasswordRules returns required by default', function () {
$rules = ValidationPatterns::databasePasswordRules();
expect($rules)->toContain('required')
->toContain('string')
->toContain('min:1')
->toContain('max:128')
->toContain('regex:'.ValidationPatterns::DB_PASSWORD_PATTERN);
});
it('databasePasswordRules returns nullable when not required', function () {
$rules = ValidationPatterns::databasePasswordRules(required: false);
expect($rules)->toContain('nullable')
->not->toContain('required');
});
it('isValidDatabaseIdentifier returns true for valid identifier', function () {
expect(ValidationPatterns::isValidDatabaseIdentifier('postgres'))->toBeTrue();
expect(ValidationPatterns::isValidDatabaseIdentifier('_admin'))->toBeTrue();
expect(ValidationPatterns::isValidDatabaseIdentifier('DB_1'))->toBeTrue();
});
it('isValidDatabaseIdentifier returns false for injection payloads', function () {
expect(ValidationPatterns::isValidDatabaseIdentifier('user; id'))->toBeFalse();
expect(ValidationPatterns::isValidDatabaseIdentifier('user$(whoami)'))->toBeFalse();
expect(ValidationPatterns::isValidDatabaseIdentifier(''))->toBeFalse();
});
// ── Validator integration ─────────────────────────────────────────────────────
it('Laravel Validator rejects advisory PoC postgres_user payload', function () {
$validator = Validator::make(
['postgres_user' => 'root; touch /tmp/pwned_rce; #'],
['postgres_user' => ValidationPatterns::databaseIdentifierRules()]
);
expect($validator->fails())->toBeTrue();
});
it('Laravel Validator rejects subshell injection in postgres_user', function () {
$validator = Validator::make(
['postgres_user' => 'a$(touch /tmp/pwn)b'],
['postgres_user' => ValidationPatterns::databaseIdentifierRules()]
);
expect($validator->fails())->toBeTrue();
});
it('Laravel Validator accepts clean postgres_user', function () {
$validator = Validator::make(
['postgres_user' => 'postgres'],
['postgres_user' => ValidationPatterns::databaseIdentifierRules()]
);
expect($validator->fails())->toBeFalse();
});
it('Laravel Validator rejects shell metachar in password', function () {
$validator = Validator::make(
['postgres_password' => 'pass$(id)word'],
['postgres_password' => ValidationPatterns::databasePasswordRules()]
);
expect($validator->fails())->toBeTrue();
});
it('Laravel Validator accepts safe password', function () {
$validator = Validator::make(
['postgres_password' => 'Str0ng!P@ss#123'],
['postgres_password' => ValidationPatterns::databasePasswordRules()]
);
expect($validator->fails())->toBeFalse();
});
@@ -0,0 +1,107 @@
<?php
/**
* Regression tests for database healthcheck command injection.
*
* Docker CMD-SHELL healthchecks pass the string to /bin/sh -c, enabling command injection
* via user-controlled DB username/password/database fields. The fix converts all affected
* healthchecks to CMD exec-form arrays, which bypass the shell entirely.
*/
dataset('malicious_db_inputs', [
'semicolon separator' => ['admin; id > /tmp/pwned; echo'],
'command substitution $()' => ['admin$(id > /tmp/pwned)'],
'backtick substitution' => ['admin`id > /tmp/pwned`'],
'pipe operator' => ['admin | cat /etc/passwd'],
'background operator' => ['admin & curl http://evil.com'],
'output redirect' => ['admin > /tmp/evil.txt'],
'newline injection' => ["admin\nid"],
'null byte' => ["admin\0id"],
]);
// ─── PostgreSQL ──────────────────────────────────────────────────────────────
test('postgresql healthcheck uses CMD exec-form, not CMD-SHELL', function () {
$source = file_get_contents(__DIR__.'/../../app/Actions/Database/StartPostgresql.php');
expect($source)->not->toContain('CMD-SHELL');
expect($source)->toContain("'CMD', 'psql'");
});
test('postgresql healthcheck exec-form array is injection-safe regardless of input', function (string $malicious) {
// Simulate what StartPostgresql now generates
$healthcheck = ['CMD', 'psql', '-U', $malicious, '-d', $malicious, '-c', 'SELECT 1'];
expect($healthcheck[0])->toBe('CMD');
expect($healthcheck[0])->not->toBe('CMD-SHELL');
// Malicious value is isolated as a single argv element — no shell interprets it
expect($healthcheck)->toContain($malicious);
expect(is_array($healthcheck))->toBeTrue();
})->with('malicious_db_inputs');
// ─── KeyDB ────────────────────────────────────────────────────────────────────
test('keydb healthcheck uses CMD exec-form, not a CMD-SHELL string', function () {
$source = file_get_contents(__DIR__.'/../../app/Actions/Database/StartKeydb.php');
expect($source)->not->toContain('CMD-SHELL');
expect($source)->toContain("'CMD', 'keydb-cli'");
});
test('keydb healthcheck exec-form array is injection-safe regardless of input', function (string $malicious) {
$healthcheck = ['CMD', 'keydb-cli', '--pass', $malicious, 'ping'];
expect($healthcheck[0])->toBe('CMD');
expect($healthcheck)->toContain($malicious);
expect(is_array($healthcheck))->toBeTrue();
})->with('malicious_db_inputs');
// ─── Dragonfly ────────────────────────────────────────────────────────────────
test('dragonfly healthcheck uses CMD exec-form, not a CMD-SHELL string', function () {
$source = file_get_contents(__DIR__.'/../../app/Actions/Database/StartDragonfly.php');
expect($source)->not->toContain('CMD-SHELL');
expect($source)->toContain("'CMD', 'redis-cli'");
});
test('dragonfly healthcheck exec-form array is injection-safe regardless of input', function (string $malicious) {
$healthcheck = ['CMD', 'redis-cli', '-a', $malicious, 'ping'];
expect($healthcheck[0])->toBe('CMD');
expect($healthcheck)->toContain($malicious);
expect(is_array($healthcheck))->toBeTrue();
})->with('malicious_db_inputs');
// ─── ClickHouse ───────────────────────────────────────────────────────────────
test('clickhouse healthcheck uses CMD exec-form, not a CMD-SHELL string', function () {
$source = file_get_contents(__DIR__.'/../../app/Actions/Database/StartClickhouse.php');
expect($source)->not->toContain('CMD-SHELL');
expect($source)->toContain("'CMD', 'clickhouse-client'");
});
test('clickhouse healthcheck exec-form array is injection-safe regardless of input', function (string $malicious) {
$healthcheck = ['CMD', 'clickhouse-client', '--user', $malicious, '--password', $malicious, '--query', 'SELECT 1'];
expect($healthcheck[0])->toBe('CMD');
expect($healthcheck)->toContain($malicious);
expect(is_array($healthcheck))->toBeTrue();
})->with('malicious_db_inputs');
// ─── Verify unaffected databases still use their safe patterns ────────────────
test('mysql healthcheck already uses CMD exec-form (no regression)', function () {
$source = file_get_contents(__DIR__.'/../../app/Actions/Database/StartMysql.php');
// MySQL already used CMD array form — ensure it stays that way
expect($source)->toContain("'CMD', 'mysqladmin'");
});
test('mariadb healthcheck uses safe fixed script (no regression)', function () {
$source = file_get_contents(__DIR__.'/../../app/Actions/Database/StartMariadb.php');
expect($source)->toContain('healthcheck.sh');
// Must not have gained any user-field interpolation
expect($source)->not->toMatch('/CMD-SHELL.*mariadb/i');
});
@@ -0,0 +1,170 @@
<?php
/**
* GHSA-rcch-8c74-7f29 — Sink-side escaping tests
*
* Verifies that credentials reaching shell commands are properly escaped
* even if validation is bypassed (e.g. legacy rows, direct DB writes).
*/
// ── executeInDocker + escapeshellarg chown pattern ────────────────────────────
it('escapeshellarg wraps postgres_user in single quotes for chown command', function () {
$user = 'postgres';
$escaped = escapeshellarg($user);
$cmd = executeInDocker('abc123', "chown {$escaped}:{$escaped} /var/lib/postgresql/certs/server.key");
// executeInDocker embeds the command inside bash -c '...', escaping inner single quotes as '\''
// so escapeshellarg('postgres') = 'postgres' becomes '\''postgres'\'' in the outer shell string
expect($cmd)->toContain('bash -c')
->toContain('postgres')
->toContain('chown');
});
it('advisory PoC postgres_user payload is contained by escapeshellarg in chown command', function () {
// Simulates a legacy row that bypassed validation
$maliciousUser = 'root; touch /tmp/pwned_rce; #';
$escaped = escapeshellarg($maliciousUser);
// escapeshellarg must wrap the entire payload in single quotes
// (semicolons inside single-quoted args are NOT shell metacharacters)
expect($escaped)->toBe("'root; touch /tmp/pwned_rce; #'");
$cmd = executeInDocker('abc123', "chown {$escaped}:{$escaped} /var/lib/postgresql/certs/server.key");
// The cmd contains the payload, but ONLY inside single-quoted segments — cannot break out.
// Verify the chown arg is never an unquoted bare ; — the payload is inside '...'
// The outer executeInDocker further escapes any single-quote chars for the host shell.
expect($cmd)->toContain('docker exec abc123 bash -c');
// Before fix: chown root; touch /tmp/pwned_rce; # ... (breaks out of chown, executes touch)
// After fix: chown 'root; touch /tmp/pwned_rce; #':'...' ... (literal arg to chown)
// The unescaped sequence "chown root;" must NOT appear.
expect($cmd)->not->toContain('chown root;');
});
it('subshell payload in mysql_user is contained by escapeshellarg in chown command', function () {
$maliciousUser = 'a$(touch /tmp/pwn)b';
$escaped = escapeshellarg($maliciousUser);
$cmd = executeInDocker('abc123', "chown {$escaped}:{$escaped} /etc/mysql/certs/server.crt");
// escapeshellarg wraps in single quotes — $() is not expanded inside single quotes
expect($escaped)->toBe("'a\$(touch /tmp/pwn)b'");
// The cmd must not contain an unquoted $( sequence — it must be inside single quotes
// If the sequence appears at all, it must be single-quoted (the quote precedes it).
expect($cmd)->not->toContain(' $(touch');
});
it('subshell payload in postgres_user is contained by escapeshellarg in chown command', function () {
$maliciousUser = 'a$(touch /tmp/pwn_postgres)b';
$escaped = escapeshellarg($maliciousUser);
$cmd = executeInDocker('abc123', "chown {$escaped}:{$escaped} /var/lib/postgresql/certs/server.key /var/lib/postgresql/certs/server.crt");
expect($escaped)->toBe("'a\$(touch /tmp/pwn_postgres)b'");
expect($cmd)->not->toContain(' $(touch');
});
it('semicolon payload in postgres_user is contained by escapeshellarg in chown command', function () {
$maliciousUser = 'root; touch /tmp/pwned_pg; #';
$escaped = escapeshellarg($maliciousUser);
$cmd = executeInDocker('abc123', "chown {$escaped}:{$escaped} /var/lib/postgresql/certs/server.key /var/lib/postgresql/certs/server.crt");
expect($escaped)->toBe("'root; touch /tmp/pwned_pg; #'");
expect($cmd)->not->toContain('chown root;');
});
it('backtick payload in mysql_user is contained by escapeshellarg', function () {
$maliciousUser = 'user`id`';
$escaped = escapeshellarg($maliciousUser);
$cmd = executeInDocker('abc123', "chown {$escaped}:{$escaped} /etc/mysql/certs/server.crt");
// escapeshellarg wraps the whole value in single quotes — backticks not expanded inside ''
expect($escaped)->toBe("'user`id`'");
// The unquoted bare backtick sequence `id` must not appear outside single-quoted context.
// Specifically, "chown user`id`" (unquoted) must not appear.
expect($cmd)->not->toContain('chown user`id`');
});
// ── MongoDB JS init script JSON-escaping ──────────────────────────────────────
it('json_encode prevents JS injection in mongo_initdb_database', function () {
$database = 'x"}); db.dropUser("admin"); //';
$dbJson = json_encode($database, JSON_UNESCAPED_SLASHES);
// The double-quotes in the payload MUST be escaped — they cannot close the JS string literal.
// json_encode escapes " as \" so the injected " cannot terminate the surrounding JS string.
expect($dbJson)->toContain('\\"');
// The resulting JSON literal, when embedded in JS, forms a valid quoted string.
// It starts and ends with the outermost " added by json_encode.
expect($dbJson)->toStartWith('"')
->toEndWith('"');
// Verify the injected payload is present but neutralised (the " that would close the JS
// string is now escaped as \", preventing breakout).
expect($dbJson)->toContain('x\\"});');
});
it('json_encode prevents JS injection in mongo_initdb_root_username', function () {
$username = 'admin", pwd: "", roles: [{role:"root", db:"admin"}]}); //';
$userJson = json_encode($username, JSON_UNESCAPED_SLASHES);
$content = 'db.createUser({user: '.$userJson.', pwd: "secret", roles: []});';
// The injected " that would close the JS string must be escaped as \"
expect($userJson)->toContain('\\"');
// The raw unescaped sequence admin" (with unescaped quote) must not appear in the JS
expect($content)->not->toContain('admin", pwd');
});
it('json_encode safely encodes a clean mongo username', function () {
$username = 'mongouser';
$userJson = json_encode($username, JSON_UNESCAPED_SLASHES);
expect($userJson)->toBe('"mongouser"');
});
it('json_encode safely encodes a mongo password with special chars', function () {
$password = 'P@ss!#word123';
$pwdJson = json_encode($password, JSON_UNESCAPED_SLASHES);
expect($pwdJson)->toBe('"P@ss!#word123"');
});
// ── Healthcheck CMD exec-form structure (no shell parsing) ────────────────────
it('CMD exec-form healthcheck array does not concatenate user into a shell string', function () {
// The fix uses an array; each element is passed directly as argv — no shell parsing.
// Simulate the post-fix healthcheck array structure.
$user = "admin'; touch /tmp/pwn; #";
$db = 'mydb';
$healthcheck = [
'CMD',
'psql',
'-U',
$user,
'-d',
$db,
'-c',
'SELECT 1',
];
// The array form means each element is argv — no shell involved.
// The malicious user value is passed as a literal argument to psql, which rejects it.
// Key assertion: the test string is NOT collapsed into a shell command string.
expect($healthcheck[3])->toBe($user)
->and($healthcheck[0])->toBe('CMD')
->and(count($healthcheck))->toBe(8);
// Sanity: if we joined with space it would be dangerous — array form avoids this.
$joinedDangerous = implode(' ', $healthcheck);
expect($joinedDangerous)->toContain('; touch /tmp/pwn'); // proof that join IS dangerous
// The array form is what Docker Compose uses — it does NOT join with spaces + sh -c.
// Simply verifying the structure is correct proves shell is not involved.
expect($healthcheck[0])->toBe('CMD');
});
+115
View File
@@ -0,0 +1,115 @@
<?php
use App\Http\Controllers\Webhook\Concerns\DetectsSkipDeployCommits;
$harness = new class
{
use DetectsSkipDeployCommits;
};
$harnessClass = get_class($harness);
describe('shouldSkipDeploy (all-must-match)', function () use ($harnessClass) {
test('returns false when messages array is empty', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeploy([]))->toBeFalse();
});
test('returns false when only nulls or empty strings are provided', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeploy([null, '', null]))->toBeFalse();
});
test('returns true when all messages contain [skip ci]', function () use ($harnessClass) {
$messages = [
'Update docs [skip ci]',
'Fix typo [skip ci]',
];
expect($harnessClass::shouldSkipDeploy($messages))->toBeTrue();
});
test('returns true when single message contains [skip cd]', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeploy(['Update README [skip cd]']))->toBeTrue();
});
test('returns true with mixed [skip ci] and [skip cd] (case-insensitive)', function () use ($harnessClass) {
$messages = [
'Docs [SKIP CI]',
'Changelog [Skip Cd]',
];
expect($harnessClass::shouldSkipDeploy($messages))->toBeTrue();
});
test('returns false when at least one message has no skip marker', function () use ($harnessClass) {
$messages = [
'Update docs [skip ci]',
'Actual feature change',
];
expect($harnessClass::shouldSkipDeploy($messages))->toBeFalse();
});
test('returns false when single message has no skip marker', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeploy(['Deploy this please']))->toBeFalse();
});
test('null entries are filtered before evaluation', function () use ($harnessClass) {
$messages = [
null,
'Docs [skip ci]',
null,
];
expect($harnessClass::shouldSkipDeploy($messages))->toBeTrue();
});
test('matches PR title scenario (single string)', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeploy(['chore: update readme [skip ci]']))->toBeTrue();
expect($harnessClass::shouldSkipDeploy(['feat: real change']))->toBeFalse();
expect($harnessClass::shouldSkipDeploy([null]))->toBeFalse();
});
});
describe('shouldSkipDeployAny (any-marker)', function () use ($harnessClass) {
test('returns false when messages array is empty', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeployAny([]))->toBeFalse();
});
test('returns false when only nulls or empty strings are provided', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeployAny([null, '', null]))->toBeFalse();
});
test('returns true when any one message contains [skip ci]', function () use ($harnessClass) {
$messages = [
'Real feature change',
'docs: update readme [skip ci]',
];
expect($harnessClass::shouldSkipDeployAny($messages))->toBeTrue();
});
test('returns true when any one message contains [skip cd]', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeployAny(['feature change', 'chore [skip cd]']))->toBeTrue();
});
test('returns true case-insensitively', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeployAny(['feat: docs [SKIP CI]']))->toBeTrue();
expect($harnessClass::shouldSkipDeployAny(['feat: docs [Skip Cd]']))->toBeTrue();
});
test('returns false when no message contains a skip marker', function () use ($harnessClass) {
$messages = [
'feat: add new endpoint',
'fix: handle edge case',
];
expect($harnessClass::shouldSkipDeployAny($messages))->toBeFalse();
});
test('null and empty entries are skipped, real markers still match', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeployAny([null, '', 'docs [skip ci]', null]))->toBeTrue();
expect($harnessClass::shouldSkipDeployAny([null, '', null]))->toBeFalse();
});
test('PR title alone with skip marker triggers skip', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeployAny(['chore: update readme [skip ci]']))->toBeTrue();
});
test('PR title without skip marker but commit message with skip marker triggers skip', function () use ($harnessClass) {
expect($harnessClass::shouldSkipDeployAny(['feat: real change', 'wip [skip cd]']))->toBeTrue();
});
});
@@ -0,0 +1,74 @@
<?php
use App\Models\EnvironmentVariable;
use App\Models\SharedEnvironmentVariable;
it('flags NIXPACKS_ keys as buildpack control variables', function () {
$env = new EnvironmentVariable;
$env->key = 'NIXPACKS_NODE_VERSION';
expect($env->is_buildpack_control)->toBeTrue();
});
it('flags RAILPACK_ keys as buildpack control variables', function () {
$env = new EnvironmentVariable;
$env->key = 'RAILPACK_NODE_VERSION';
expect($env->is_buildpack_control)->toBeTrue();
});
it('does not flag user-defined keys as buildpack control variables', function () {
$env = new EnvironmentVariable;
$env->key = 'MY_BUILD_VAR';
expect($env->is_buildpack_control)->toBeFalse();
});
it('does not flag empty key as buildpack control variable', function () {
$env = new EnvironmentVariable;
expect($env->is_buildpack_control)->toBeFalse();
});
it('lists is_buildpack_control in appends and drops legacy is_nixpacks', function () {
$env = new EnvironmentVariable;
expect($env->getAppends())->toContain('is_buildpack_control');
expect($env->getAppends())->not->toContain('is_nixpacks');
});
it('normalizes environment variable keys before storing them on the model', function () {
$env = new EnvironmentVariable;
$env->key = ' node.name ';
expect($env->key)->toBe('node.name');
});
it('allows Docker-compatible environment variable keys on the model', function (string $key) {
$env = new EnvironmentVariable;
$env->key = $key;
expect($env->key)->toBe($key);
})->with([
'starts with digit' => '1BAD',
'hyphen' => 'BAD-KEY',
'dot' => 'node.name',
'uppercase dots' => 'XPACK.SECURITY.ENABLED',
'semicolon' => 'BAD;KEY',
]);
it('rejects environment variable keys Docker cannot represent on the model', function () {
$env = new EnvironmentVariable;
expect(function () use ($env) {
$env->key = 'BAD=KEY';
})->toThrow(InvalidArgumentException::class, 'Docker-compatible');
});
it('rejects shared environment variable keys Docker cannot represent on the model', function () {
$env = new SharedEnvironmentVariable;
expect(function () use ($env) {
$env->key = 'BAD=KEY';
})->toThrow(InvalidArgumentException::class, 'Docker-compatible');
});
+1 -1
View File
@@ -92,7 +92,7 @@ test('file storage accepts paths with underscores and hyphens', function () {
->not->toThrow(Exception::class);
});
// --- Regression tests for GHSA-46hp-7m8g-7622 ---
// --- Regression tests for file mount path validation ---
// These verify that file mount paths (not just directory mounts) are validated,
// and that saveStorageOnServer() validates fs_path before any shell interpolation.
+29
View File
@@ -0,0 +1,29 @@
<?php
test('hex magic variables generate valid hex strings with expected lengths', function (string $command, int $expectedLength) {
$value = generateEnvValue($command);
expect($value)
->toBeString()
->toMatch('/^[0-9a-f]+$/');
expect(strlen($value))->toBe($expectedLength);
})->with([
'HEX_32' => ['HEX_32', 32],
'HEX_64' => ['HEX_64', 64],
'HEX_128' => ['HEX_128', 128],
]);
test('real base64 magic variables generate valid base64 strings from expected byte lengths', function (string $command, int $expectedBytes) {
$value = generateEnvValue($command);
$decodedValue = base64_decode($value, true);
expect($value)->toBeString();
expect($decodedValue)->not->toBeFalse();
expect(strlen($decodedValue))->toBe($expectedBytes);
})->with([
'REALBASE64' => ['REALBASE64', 32],
'REALBASE64_32' => ['REALBASE64_32', 32],
'REALBASE64_64' => ['REALBASE64_64', 64],
'REALBASE64_128' => ['REALBASE64_128', 128],
]);
+1 -1
View File
@@ -4,7 +4,7 @@ use App\Models\Application;
use App\Models\ApplicationSetting;
/**
* Security tests for git ref validation (GHSA-mw5w-2vvh-mgf4).
* Tests for git ref validation.
*
* Ensures that git_commit_sha and related inputs are validated
* to prevent OS command injection via shell metacharacters.
-2
View File
@@ -5,8 +5,6 @@
*
* mt_rand() and rand() are not cryptographically secure. Use random_int()
* or random_bytes() instead for any security-sensitive context.
*
* @see GHSA-33rh-4c9r-74pf
*/
arch('app code must not use mt_rand')
->expect('App')
+61
View File
@@ -0,0 +1,61 @@
<?php
use App\Models\Server;
afterEach(function () {
Mockery::close();
});
function makeServerForReachabilityTest(bool $isReachable, bool $notificationSent, int $unreachableCount): Server
{
$settings = Mockery::mock();
$settings->is_reachable = $isReachable;
$server = Mockery::mock(Server::class)->makePartial()->shouldAllowMockingProtectedMethods();
$server->shouldReceive('refresh')->andReturnSelf();
$server->shouldReceive('getAttribute')->with('settings')->andReturn($settings);
$server->shouldReceive('getAttribute')->with('unreachable_notification_sent')->andReturn($notificationSent);
$server->shouldReceive('getAttribute')->with('unreachable_count')->andReturn($unreachableCount);
return $server;
}
it('sends Reachable notification when reachable and notification was previously sent', function () {
$server = makeServerForReachabilityTest(isReachable: true, notificationSent: true, unreachableCount: 0);
$server->shouldReceive('sendReachableNotification')->once();
$server->shouldNotReceive('sendUnreachableNotification');
$server->isReachableChanged();
});
it('does not send any notification when reachable and notification was never sent', function () {
$server = makeServerForReachabilityTest(isReachable: true, notificationSent: false, unreachableCount: 0);
$server->shouldNotReceive('sendReachableNotification');
$server->shouldNotReceive('sendUnreachableNotification');
$server->isReachableChanged();
});
it('sends Unreachable notification when count >= 2 and not yet notified', function () {
$server = makeServerForReachabilityTest(isReachable: false, notificationSent: false, unreachableCount: 2);
$server->shouldReceive('sendUnreachableNotification')->once();
$server->shouldNotReceive('sendReachableNotification');
$server->isReachableChanged();
});
it('does not send Unreachable notification on first transient failure (count=1)', function () {
$server = makeServerForReachabilityTest(isReachable: false, notificationSent: false, unreachableCount: 1);
$server->shouldNotReceive('sendUnreachableNotification');
$server->shouldNotReceive('sendReachableNotification');
$server->isReachableChanged();
});
it('does not double-send Unreachable when already notified', function () {
$server = makeServerForReachabilityTest(isReachable: false, notificationSent: true, unreachableCount: 5);
$server->shouldNotReceive('sendUnreachableNotification');
$server->shouldNotReceive('sendReachableNotification');
$server->isReachableChanged();
});
@@ -0,0 +1,66 @@
<?php
/**
* Unit tests for LocalFileVolume content size handling.
*
* Related Issue: #4701 - Storages page becomes unusable when Docker volumes
* mount large host files. Coolify previously stored full file content in the
* encrypted `content` mediumText column, then serialized it to the Livewire
* payload, crashing the browser.
*/
use App\Models\LocalFileVolume;
use Tests\TestCase;
uses(TestCase::class);
it('exposes a 5 MiB content size limit', function () {
expect(LocalFileVolume::MAX_CONTENT_SIZE)->toBe(5_242_880);
});
it('exposes binary and too-large placeholder constants', function () {
expect(LocalFileVolume::BINARY_PLACEHOLDER)->toBe('[binary file]');
expect(LocalFileVolume::TOO_LARGE_PLACEHOLDER)->toBe('[file too large to display]');
});
it('flags is_too_large when content matches the placeholder', function () {
$volume = new LocalFileVolume;
$volume->content = LocalFileVolume::TOO_LARGE_PLACEHOLDER;
expect($volume->is_too_large)->toBeTrue();
expect($volume->is_binary)->toBeFalse();
});
it('flags is_binary when content matches the placeholder', function () {
$volume = new LocalFileVolume;
$volume->content = LocalFileVolume::BINARY_PLACEHOLDER;
expect($volume->is_binary)->toBeTrue();
expect($volume->is_too_large)->toBeFalse();
});
it('does not flag normal content as binary or too large', function () {
$volume = new LocalFileVolume;
$volume->content = "hello\nworld\n";
expect($volume->is_binary)->toBeFalse();
expect($volume->is_too_large)->toBeFalse();
});
it('does not flag empty content as binary or too large', function () {
$volume = new LocalFileVolume;
$volume->content = null;
expect($volume->is_binary)->toBeFalse();
expect($volume->is_too_large)->toBeFalse();
});
it('exposes the too-large flag via toArray for Livewire serialization', function () {
$volume = new LocalFileVolume;
$volume->content = LocalFileVolume::TOO_LARGE_PLACEHOLDER;
$array = $volume->toArray();
expect($array)->toHaveKey('is_too_large');
expect($array['is_too_large'])->toBeTrue();
});
+1 -1
View File
@@ -5,7 +5,7 @@ use App\Models\Server;
use App\Models\ServerSetting;
// -------------------------------------------------------------------------
// GHSA-3xm2-hqg8-4m2p: Verify log drain env values are base64-encoded
// Verify log drain env values are base64-encoded
// and never appear raw in shell commands
// -------------------------------------------------------------------------
+85 -1
View File
@@ -6,7 +6,6 @@
* Tests to ensure persistent volume names are validated against command injection
* and that shell commands properly escape volume names.
*
* Related Advisory: GHSA-mh8x-fppq-cp77
* Related Files:
* - app/Models/LocalPersistentVolume.php
* - app/Support/ValidationPatterns.php
@@ -96,3 +95,88 @@ it('generates volumeNameMessages with custom field name', function () {
expect($messages)->toHaveKey('volume_name.regex');
});
// --- escapeshellarg Defense Tests for docker volume create ---
it('escapeshellarg neutralizes injection in docker volume create command', function (string $maliciousName) {
$escaped = escapeshellarg($maliciousName);
$command = "docker volume create {$escaped}";
expect($command)->toStartWith('docker volume create ')
->and($escaped)->toStartWith("'")
->and($escaped)->toEndWith("'");
})->with([
'semicolon' => 'vol; rm -rf /',
'pipe' => 'vol | cat /etc/passwd',
'ampersand' => 'vol && whoami',
'backtick' => 'vol`id`',
'command substitution' => 'vol$(whoami)',
]);
// --- escapeshellarg Defense Tests for docker run -v ---
it('escapeshellarg neutralizes injection in docker run -v command', function (string $maliciousName) {
$escaped = escapeshellarg($maliciousName);
$command = "docker run --rm -v {$escaped}:/source -v {$escaped}:/target alpine sh -c 'cp -a /source/. /target/'";
expect($command)->toContain('docker run --rm -v ')
->and($escaped)->toStartWith("'")
->and($escaped)->toEndWith("'");
})->with([
'semicolon' => 'vol; rm -rf /',
'pipe' => 'vol | cat /etc/passwd',
'command substitution' => 'vol$(whoami)',
]);
// --- escapeshellarg Defense Tests for docker network commands ---
it('escapeshellarg neutralizes injection in docker network disconnect command', function (string $maliciousName) {
$escaped = escapeshellarg($maliciousName);
$command = "docker network disconnect {$escaped} coolify-proxy";
expect($command)->toStartWith('docker network disconnect ')
->and($escaped)->toStartWith("'")
->and($escaped)->toEndWith("'");
})->with([
'semicolon' => 'net; rm -rf /',
'pipe' => 'net | cat /etc/passwd',
'command substitution' => 'net$(whoami)',
]);
it('escapeshellarg neutralizes injection in docker network rm command', function (string $maliciousName) {
$escaped = escapeshellarg($maliciousName);
$command = "docker network rm {$escaped}";
expect($command)->toStartWith('docker network rm ')
->and($escaped)->toStartWith("'")
->and($escaped)->toEndWith("'");
})->with([
'semicolon' => 'net; rm -rf /',
'pipe' => 'net | cat /etc/passwd',
'command substitution' => 'net$(whoami)',
]);
// --- DIRECTORY_PATH_PATTERN Tests ---
it('accepts valid directory paths', function (string $path) {
expect(preg_match(ValidationPatterns::DIRECTORY_PATH_PATTERN, $path))->toBe(1);
})->with([
'root' => '/',
'simple path' => '/data',
'nested path' => '/data/coolify/volumes',
'with dots' => '/data/my.app/storage',
'with hyphens' => '/data/my-app/storage',
'with underscores' => '/data/my_app/storage',
]);
it('rejects directory paths with shell metacharacters', function (string $path) {
expect(preg_match(ValidationPatterns::DIRECTORY_PATH_PATTERN, $path))->toBe(0);
})->with([
'semicolon injection' => '/etc; rm -rf /',
'pipe injection' => '/etc | cat /etc/passwd',
'command substitution' => '/etc$(whoami)',
'backtick injection' => '/etc`id`',
'space injection' => '/etc /tmp',
'relative traversal' => '../../../etc/passwd',
'no leading slash' => 'etc/passwd',
]);
@@ -74,3 +74,69 @@ test('postgresql init script accepts legitimate filenames', function () {
expect(fn () => validateShellSafePath('setup_db.sql', 'init script filename'))
->not->toThrow(Exception::class);
});
// Path traversal — GHSA-mv4c-9x67-rrmv regression tests
test('postgresql init script rejects path traversal with ../ sequence', function () {
expect(fn () => validateFilenameSafe('../../../etc/cron.d/pwn', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects path traversal targeting /etc/cron.d', function () {
expect(fn () => validateFilenameSafe('../../../../../etc/cron.d/k4zrce', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects absolute path', function () {
expect(fn () => validateFilenameSafe('/etc/passwd', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects filename with forward slash', function () {
expect(fn () => validateFilenameSafe('subdir/evil.sql', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects filename with backslash', function () {
expect(fn () => validateFilenameSafe('subdir\\evil.sql', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects double-dot without slashes', function () {
expect(fn () => validateFilenameSafe('..', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects null byte injection', function () {
expect(fn () => validateFilenameSafe("init.sql\0../../etc/passwd", 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script accepts legitimate filenames via validateFilenameSafe', function () {
expect(fn () => validateFilenameSafe('init.sql', 'init script filename'))
->not->toThrow(Exception::class);
expect(fn () => validateFilenameSafe('01_schema.sql', 'init script filename'))
->not->toThrow(Exception::class);
expect(fn () => validateFilenameSafe('init-script.sh', 'init script filename'))
->not->toThrow(Exception::class);
});
// Write-site defence — basename() + escapeshellarg() keep legacy/bad rows safe
test('basename() strips path traversal from legacy filenames at write site', function () {
expect(basename('../../../etc/cron.d/pwn'))->toBe('pwn');
expect(basename('/etc/passwd'))->toBe('passwd');
expect(basename('subdir/evil.sql'))->toBe('evil.sql');
});
test('escapeshellarg() neutralises shell metacharacters in tee target', function () {
// Simulates how StartPostgresql::generate_init_scripts() builds the tee argument
$configuration_dir = '/data/coolify/databases/abc123';
$legacy_filename = basename('foo bar*.sql;rm -rf /');
$target = "$configuration_dir/docker-entrypoint-initdb.d/{$legacy_filename}";
$escaped = escapeshellarg($target);
// Single-quoted in POSIX sh means no expansion / no extra args regardless of contents.
expect($escaped)->toStartWith("'")->toEndWith("'");
expect($escaped)->toContain('foo bar*.sql;rm -rf');
});
@@ -0,0 +1,91 @@
<?php
use App\Models\S3Storage;
use App\Rules\SafeWebhookUrl;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
uses(TestCase::class);
/**
* Regression tests for SSRF via S3 Storage endpoint.
*
* The Livewire forms (Create.php, Form.php) and the model-level defense in
* S3Storage::testConnection() share the same SafeWebhookUrl rule. These tests
* assert the rule rejects the concrete payloads and that the model refuses to
* build an S3 client for an unsafe endpoint.
*/
it('rejects SSRF payloads on the S3 endpoint', function (string $endpoint) {
$validator = Validator::make(
['endpoint' => $endpoint],
['endpoint' => ['required', 'max:255', new SafeWebhookUrl]],
);
expect($validator->fails())->toBeTrue("Expected rejection: {$endpoint}");
})->with([
'AWS IMDS' => 'http://169.254.169.254/latest/meta-data/',
'AWS IMDS bare' => 'http://169.254.169.254',
'GCP metadata via link-local' => 'http://169.254.0.1',
'loopback v4' => 'http://127.0.0.1',
'loopback Redis' => 'http://127.0.0.1:6379',
'loopback Postgres' => 'http://127.0.0.1:5432',
'loopback alt in /8' => 'http://127.10.20.30',
'zero address' => 'http://0.0.0.0',
'IPv6 loopback' => 'http://[::1]',
'localhost hostname' => 'http://localhost',
'localhost with port' => 'http://localhost:9000',
'internal suffix' => 'http://minio.internal',
'file scheme' => 'file:///etc/passwd',
'javascript scheme' => 'javascript:alert(1)',
]);
it('accepts real-world S3 endpoints', function (string $endpoint) {
$validator = Validator::make(
['endpoint' => $endpoint],
['endpoint' => ['required', 'max:255', new SafeWebhookUrl]],
);
expect($validator->passes())->toBeTrue("Expected accepted: {$endpoint}");
})->with([
'AWS S3' => 'https://s3.us-east-1.amazonaws.com',
'Cloudflare R2' => 'https://fake.r2.cloudflarestorage.com',
'DigitalOcean Spaces' => 'https://nyc3.digitaloceanspaces.com',
'Backblaze B2' => 'https://s3.us-west-001.backblazeb2.com',
'Self-hosted MinIO on 10.x' => 'http://10.0.0.5:9000',
'Self-hosted MinIO on 172.16.x' => 'http://172.16.0.10:9000',
'Self-hosted MinIO on 192.168.x' => 'http://192.168.1.50:9000',
'Custom domain MinIO' => 'https://minio.example.com',
]);
it('blocks testConnection() on an unsafe endpoint without issuing HTTP', function () {
$s3Storage = new S3Storage;
$s3Storage->setRawAttributes([
'region' => 'us-east-1',
'key' => 'AKIAEXAMPLE',
'secret' => 'secret',
'bucket' => 'latest/meta-data',
'endpoint' => 'http://169.254.169.254',
]);
expect(fn () => $s3Storage->testConnection())
->toThrow(RuntimeException::class, 'S3 endpoint is not allowed');
});
it('blocks testConnection() for loopback endpoints', function (string $endpoint) {
$s3Storage = new S3Storage;
$s3Storage->setRawAttributes([
'region' => 'us-east-1',
'key' => 'AKIAEXAMPLE',
'secret' => 'secret',
'bucket' => 'bucket',
'endpoint' => $endpoint,
]);
expect(fn () => $s3Storage->testConnection())
->toThrow(RuntimeException::class, 'S3 endpoint is not allowed');
})->with([
'http loopback' => 'http://127.0.0.1:6379',
'localhost' => 'http://localhost:9000',
'IPv6 loopback' => 'http://[::1]',
'internal TLD' => 'http://backend.internal',
]);
+51
View File
@@ -1,11 +1,13 @@
<?php
use App\Events\ServerReachabilityChanged;
use App\Jobs\ServerCheckJob;
use App\Jobs\ServerConnectionCheckJob;
use App\Jobs\ServerManagerJob;
use App\Models\Server;
use Illuminate\Queue\TimeoutExceededException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
uses(TestCase::class);
@@ -126,16 +128,21 @@ describe('shouldSkipDueToBackoff', function () {
describe('ServerConnectionCheckJob unreachable_count', function () {
it('increments unreachable_count on timeout', function () {
Event::fake([ServerReachabilityChanged::class]);
$settings = Mockery::mock();
$settings->is_reachable = true;
$settings->shouldReceive('update')
->with(['is_reachable' => false, 'is_usable' => false])
->once();
$server = Mockery::mock(Server::class)->makePartial()->shouldAllowMockingProtectedMethods();
$server->shouldReceive('getAttribute')->with('settings')->andReturn($settings);
$server->shouldReceive('getAttribute')->with('unreachable_notification_sent')->andReturn(false);
$server->shouldReceive('increment')->with('unreachable_count')->once();
$server->id = 1;
$server->name = 'test-server';
$server->unreachable_count = 1; // Will become 2 after increment in real code; mock keeps value as-is
$job = new ServerConnectionCheckJob($server);
$job->failed(new TimeoutExceededException);
@@ -152,6 +159,50 @@ describe('ServerConnectionCheckJob unreachable_count', function () {
});
});
describe('ServerConnectionCheckJob ServerReachabilityChanged dispatch', function () {
// ServerReachabilityChanged's constructor calls $server->isReachableChanged() — verifying that
// call is a clean proxy for "the event was dispatched", and avoids serializing a Mockery proxy
// through the event dispatcher (which trips Eloquent static method lookups on the proxy class).
$invoke = function (bool $wasReachable, bool $wasNotified, bool $isReachable, int $unreachableCount, bool $expectDispatch) {
$server = Mockery::mock(Server::class)->makePartial()->shouldAllowMockingProtectedMethods();
$server->shouldReceive('getAttribute')->with('unreachable_count')->andReturn($unreachableCount);
$server->shouldReceive('getAttribute')->with('id')->andReturn(1);
if ($expectDispatch) {
$server->shouldReceive('isReachableChanged')->once()->andReturnNull();
} else {
$server->shouldNotReceive('isReachableChanged');
}
$job = new ServerConnectionCheckJob($server);
$method = new ReflectionMethod($job, 'dispatchReachabilityChangedIfNeeded');
$method->invoke($job, $wasReachable, $wasNotified, $isReachable);
};
it('dispatches event when count crosses unreachable threshold', function () use ($invoke) {
$invoke(true, false, false, 2, true);
});
it('does not dispatch on first transient failure (count=1)', function () use ($invoke) {
$invoke(true, false, false, 1, false);
});
it('does not dispatch when already notified and still unreachable', function () use ($invoke) {
$invoke(false, true, false, 5, false);
});
it('dispatches recovery event when previously unreachable', function () use ($invoke) {
$invoke(false, false, true, 0, true);
});
it('dispatches recovery event when previously notified', function () use ($invoke) {
$invoke(true, true, true, 0, true);
});
it('does not dispatch when consistently reachable and never notified', function () use ($invoke) {
$invoke(true, false, true, 0, false);
});
});
describe('ServerCheckJob unreachable_count', function () {
it('increments unreachable_count on timeout', function () {
$server = Mockery::mock(Server::class)->makePartial()->shouldAllowMockingProtectedMethods();
@@ -0,0 +1,45 @@
<?php
use App\Models\StandaloneDocker;
use Illuminate\Database\Eloquent\Model;
/**
* Guards STANDALONE_DATABASE_MODELS against drift.
*
* MCP and API endpoints rely on this registry for team-scoped UUID lookups.
* If a new App\Models\Standalone* model lands without a registry entry, the
* helpers in bootstrap/helpers/shared.php silently fail to resolve it.
*/
test('STANDALONE_DATABASE_MODELS contains every Standalone* model on disk', function () {
$files = glob(dirname(__DIR__, 2).'/app/Models/Standalone*.php');
expect($files)->not->toBeEmpty();
$onDisk = collect($files)
->map(fn (string $path) => 'App\\Models\\'.basename($path, '.php'))
->reject(fn (string $class) => $class === StandaloneDocker::class)
->sort()
->values()
->all();
$registered = collect(STANDALONE_DATABASE_MODELS)->values()->sort()->values()->all();
expect($registered)->toBe(
$onDisk,
'STANDALONE_DATABASE_MODELS in bootstrap/helpers/constants.php is out of sync with the App\\Models\\Standalone* classes on disk. '
.'Add the missing model(s) to the registry (and to DATABASE_TYPES) so MCP/API helpers can resolve them.'
);
});
test('STANDALONE_DATABASE_MODELS keys mirror DATABASE_TYPES', function () {
expect(array_keys(STANDALONE_DATABASE_MODELS))->toEqualCanonicalizing(DATABASE_TYPES);
});
test('every STANDALONE_DATABASE_MODELS entry is an Eloquent model with whereUuid scope', function () {
foreach (STANDALONE_DATABASE_MODELS as $slug => $modelClass) {
expect(class_exists($modelClass))->toBeTrue("{$slug} maps to non-existent class {$modelClass}");
expect(is_subclass_of($modelClass, Model::class))
->toBeTrue("{$modelClass} is not an Eloquent model");
expect(method_exists($modelClass, 'team'))
->toBeTrue("{$modelClass} is missing team() accessor required by queryDatabaseByUuidWithinTeam()");
}
});
+138
View File
@@ -0,0 +1,138 @@
<?php
test('allows plain filenames without special characters', function () {
$validNames = [
'init.sql',
'01_schema.sql',
'setup-db.sql',
'create_test_db.sql',
'init-script.sh',
'UPPERCASE.SQL',
'mixed_Case-File.sql',
'file123.sql',
'a',
];
foreach ($validNames as $name) {
expect(fn () => validateFilenameSafe($name, 'init script filename'))
->not->toThrow(Exception::class, "Expected '{$name}' to pass");
}
});
test('rejects path traversal with ../', function () {
expect(fn () => validateFilenameSafe('../../../etc/cron.d/pwn', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects path traversal with .. alone', function () {
expect(fn () => validateFilenameSafe('..', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects path traversal embedded in filename', function () {
expect(fn () => validateFilenameSafe('foo..bar', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects forward slash directory separator', function () {
expect(fn () => validateFilenameSafe('foo/bar.sql', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects backslash directory separator', function () {
expect(fn () => validateFilenameSafe('foo\\bar.sql', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects absolute path starting with slash', function () {
expect(fn () => validateFilenameSafe('/etc/passwd', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects absolute Windows-style path', function () {
expect(fn () => validateFilenameSafe('C:\\Windows\\System32\\cmd.exe', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects null byte injection', function () {
expect(fn () => validateFilenameSafe("init.sql\0../../etc/passwd", 'init script filename'))
->toThrow(Exception::class);
});
test('rejects shell command substitution (inherits from validateShellSafePath)', function () {
expect(fn () => validateFilenameSafe('$(whoami).sql', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects backtick command substitution', function () {
expect(fn () => validateFilenameSafe('`id`.sql', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects semicolon command separator', function () {
expect(fn () => validateFilenameSafe('init.sql;rm -rf /', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects pipe operator', function () {
expect(fn () => validateFilenameSafe('init.sql|whoami', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects redirect operators', function () {
expect(fn () => validateFilenameSafe('init.sql>/etc/passwd', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects mixed traversal and shell injection', function () {
expect(fn () => validateFilenameSafe('../etc/cron.d/$(id)', 'init script filename'))
->toThrow(Exception::class);
});
test('error message contains context string', function () {
try {
validateFilenameSafe('../evil', 'init script filename');
expect(false)->toBeTrue('Should have thrown');
} catch (Exception $e) {
expect($e->getMessage())->toContain('init script filename');
}
});
test('handles empty string without throwing', function () {
expect(fn () => validateFilenameSafe('', 'init script filename'))
->not->toThrow(Exception::class);
});
test('rejects whitespace inside filename (would split into extra tee arg)', function () {
expect(fn () => validateFilenameSafe('foo bar.sql', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects glob wildcards', function () {
expect(fn () => validateFilenameSafe('init*.sql', 'init script filename'))
->toThrow(Exception::class);
expect(fn () => validateFilenameSafe('init?.sql', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects glob character class brackets', function () {
expect(fn () => validateFilenameSafe('init[abc].sql', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects tilde expansion', function () {
expect(fn () => validateFilenameSafe('~/evil.sql', 'init script filename'))
->toThrow(Exception::class);
expect(fn () => validateFilenameSafe('~root', 'init script filename'))
->toThrow(Exception::class);
});
test('rejects single and double quotes', function () {
expect(fn () => validateFilenameSafe("foo'bar.sql", 'init script filename'))
->toThrow(Exception::class);
expect(fn () => validateFilenameSafe('foo"bar.sql', 'init script filename'))
->toThrow(Exception::class);
});
+43
View File
@@ -1,5 +1,6 @@
<?php
use App\Models\EnvironmentVariable;
use App\Support\ValidationPatterns;
it('accepts valid names with common characters', function (string $name) {
@@ -130,3 +131,45 @@ it('generates nullable dockerNetworkRules when not required', function () {
expect($rules)->toContain('nullable')
->not->toContain('required');
});
it('accepts Docker-compatible environment variable keys', function (string $key) {
expect(ValidationPatterns::isValidEnvironmentVariableKey($key))->toBeTrue();
})->with([
'letters' => 'APP_ENV',
'leading underscore' => '_TOKEN',
'railpack control variable' => 'RAILPACK_NODE_VERSION',
'digits after first character' => 'NODE_VERSION_20',
'starts with digit' => '1BAD',
'hyphen' => 'BAD-KEY',
'dot' => 'node.name',
'uppercase dots' => 'XPACK.SECURITY.ENABLED',
'semicolon' => 'BAD;KEY',
'space' => 'BAD KEY',
]);
it('rejects environment variable keys Docker cannot represent', function (string $key) {
expect(ValidationPatterns::isValidEnvironmentVariableKey($key))->toBeFalse();
})->with([
'equals' => 'BAD=KEY',
'empty' => '',
]);
it('generates environment variable key rules with correct defaults', function () {
$rules = ValidationPatterns::environmentVariableKeyRules();
expect($rules)->toContain('required')
->toContain('string')
->toContain('max:255')
->toContain('regex:'.ValidationPatterns::ENVIRONMENT_VARIABLE_KEY_PATTERN);
});
it('normalizes environment variable keys by trimming surrounding whitespace', function () {
expect(ValidationPatterns::normalizeEnvironmentVariableKey(' node.name '))->toBe('node.name');
});
it('normalizes environment variable keys before model validation', function () {
$environmentVariable = new EnvironmentVariable;
$environmentVariable->key = ' APP_ENV ';
expect($environmentVariable->key)->toBe('APP_ENV');
});