Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

20.9 KB
Raw Blame
<?php

use App\Livewire\Project\CloneMe;
use App\Livewire\Project\New\Select as ResourceSelect;
use App\Livewire\Project\New\SimpleDockerfile;
use App\Livewire\Project\Shared\ResourceOperations;
use App\Livewire\Server\Show;
use App\Models\Application;
use App\Models\Environment;
use App\Models\InstanceSettings;
use App\Models\Project;
use App\Models\Server;
use App\Models\Service;
use App\Models\StandaloneDocker;
use App\Models\StandalonePostgresql;
use App\Models\SwarmDocker;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Blade;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    Server::flushIdentityMap();
    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->token = $this->user->createToken('resource-hosting-test', ['*']);
    $this->bearerToken = $this->token->plainTextToken;

    $this->server = Server::factory()->create(['team_id' => $this->team->id]);
    $this->server->settings()->update([
        'is_reachable' => true,
        'is_usable' => true,
        'is_build_server' => false,
        'is_swarm_worker' => false,
        'force_disabled' => false,
    ]);
    $this->server->refresh()->load('settings');

    $this->destination = StandaloneDocker::where('server_id', $this->server->id)->firstOrFail();
    $this->project = Project::factory()->create(['team_id' => $this->team->id]);
    $this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
});

afterEach(function () {
    Server::flushIdentityMap();
});

function resourceHostingApiHeaders(string $token): array
{
    return [
        'Authorization' => 'Bearer '.$token,
        'Content-Type' => 'application/json',
    ];
}

function createResourceHostingTestApplication(object $test): Application
{
    return Application::factory()->create([
        'environment_id' => $test->environment->id,
        'destination_id' => $test->destination->id,
        'destination_type' => $test->destination->getMorphClass(),
    ]);
}

test('only eligible deployment servers can host resources', function () {
    expect($this->server->canHostResources())->toBeTrue();

    $this->server->settings->update(['server_role' => 'build', 'is_build_server' => true]);

    expect($this->server->fresh()->canHostResources())->toBeFalse();
});

test('legacy server settings with a null role use the combined role', function () {
    $this->actingAs($this->user);
    $this->server->settings()->update(['server_role' => null]);
    $this->server->refresh()->load('settings');

    expect($this->server->settings->effectiveServerRole()->value)->toBe('both')
        ->and($this->server->canHostResources())->toBeTrue()
        ->and(Server::isUsable()->pluck('id'))->toContain($this->server->id)
        ->and(Server::isUsableBuildServer()->pluck('id'))->not->toContain($this->server->id)
        ->and(Server::buildServers($this->team->id)->pluck('id'))->not->toContain($this->server->id);
});

test('legacy build servers with a null role stay build only', function () {
    $this->actingAs($this->user);
    $this->server->settings()->update(['server_role' => null, 'is_build_server' => true]);
    $this->server->refresh()->load('settings');

    expect($this->server->settings->effectiveServerRole()->value)->toBe('build')
        ->and(Server::isUsable()->pluck('id'))->not->toContain($this->server->id)
        ->and(Server::isUsableBuildServer()->pluck('id'))->toContain($this->server->id)
        ->and(Server::buildServers($this->team->id)->pluck('id'))->toContain($this->server->id);
});

test('deployments only requires a dedicated build server, not a combined server', function () {
    $combinedServer = Server::factory()->create(['team_id' => $this->team->id]);
    $combinedServer->settings()->update(['server_role' => 'both',
        'is_build_server' => false, 'is_reachable' => true, 'is_usable' => true]);

    Livewire::actingAs($this->user)
        ->test(Show::class, ['server_uuid' => $this->server->uuid])
        ->set('serverRole', 'deployment')
        ->call('requestServerRoleChange')
        ->assertSet('serverRole', 'both')
        ->assertDispatched('error');

    expect($this->server->settings->fresh()->server_role->value)->toBe('both');
});

test('changing from build only to deployments and builds requires confirmation', function () {
    createResourceHostingTestApplication($this);
    $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);

    Livewire::actingAs($this->user)
        ->test(Show::class, ['server_uuid' => $this->server->uuid])
        ->assertSet('serverRole', 'build')
        ->set('serverRole', 'both')
        ->call('requestServerRoleChange')
        ->assertSet('serverRole', 'build')
        ->assertSet('pendingServerRole', 'both')
        ->assertDispatched('open-server-role-confirmation')
        ->call('confirmServerRoleChange')
        ->assertSet('serverRole', 'both');

    expect($this->server->settings->fresh()->server_role->value)->toBe('both');
});

