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.

10.9 KB
Raw Blame
<?php

use App\Livewire\Server\Show;
use App\Models\InstanceSettings;
use App\Models\Server;
use App\Models\ServerSetting;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Once;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    DB::table('instance_settings')->insert(['id' => 0]);
    $user = User::factory()->create();
    $this->team = $user->teams()->first();

    $this->server = Server::factory()->create([
        'team_id' => $this->team->id,
    ]);
});

describe('ServerSetting::isValidSentinelToken', function () {
    it('accepts alphanumeric tokens', function () {
        expect(ServerSetting::isValidSentinelToken('abc123'))->toBeTrue();
    });

    it('accepts tokens with dots, hyphens, and underscores', function () {
        expect(ServerSetting::isValidSentinelToken('my-token_v2.0'))->toBeTrue();
    });

    it('accepts long base64-like encrypted tokens', function () {
        $token = 'eyJpdiI6IjRGN0V4YnRkZ1p0UXdBPT0iLCJ2YWx1ZSI6IjZqQT0iLCJtYWMiOiIxMjM0NTY3ODkwIn0';
        expect(ServerSetting::isValidSentinelToken($token))->toBeTrue();
    });

    it('accepts tokens with base64 characters (+, /, =)', function () {
        expect(ServerSetting::isValidSentinelToken('abc+def/ghi='))->toBeTrue();
    });

    it('rejects tokens with double quotes', function () {
        expect(ServerSetting::isValidSentinelToken('abc" ; id ; echo "'))->toBeFalse();
    });

    it('rejects tokens with single quotes', function () {
        expect(ServerSetting::isValidSentinelToken("abc' ; id ; echo '"))->toBeFalse();
    });

    it('rejects tokens with semicolons', function () {
        expect(ServerSetting::isValidSentinelToken('abc;id'))->toBeFalse();
    });

    it('rejects tokens with backticks', function () {
        expect(ServerSetting::isValidSentinelToken('abc`id`'))->toBeFalse();
    });

    it('rejects tokens with dollar sign command substitution', function () {
        expect(ServerSetting::isValidSentinelToken('abc$(whoami)'))->toBeFalse();
    });

    it('rejects tokens with spaces', function () {
        expect(ServerSetting::isValidSentinelToken('abc def'))->toBeFalse();
    });

    it('rejects tokens with newlines', function () {
        expect(ServerSetting::isValidSentinelToken("abc\nid"))->toBeFalse();
    });

    it('rejects tokens with pipe operator', function () {
        expect(ServerSetting::isValidSentinelToken('abc|id'))->toBeFalse();
    });

    it('rejects tokens with ampersand', function () {
        expect(ServerSetting::isValidSentinelToken('abc&&id'))->toBeFalse();
    });

    it('rejects tokens with redirection operators', function () {
        expect(ServerSetting::isValidSentinelToken('abc>/tmp/pwn'))->toBeFalse();
    });

    it('rejects empty strings', 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('loads the server page when the stored token cannot be decrypted', function () {
        $settings = $this->server->settings;
        DB::table('server_settings')->where('id', $settings->id)->update(['sentinel_token' => 'not-encrypted-junk']);

        $this->actingAs($this->team->members()->first());
        session(['currentTeam' => $this->team]);

        Livewire::test(Show::class, ['server_uuid' => $this->server->uuid])
            ->assertOk()
            ->assertSet('sentinelToken', $settings->fresh()->sentinel_token);

        expect(ServerSetting::isValidSentinelToken($settings->fresh()->sentinel_token))->toBeTrue();
    });

    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('ServerSetting::ensureSentinelUrl', function () {
    it('uses the internal Coolify endpoint for the local server', function () {
        InstanceSettings::query()->whereKey(0)->update([
            'fqdn' => 'https://coolify.example.com',
        ]);
        Once::flush();
        $this->server->update(['ip' => 'host.docker.internal']);
        DB::table('server_settings')->where('id', $this->server->settings->id)->update(['sentinel_custom_url' => null]);

        $url = $this->server->settings->fresh()->ensureSentinelUrl();

        expect($url)->toBe('http://coolify:8080')
            ->and($this->server->settings->fresh()->sentinel_custom_url)->toBe($url);
    });

    it('replaces the legacy local endpoint that depends on published port 8000', function () {
        $this->server->update(['ip' => 'host.docker.internal']);
        DB::table('server_settings')->where('id', $this->server->settings->id)->update([
            'sentinel_custom_url' => 'http://host.docker.internal:8000',
        ]);

        $url = $this->server->settings->fresh()->ensureSentinelUrl();

        expect($url)->toBe('http://coolify:8080')
            ->and($this->server->settings->fresh()->sentinel_custom_url)->toBe($url);
    });

    it('replaces a local host gateway endpoint on any port, because the Coolify network firewall can block it', function (string $legacyUrl) {
        $this->server->update(['ip' => 'host.docker.internal']);
        DB::table('server_settings')->where('id', $this->server->settings->id)->update([
            'sentinel_custom_url' => $legacyUrl,
        ]);

        $url = $this->server->settings->fresh()->ensureSentinelUrl();

        expect($url)->toBe('http://coolify:8080')
            ->and($this->server->settings->fresh()->sentinel_custom_url)->toBe($url);
    })->with([
        'custom APP_PORT' => 'http://host.docker.internal:8010',
        'trailing slash' => 'http://host.docker.internal:8000/',
        'uppercase host' => 'HTTP://Host.Docker.Internal:8010',
    ]);

    it('keeps a host gateway endpoint for a remote server', function () {
        DB::table('server_settings')->where('id', $this->server->settings->id)->update([
            'sentinel_custom_url' => 'http://host.docker.internal:8010',
        ]);

        expect($this->server->settings->fresh()->ensureSentinelUrl())->toBe('http://host.docker.internal:8010');
    });

    it('preserves an explicit custom URL for the local server', function () {
        $this->server->update(['ip' => 'host.docker.internal']);
        DB::table('server_settings')->where('id', $this->server->settings->id)->update([
            'sentinel_custom_url' => 'https://coolify.example.com',
        ]);

        $url = $this->server->settings->fresh()->ensureSentinelUrl();

        expect($url)->toBe('https://coolify.example.com');
    });

    it('uses the current private instance URL when no public address is configured', function () {
        InstanceSettings::query()->whereKey(0)->update([
            'fqdn' => null,
            'public_ipv4' => null,
            'public_ipv6' => null,
        ]);
        Once::flush();
        DB::table('server_settings')->where('id', $this->server->settings->id)->update(['sentinel_custom_url' => null]);
        app()->instance('request', Request::create('http://192.168.1.50:8000/server'));

        $url = $this->server->settings->fresh()->ensureSentinelUrl();

        expect($url)->toBe('http://192.168.1.50:8000')
            ->and($this->server->settings->fresh()->sentinel_custom_url)->toBe($url);
    });

    it('does not use a loopback request URL for a remote server', function () {
        InstanceSettings::query()->whereKey(0)->update([
            'fqdn' => null,
            'public_ipv4' => null,
            'public_ipv6' => null,
        ]);
        Once::flush();
        DB::table('server_settings')->where('id', $this->server->settings->id)->update(['sentinel_custom_url' => null]);
        app()->instance('request', Request::create('http://localhost:8000/server'));

        expect(fn () => $this->server->settings->fresh()->ensureSentinelUrl())
            ->toThrow(RuntimeException::class, 'Set an instance FQDN, public IP, or reachable Coolify URL before enabling Sentinel.');
    });
});

describe('generated sentinel tokens are valid', function () {
    it('generates tokens that pass format validation', function () {
        $settings = $this->server->settings;
        $settings->generateSentinelToken(save: false, ignoreEvent: true);
        $token = $settings->sentinel_token;

        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);
    });
});