test('an empty deployment-only server requires confirmation before the combined role is enabled', function () {
    $this->server->settings()->update([
        'server_role' => 'deployment',
        'is_build_server' => false,
    ]);

    Livewire::actingAs($this->user)
        ->test(Show::class, ['server_uuid' => $this->server->uuid])
        ->set('serverRole', 'both')
        ->call('requestServerRoleChange')
        ->assertSet('serverRole', 'deployment')
        ->assertSet('pendingServerRole', 'both')
        ->assertDispatched('open-server-role-confirmation');

    expect($this->server->settings->fresh()->server_role->value)->toBe('deployment');
});

test('a populated server requires confirmation before builds are enabled', function () {
    createResourceHostingTestApplication($this);

    $component = Livewire::actingAs($this->user)
        ->test(Show::class, ['server_uuid' => $this->server->uuid])
        ->assertSet('serverRole', 'both')
        ->set('serverRole', 'deployment')
        ->call('requestServerRoleChange');

    $otherBuildServer = Server::factory()->create(['team_id' => $this->team->id]);
    $otherBuildServer->settings()->update(['server_role' => 'build',
        'is_build_server' => true, 'is_reachable' => true, 'is_usable' => true]);

    $component
        ->set('serverRole', 'deployment')
        ->call('requestServerRoleChange')
        ->set('serverRole', 'both')
        ->call('requestServerRoleChange')
        ->assertSet('serverRole', 'deployment')
        ->assertSet('pendingServerRole', 'both')
        ->assertDispatched('open-server-role-confirmation')
        ->call('confirmServerRoleChange')
        ->assertSet('serverRole', 'both');

    expect($this->server->settings->fresh()->server_role->value)->toBe('both');
});

test('resource selection keeps excluded build servers visible for explanation', function () {
    $this->actingAs($this->user);
    $buildServer = Server::factory()->create(['team_id' => $this->team->id]);
    $buildServer->settings()->update([
        'is_reachable' => true,
        'is_usable' => true,
        'server_role' => 'build',
        'is_build_server' => true,
        'is_swarm_worker' => false,
        'force_disabled' => false,
    ]);

    $component = new ResourceSelect;
    $component->loadServers();

    expect($component->servers->pluck('id'))->toContain($this->server->id)
        ->not->toContain($buildServer->id)
        ->and(Server::isUsableBuildServer()->pluck('id'))->toContain($buildServer->id)
        ->not->toContain($this->server->id)
        ->and($component->buildServers->pluck('id'))->toContain($buildServer->id)
        ->and($component->allServers->pluck('id'))->toContain($this->server->id, $buildServer->id);
});

test('resource selection lists each combined server once', function () {
    $this->actingAs($this->user);
    $otherServer = Server::factory()->create(['team_id' => $this->team->id]);
    $otherServer->settings()->update([
        'is_reachable' => true,
        'is_usable' => true,
        'server_role' => 'both',
        'is_build_server' => false,
        'is_swarm_worker' => false,
        'force_disabled' => false,
    ]);

    $component = new ResourceSelect;
    $component->loadServers();

    expect($component->buildServers)->toBeEmpty()
        ->and($component->servers->pluck('id')->all())->toEqualCanonicalizing([$this->server->id, $otherServer->id])
        ->and($component->allServers->pluck('id')->duplicates())->toBeEmpty();
});

test('resource selection does not show the empty server message when only build servers are available', function () {
    $html = Blade::render(
        file_get_contents(resource_path('views/livewire/project/new/select.blade.php')),
        [
            'current_step' => 'servers',
            'onlyBuildServerAvailable' => true,
            'servers' => collect(),
            'buildServers' => collect(),
        ],
    );

    expect($html)
        ->toContain('Only build servers are available')
        ->not->toContain('No validated & reachable servers found');
});

test('application API rejects build servers', function () {
    $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);

    $this->withHeaders(resourceHostingApiHeaders($this->bearerToken))
        ->postJson('/api/v1/applications/dockerimage', [
            'project_uuid' => $this->project->uuid,
            'environment_uuid' => $this->environment->uuid,
            'server_uuid' => $this->server->uuid,
            'docker_registry_image_name' => 'nginx',
            'docker_registry_image_tag' => 'latest',
            'ports_exposes' => '80',
            'instant_deploy' => false,
        ])
        ->assertUnprocessable()
        ->assertInvalid(['server_uuid']);

    expect(Application::count())->toBe(0);
});

test('database API rejects build servers', function () {
    $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);

    $this->withHeaders(resourceHostingApiHeaders($this->bearerToken))
        ->postJson('/api/v1/databases/postgresql', [
            'project_uuid' => $this->project->uuid,
            'environment_uuid' => $this->environment->uuid,
            'server_uuid' => $this->server->uuid,
            'instant_deploy' => false,
        ])
        ->assertUnprocessable()
        ->assertInvalid(['server_uuid']);
});

test('service API rejects build servers', function () {
    $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);

    $this->withHeaders(resourceHostingApiHeaders($this->bearerToken))
        ->postJson('/api/v1/services', [
            'project_uuid' => $this->project->uuid,
            'environment_uuid' => $this->environment->uuid,
            'server_uuid' => $this->server->uuid,
            'docker_compose_raw' => base64_encode("services:\n  app:\n    image: nginx:latest"),
            'instant_deploy' => false,
        ])
        ->assertUnprocessable()
        ->assertInvalid(['server_uuid']);
});

test('server API rejects enabling build mode when resources exist', function () {
    createResourceHostingTestApplication($this);
    $originalName = $this->server->name;

    $this->withHeaders(resourceHostingApiHeaders($this->bearerToken))
        ->patchJson('/api/v1/servers/'.$this->server->uuid, [
            'server_role' => 'build',
            'name' => 'should-not-be-saved',
        ])
        ->assertUnprocessable()
        ->assertInvalid(['server_role']);

    expect((bool) $this->server->settings->fresh()->is_build_server)->toBeFalse()
        ->and($this->server->fresh()->name)->toBe($originalName);
});

test('server API allows keeping build mode enabled when resources exist', function () {
    createResourceHostingTestApplication($this);
    $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);

    $this->withHeaders(resourceHostingApiHeaders($this->bearerToken))
        ->patchJson('/api/v1/servers/'.$this->server->uuid, [
            'server_role' => 'build',
        ])
        ->assertCreated();

    expect((bool) $this->server->settings->fresh()->is_build_server)->toBeTrue();
});

test('server API allows disabling build mode when resources exist', function () {
    createResourceHostingTestApplication($this);
    $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);

    $this->withHeaders(resourceHostingApiHeaders($this->bearerToken))
        ->patchJson('/api/v1/servers/'.$this->server->uuid, [
            'server_role' => 'both',
            'name' => 'Deployment Server',
        ])
        ->assertCreated();

    expect((bool) $this->server->settings->fresh()->is_build_server)->toBeFalse()
        ->and($this->server->settings->fresh()->server_role->value)->toBe('both')
        ->and($this->server->fresh()->name)->toBe('Deployment Server');
});

test('resource APIs still accept deployment servers', function () {
    $headers = resourceHostingApiHeaders($this->bearerToken);

    $this->withHeaders($headers)
        ->postJson('/api/v1/applications/dockerimage', [
            'project_uuid' => $this->project->uuid,
            'environment_uuid' => $this->environment->uuid,
            'server_uuid' => $this->server->uuid,
            'docker_registry_image_name' => 'nginx',
            'docker_registry_image_tag' => 'latest',
            'ports_exposes' => '80',
            'instant_deploy' => false,
        ])
        ->assertCreated();

    $this->withHeaders($headers)
        ->postJson('/api/v1/databases/postgresql', [
            'project_uuid' => $this->project->uuid,
            'environment_uuid' => $this->environment->uuid,
            'server_uuid' => $this->server->uuid,
            'instant_deploy' => false,
        ])
        ->assertCreated();

    $this->withHeaders($headers)
        ->postJson('/api/v1/services', [
            'project_uuid' => $this->project->uuid,
            'environment_uuid' => $this->environment->uuid,
            'server_uuid' => $this->server->uuid,
            'docker_compose_raw' => base64_encode("services:\n  app:\n    image: nginx:latest"),
            'instant_deploy' => false,
        ])
        ->assertCreated();
});

test('a crafted web request cannot create a resource on a build server', function () {
    $this->actingAs($this->user);
    $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);

    $url = route('project.resource.create', [
        'project_uuid' => $this->project->uuid,
        'environment_uuid' => $this->environment->uuid,
    ]).'?type=postgresql&destination='.$this->destination->uuid.'&server_id='.$this->server->id.'&database_image=postgres:16-alpine';

    $this->get($url)->assertRedirectToRoute('dashboard');

    expect(StandalonePostgresql::count())->toBe(0);
});

test('a manipulated resource form cannot submit to a build server', function () {
    $this->actingAs($this->user);
    $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);
    $routeParameters = [
        'project_uuid' => $this->project->uuid,
        'environment_uuid' => $this->environment->uuid,
    ];

    expect(fn () => Livewire::withUrlParams(['destination' => $this->destination->uuid])
        ->test(SimpleDockerfile::class, $routeParameters)
        ->set('dockerfile', "FROM nginx\nCMD [\"nginx\"]\n")
        ->call('submit'))
        ->toThrow(Exception::class, 'Destination not found.');

    expect(Application::count())->toBe(0);
});

test('a manipulated project clone cannot target a build server', function () {
    $this->actingAs($this->user);
    $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);
    $projectCount = Project::count();

    Livewire::test(CloneMe::class, [
        'project_uuid' => $this->project->uuid,
        'environment_uuid' => $this->environment->uuid,
    ])
        ->set('selectedDestination', $this->destination->uuid)
        ->set('newName', 'blocked-clone')
        ->call('clone', 'project');

    expect(Project::count())->toBe($projectCount);
});

test('project clone resolves overlapping destination ids by uuid', function () {
    $this->actingAs($this->user);
    createResourceHostingTestApplication($this);
    $swarmDestination = SwarmDocker::create([
        'server_id' => $this->server->id,
        'name' => 'Swarm destination',
        'network' => 'swarm-network',
    ]);

    expect($swarmDestination->id)->toBe($this->destination->id);

    Livewire::test(CloneMe::class, [
        'project_uuid' => $this->project->uuid,
        'environment_uuid' => $this->environment->uuid,
    ])
        ->set('selectedDestination', $swarmDestination->uuid)
        ->set('newName', 'swarm-clone')
        ->call('clone', 'project')
        ->assertNotDispatched('error');

    $clonedApplication = Project::where('name', 'swarm-clone')
        ->firstOrFail()
        ->environments()
        ->where('name', $this->environment->name)
        ->firstOrFail()
        ->applications()
        ->firstOrFail();

    expect($clonedApplication->destination_id)->toBe($swarmDestination->id)
        ->and($clonedApplication->destination_type)->toBe(SwarmDocker::class)
        ->and($clonedApplication->destination->is($swarmDestination))->toBeTrue();
});

test('project clone assigns services to the selected server', function () {
    $this->actingAs($this->user);
    Service::factory()->create([
        'environment_id' => $this->environment->id,
        'server_id' => $this->server->id,
        'destination_id' => $this->destination->id,
        'destination_type' => $this->destination->getMorphClass(),
    ]);
    $targetServer = Server::factory()->create(['team_id' => $this->team->id]);
    $targetServer->settings()->update(['is_build_server' => false]);
    $targetDestination = StandaloneDocker::where('server_id', $targetServer->id)->firstOrFail();

    Livewire::test(CloneMe::class, [
        'project_uuid' => $this->project->uuid,
        'environment_uuid' => $this->environment->uuid,
    ])
        ->set('selectedDestination', $targetDestination->uuid)
        ->set('newName', 'service-clone')
        ->call('clone', 'project')
        ->assertNotDispatched('error');

    $clonedService = Project::where('name', 'service-clone')
        ->firstOrFail()
        ->environments()
        ->where('name', $this->environment->name)
        ->firstOrFail()
        ->services()
        ->firstOrFail();

    expect($clonedService->server_id)->toBe($targetServer->id)
        ->and($clonedService->destination_id)->toBe($targetDestination->id)
        ->and($targetServer->fresh()->isEmpty())->toBeFalse();
});

test('a manipulated clone request cannot target a build server', function () {
    $this->actingAs($this->user);
    $source = createResourceHostingTestApplication($this);
    $buildServer = Server::factory()->create(['team_id' => $this->team->id]);
    $buildServer->settings()->update([
        'is_reachable' => true,
        'is_usable' => true,
        'server_role' => 'build',
        'is_build_server' => true,
    ]);
    $buildDestination = StandaloneDocker::where('server_id', $buildServer->id)->firstOrFail();

    Livewire::test(ResourceOperations::class, ['resource' => $source])
        ->call('cloneTo', $buildDestination->uuid)
        ->assertHasErrors(['destination_id']);

    expect(Application::count())->toBe(1);
});

test('resource clone resolves overlapping destination ids by uuid', function () {
    $this->actingAs($this->user);
    $source = createResourceHostingTestApplication($this);
    $swarmDestination = SwarmDocker::create([
        'server_id' => $this->server->id,
        'name' => 'Swarm clone target',
        'network' => 'swarm-clone-target',
    ]);

    expect($swarmDestination->id)->toBe($this->destination->id);

    Livewire::test(ResourceOperations::class, ['resource' => $source])
        ->call('cloneTo', $swarmDestination->uuid);

    $clone = Application::whereKeyNot($source->id)->firstOrFail();

    expect($clone->destination_id)->toBe($swarmDestination->id)
        ->and($clone->destination_type)->toBe(SwarmDocker::class)
        ->and($clone->destination->is($swarmDestination))->toBeTrue();
});

test('resource operations explains why build servers cannot be clone targets', function () {
    $this->actingAs($this->user);
    $source = createResourceHostingTestApplication($this);
    $buildServer = Server::factory()->create(['team_id' => $this->team->id, 'name' => 'Dedicated Builder']);
    $buildServer->settings()->update([
        'is_reachable' => true,
        'is_usable' => true,
        'server_role' => 'build',
        'is_build_server' => true,
    ]);

    Livewire::test(ResourceOperations::class, ['resource' => $source])
        ->assertSet('buildServers', fn ($servers) => $servers->contains('id', $buildServer->id))
        ->assertSee('Dedicated Builder')
        ->assertSee('build server');
});