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.

Merge remote-tracking branch 'origin/next' into openid-auth-support

Andras Bacsai0f051386088f
diff --cc app/Livewire/Destination/Show.php
index 9d55d74627,17fb5cea5d..1b344c9056
--- a/app/Livewire/Destination/Show.php
+++ b/app/Livewire/Destination/Show.php
@@@ -3,6 -3,6 +3,7 @@@
namespace App\Livewire\Destination;
use App\Models\StandaloneDocker;
++use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
@@@ -31,8 -31,12 +32,12 @@@ class Show extends Componen
if (! $destination) {
return redirect()->route('destination.index');
}
+ $this->authorize('view', $destination);
+
$this->destination = $destination;
$this->syncData();
- } catch (\Illuminate\Auth\Access\AuthorizationException) {
++ } catch (AuthorizationException) {
+ abort(403);
} catch (\Throwable $e) {
return handleError($e, $this);
}
diff --cc app/Livewire/Project/Database/BackupEdit.php
index ef106a65fe,6a1175dc7d..99426c120f
--- a/app/Livewire/Project/Database/BackupEdit.php
+++ b/app/Livewire/Project/Database/BackupEdit.php
@@@ -2,6 -2,6 +2,7 @@@
namespace App\Livewire\Project\Database;
++use App\Jobs\DatabaseBackupJob;
use App\Models\ScheduledDatabaseBackup;
use App\Models\ServiceDatabase;
use Exception;
@@@ -190,6 -190,18 +191,18 @@@ class BackupEdit extends Componen
}
}
+ public function backupNow()
+ {
+ try {
+ $this->authorize('manageBackups', $this->backup->database);
+
- \App\Jobs\DatabaseBackupJob::dispatch($this->backup);
++ DatabaseBackupJob::dispatch($this->backup);
+ $this->dispatch('success', 'Backup queued. It will be available in a few minutes.');
+ } catch (\Throwable $e) {
+ return handleError($e, $this);
+ }
+ }
+
public function instantSave()
{
try {
diff --cc app/Livewire/Project/Database/BackupExecutions.php
index 1dd93781dd,d27345b8db..41fb1681bf
--- a/app/Livewire/Project/Database/BackupExecutions.php
+++ b/app/Livewire/Project/Database/BackupExecutions.php
@@@ -3,6 -3,7 +3,8 @@@
namespace App\Livewire\Project\Database;
use App\Models\ScheduledDatabaseBackup;
++use App\Models\ServiceDatabase;
+ use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
@@@ -78,7 -97,7 +98,7 @@@ class BackupExecutions extends Componen
return;
}
-- $server = $execution->scheduledDatabaseBackup->database->getMorphClass() === \App\Models\ServiceDatabase::class
++ $server = $execution->scheduledDatabaseBackup->database->getMorphClass() === ServiceDatabase::class
? $execution->scheduledDatabaseBackup->database->service->destination->server
: $execution->scheduledDatabaseBackup->database->destination->server;
@@@ -185,7 -204,7 +205,7 @@@
if ($this->database) {
$server = null;
-- if ($this->database instanceof \App\Models\ServiceDatabase) {
++ if ($this->database instanceof ServiceDatabase) {
$server = $this->database->service->destination->server;
} elseif ($this->database->destination && $this->database->destination->server) {
$server = $this->database->destination->server;
diff --cc app/Livewire/Project/Database/ScheduledBackups.php
index 1cf5e53f6b,06473c56a7..9d1f212e44
--- a/app/Livewire/Project/Database/ScheduledBackups.php
+++ b/app/Livewire/Project/Database/ScheduledBackups.php
@@@ -3,6 -3,6 +3,7 @@@
namespace App\Livewire\Project\Database;
use App\Models\ScheduledDatabaseBackup;
++use App\Models\ServiceDatabase;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
@@@ -34,7 -34,7 +35,7 @@@ class ScheduledBackups extends Componen
$this->setSelectedBackup($this->selectedBackupId, true);
}
$this->parameters = get_route_parameters();
-- if ($this->database->getMorphClass() === \App\Models\ServiceDatabase::class) {
++ if ($this->database->getMorphClass() === ServiceDatabase::class) {
$this->type = 'service-database';
} else {
$this->type = 'database';
diff --cc app/Livewire/Settings/Advanced.php
index 8b8e93f5fa,5be066c7f6..8bc7ed306c
--- a/app/Livewire/Settings/Advanced.php
+++ b/app/Livewire/Settings/Advanced.php
@@@ -151,8 -150,8 +155,9 @@@ class Advanced extends Componen
public function instantSave()
{
try {
+ $this->authorize('update', $this->settings);
$this->settings->is_registration_enabled = $this->is_registration_enabled;
+ $this->settings->disable_registration_when_oauth_enabled = $this->disable_registration_when_oauth_enabled;
$this->settings->do_not_track = $this->do_not_track;
$this->settings->is_dns_validation_enabled = $this->is_dns_validation_enabled;
$this->settings->custom_dns_servers = $this->custom_dns_servers;
diff --cc app/Livewire/SettingsEmail.php
index a7b1c605f8,1bb9b23609..6a8e169d8b
--- a/app/Livewire/SettingsEmail.php
+++ b/app/Livewire/SettingsEmail.php
@@@ -185,11 -146,26 +190,12 @@@ class SettingsEmail extends Componen
public function submitSmtp()
{
try {
+ $this->authorize('update', $this->settings);
- $this->validate([
- 'smtpEnabled' => 'boolean',
- 'smtpFromAddress' => 'required|email',
- 'smtpFromName' => 'required|string',
- 'smtpHost' => 'required|string',
- 'smtpPort' => 'required|numeric',
- 'smtpEncryption' => 'required|string|in:starttls,tls,none',
- 'smtpUsername' => 'nullable|string',
- 'smtpPassword' => 'nullable|string',
- 'smtpTimeout' => 'nullable|numeric',
- ], [
- 'smtpFromAddress.required' => 'From Address is required.',
- 'smtpFromAddress.email' => 'Please enter a valid email address.',
- 'smtpFromName.required' => 'From Name is required.',
- 'smtpHost.required' => 'SMTP Host is required.',
- 'smtpPort.required' => 'SMTP Port is required.',
- 'smtpPort.numeric' => 'SMTP Port must be a number.',
- 'smtpEncryption.required' => 'Encryption type is required.',
- ]);
+ $this->validateSmtpSettings();
+
+ if ($this->smtpEnabled) {
+ $this->settings->resend_enabled = $this->resendEnabled = false;
+ }
$this->settings->smtp_enabled = $this->smtpEnabled;
$this->settings->smtp_host = $this->smtpHost;
@@@ -214,11 -190,18 +220,12 @@@
public function submitResend()
{
try {
+ $this->authorize('update', $this->settings);
- $this->validate([
- 'resendEnabled' => 'boolean',
- 'resendApiKey' => 'required|string',
- 'smtpFromAddress' => 'required|email',
- 'smtpFromName' => 'required|string',
- ], [
- 'resendApiKey.required' => 'Resend API Key is required.',
- 'smtpFromAddress.required' => 'From Address is required.',
- 'smtpFromAddress.email' => 'Please enter a valid email address.',
- 'smtpFromName.required' => 'From Name is required.',
- ]);
+ $this->validateResendSettings();
+
+ if ($this->resendEnabled) {
+ $this->settings->smtp_enabled = $this->smtpEnabled = false;
+ }
$this->settings->resend_enabled = $this->resendEnabled;
$this->settings->resend_api_key = $this->resendApiKey;
diff --cc app/Livewire/SettingsOauth.php
index a3025f5938,44ea4f611e..8b4c902d5f
--- a/app/Livewire/SettingsOauth.php
+++ b/app/Livewire/SettingsOauth.php
@@@ -2,45 -2,25 +2,48 @@@
namespace App\Livewire;
+use App\Models\InstanceSettings;
use App\Models\OauthSetting;
+ use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+use Illuminate\Validation\ValidationException;
use Livewire\Component;
class SettingsOauth extends Component
{
+ use AuthorizesRequests;
+
+ public InstanceSettings $settings;
+
public $oauth_settings_map;
- protected function rules()
+ public ?string $selectedProvider = null;
+
+ public bool $disable_registration_when_oauth_enabled = false;
+
+ protected function rules(): array
{
- return OauthSetting::all()->reduce(function ($carry, $setting) {
- $carry["oauth_settings_map.$setting->provider.enabled"] = 'required';
- $carry["oauth_settings_map.$setting->provider.client_id"] = 'nullable';
- $carry["oauth_settings_map.$setting->provider.client_secret"] = 'nullable';
- $carry["oauth_settings_map.$setting->provider.redirect_uri"] = 'nullable';
- $carry["oauth_settings_map.$setting->provider.tenant"] = 'nullable';
- $carry["oauth_settings_map.$setting->provider.base_url"] = 'nullable';
+ return $this->validationRules();
+ }
+
+ private function validationRules(?string $provider = null): array
+ {
+ $rules = OauthSetting::all()->reduce(function ($carry, $setting) use ($provider) {
+ if ($provider !== null && $setting->provider !== $provider) {
+ return $carry;
+ }
+
+ $carry["oauth_settings_map.$setting->provider.enabled"] = 'required|boolean';
+ $carry["oauth_settings_map.$setting->provider.client_id"] = 'nullable|string';
+ $carry["oauth_settings_map.$setting->provider.client_secret"] = 'nullable|string';
+ $carry["oauth_settings_map.$setting->provider.redirect_uri"] = 'nullable|string|max:2048|url:http,https';
+ $carry["oauth_settings_map.$setting->provider.tenant"] = 'nullable|string';
+ $carry["oauth_settings_map.$setting->provider.base_url"] = 'nullable|string|max:2048|url:http,https';
+ $carry["oauth_settings_map.$setting->provider.custom_label"] = 'nullable|string|max:255';
+ $carry["oauth_settings_map.$setting->provider.scopes"] = 'nullable|string|max:1000';
+ $carry["oauth_settings_map.$setting->provider.allow_registration"] = 'boolean';
+ $carry["oauth_settings_map.$setting->provider.require_email_verified"] = 'boolean';
+ $carry["oauth_settings_map.$setting->provider.use_pkce"] = 'boolean';
+ $carry["oauth_settings_map.$setting->provider.clock_skew_seconds"] = 'nullable|integer|min:0|max:600';
return $carry;
}, []);
@@@ -215,84 -141,14 +219,88 @@@
}
}
- public function submit()
+ public function toggleProvider(string $provider)
{
try {
+ $this->authorize('update', instanceSettings());
- $this->updateOauthSettings();
- $this->dispatch('success', 'Instance settings updated successfully!');
- } catch (\Throwable $e) {
++
+ if (! array_key_exists($provider, $this->oauth_settings_map)) {
+ abort(404);
+ }
+
+ if (! (bool) $this->oauth_settings_map[$provider]['enabled']) {
+ $this->validateProviderCanBeEnabled($provider);
+ }
+
+ $this->oauth_settings_map[$provider]['enabled'] = ! (bool) $this->oauth_settings_map[$provider]['enabled'];
+ $this->updateOauthSettings($provider);
+ } catch (\Exception $e) {
+ $oauth = OauthSetting::where('provider', $provider)->first();
+ if ($oauth) {
+ $this->oauth_settings_map[$provider] = $this->oauthSettingToArray($oauth);
+ }
+
return handleError($e, $this);
}
}
+
+ private function validateProviderCanBeEnabled(string $provider): void
+ {
+ $this->validate($this->validationRules($provider));
+
+ $oauth = OauthSetting::find($this->oauth_settings_map[$provider]['id']);
+ if (! $oauth) {
+ throw new \Exception('OAuth setting for '.$provider.' not found. It may have been deleted.');
+ }
+
+ $this->fillOauthSetting($oauth, [
+ ...$this->oauth_settings_map[$provider],
+ 'enabled' => true,
+ ]);
+
+ if (! $oauth->couldBeEnabled()) {
+ throw new \Exception('OAuth settings are not complete for '.$oauth->provider.'.<br/>Please fill in all required fields.');
+ }
+
+ if ($oauth->isOidc() && ! in_array('openid', $oauth->scopeList(), true)) {
+ throw new \Exception("OIDC scopes must include 'openid'.");
+ }
+ }
+
+ public function saveRegistrationPolicy(): void
+ {
++ $this->authorize('update', instanceSettings());
+ $this->validate([
+ 'disable_registration_when_oauth_enabled' => 'boolean',
+ ]);
+
+ instanceSettings()->update([
+ 'disable_registration_when_oauth_enabled' => $this->disable_registration_when_oauth_enabled,
+ ]);
+
+ $this->dispatch('success', 'Authentication settings updated successfully!');
+ }
+
+ public function submit(): void
+ {
+ try {
++ $this->authorize('update', instanceSettings());
+ $this->updateOauthSettings($this->selectedProvider);
+
+ if ($this->selectedProvider === null) {
+ $this->dispatch('success', 'Instance settings updated successfully!');
+ }
+ } catch (ValidationException $e) {
+ throw $e;
+ } catch (\Exception $e) {
+ if ($this->selectedProvider !== null) {
+ $oauth = OauthSetting::where('provider', $this->selectedProvider)->first();
+ if ($oauth) {
+ $this->oauth_settings_map[$this->selectedProvider] = $this->oauthSettingToArray($oauth);
+ }
+ }
+
+ handleError($e, $this);
+ }
+ }
}
diff --cc app/Livewire/Storage/Show.php
index dc5121e945,93c1ff2e4a..dd6640c233
--- a/app/Livewire/Storage/Show.php
+++ b/app/Livewire/Storage/Show.php
@@@ -4,6 -4,6 +4,7 @@@ namespace App\Livewire\Storage
use App\Models\S3Storage;
use App\Models\ScheduledDatabaseBackup;
++use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
@@@ -23,7 -23,11 +24,11 @@@ class Show extends Componen
if (! $this->storage) {
abort(404);
}
- $this->authorize('view', $this->storage);
+ try {
+ $this->authorize('view', $this->storage);
- } catch (\Illuminate\Auth\Access\AuthorizationException) {
++ } catch (AuthorizationException) {
+ return $this->redirectRoute('storage.index', navigate: true);
+ }
$this->currentRoute = request()->route()->getName();
$this->backupCount = ScheduledDatabaseBackup::where('s3_storage_id', $this->storage->id)->count();
}
diff --cc resources/views/livewire/notifications/pushover.blade.php
index f633b7b33a,4ea1a159cb..c92546ab0c
--- a/resources/views/livewire/notifications/pushover.blade.php
+++ b/resources/views/livewire/notifications/pushover.blade.php
@@@ -23,13 -20,25 +23,22 @@@
</x-forms.button>
@endif
</div>
- <div class="w-32">
- <x-forms.checkbox canGate="update" :canResource="$settings" instantSave="instantSavePushoverEnabled" id="pushoverEnabled" label="Enabled" />
- </div>
<div class="flex gap-2">
- <x-forms.input canGate="update" :canResource="$settings" type="password"
- helper="Get your User Key in Pushover. You need to be logged in to Pushover to see your user key in the top right corner. <br><a class='inline-block underline dark:text-white' href='https://pushover.net/' target='_blank'>Pushover Dashboard</a>"
- required id="pushoverUserKey" label="User Key" />
- <x-forms.input canGate="update" :canResource="$settings" type="password"
- helper="Generate an API Token/Key in Pushover by creating a new application. <br><a class='inline-block underline dark:text-white' href='https://pushover.net/apps/build' target='_blank'>Create Pushover Application</a>"
- required id="pushoverApiToken" label="API Token" />
+ @can('update', $settings)
+ <x-forms.input type="password"
+ helper="Get your User Key in Pushover. You need to be logged in to Pushover to see your user key in the top right corner. <br><a class='inline-block underline dark:text-white' href='https://pushover.net/' target='_blank'>Pushover Dashboard</a>"
+ required id="pushoverUserKey" label="User Key" />
+ <x-forms.input type="password"
+ helper="Generate an API Token/Key in Pushover by creating a new application. <br><a class='inline-block underline dark:text-white' href='https://pushover.net/apps/build' target='_blank'>Create Pushover Application</a>"
+ required id="pushoverApiToken" label="API Token" />
+ @else
+ <x-forms.input disabled
+ helper="Get your User Key in Pushover. You need to be logged in to Pushover to see your user key in the top right corner. <br><a class='inline-block underline dark:text-white' href='https://pushover.net/' target='_blank'>Pushover Dashboard</a>"
+ required label="User Key" value="Hidden (only admins can view)" />
+ <x-forms.input disabled
+ helper="Generate an API Token/Key in Pushover by creating a new application. <br><a class='inline-block underline dark:text-white' href='https://pushover.net/apps/build' target='_blank'>Create Pushover Application</a>"
+ required label="API Token" value="Hidden (only admins can view)" />
+ @endcan
</div>
</form>
<h2 class="mt-4">Notification Settings</h2>
diff --cc resources/views/livewire/notifications/slack.blade.php
index d7fd243552,9ab7522918..359169a13b
--- a/resources/views/livewire/notifications/slack.blade.php
+++ b/resources/views/livewire/notifications/slack.blade.php
@@@ -23,9 -20,18 +23,15 @@@
</x-forms.button>
@endif
</div>
- <x-forms.input canGate="update" :canResource="$settings" type="password"
- helper="Create a Slack APP and generate a Incoming Webhook URL. <br><a class='inline-block underline dark:text-white' href='https://api.slack.com/apps' target='_blank'>Create Slack APP</a>"
- required id="slackWebhookUrl" label="Webhook" />
- <div class="w-32">
- <x-forms.checkbox canGate="update" :canResource="$settings" instantSave="instantSaveSlackEnabled" id="slackEnabled" label="Enabled" />
- </div>
+ @can('update', $settings)
+ <x-forms.input type="password"
+ helper="Create a Slack APP and generate a Incoming Webhook URL. <br><a class='inline-block underline dark:text-white' href='https://api.slack.com/apps' target='_blank'>Create Slack APP</a>"
+ required id="slackWebhookUrl" label="Webhook" />
+ @else
+ <x-forms.input disabled
+ helper="Create a Slack APP and generate a Incoming Webhook URL. <br><a class='inline-block underline dark:text-white' href='https://api.slack.com/apps' target='_blank'>Create Slack APP</a>"
+ required label="Webhook" value="Hidden (only admins can view)" />
+ @endcan
</form>
<h2 class="mt-4">Notification Settings</h2>
<p class="mb-4">
diff --cc resources/views/livewire/notifications/telegram.blade.php
index fb7b1bc40a,98ec128d59..e226871d1f
--- a/resources/views/livewire/notifications/telegram.blade.php
+++ b/resources/views/livewire/notifications/telegram.blade.php
@@@ -23,13 -20,25 +23,22 @@@
</x-forms.button>
@endif
</div>
- <div class="w-32">
- <x-forms.checkbox canGate="update" :canResource="$settings" instantSave="instantSaveTelegramEnabled" id="telegramEnabled" label="Enabled" />
- </div>
<div class="flex gap-2">
- <x-forms.input canGate="update" :canResource="$settings" type="password" autocomplete="new-password"
- helper="Get it from the <a class='inline-block underline dark:text-white' href='https://t.me/botfather' target='_blank'>BotFather Bot</a> on Telegram."
- required id="telegramToken" label="Bot API Token" />
- <x-forms.input canGate="update" :canResource="$settings" type="password" autocomplete="new-password"
- helper="Add your bot to a group chat and add its Chat ID here." required id="telegramChatId"
- label="Chat ID" />
+ @can('update', $settings)
+ <x-forms.input type="password" autocomplete="new-password"
+ helper="Get it from the <a class='inline-block underline dark:text-white' href='https://t.me/botfather' target='_blank'>BotFather Bot</a> on Telegram."
+ required id="telegramToken" label="Bot API Token" />
+ <x-forms.input type="password" autocomplete="new-password"
+ helper="Add your bot to a group chat and add its Chat ID here." required id="telegramChatId"
+ label="Chat ID" />
+ @else
+ <x-forms.input disabled autocomplete="new-password"
+ helper="Get it from the <a class='inline-block underline dark:text-white' href='https://t.me/botfather' target='_blank'>BotFather Bot</a> on Telegram."
+ required label="Bot API Token" value="Hidden (only admins can view)" />
+ <x-forms.input disabled autocomplete="new-password"
+ helper="Add your bot to a group chat and add its Chat ID here." required label="Chat ID"
+ value="Hidden (only admins can view)" />
+ @endcan
</div>
</form>
<h2 class="mt-4">Notification Settings</h2>
diff --cc resources/views/livewire/notifications/webhook.blade.php
index 583583fa18,4bacb6091c..20fa3163c7
--- a/resources/views/livewire/notifications/webhook.blade.php
+++ b/resources/views/livewire/notifications/webhook.blade.php
@@@ -24,11 -22,21 +24,17 @@@
</x-forms.button>
@endif
</div>
- <div class="w-48">
- <x-forms.checkbox canGate="update" :canResource="$settings" instantSave="instantSaveWebhookEnabled"
- id="webhookEnabled" label="Enabled" />
- </div>
<div class="flex items-end gap-2">
- <x-forms.input canGate="update" :canResource="$settings" type="password"
- helper="Enter a valid HTTP or HTTPS URL. Coolify will send POST requests to this endpoint when events occur."
- required id="webhookUrl" label="Webhook URL (POST)" />
+ @can('update', $settings)
+ <x-forms.input type="password"
+ helper="Enter a valid HTTP or HTTPS URL. Coolify will send POST requests to this endpoint when events occur."
+ required id="webhookUrl" label="Webhook URL (POST)" />
+ @else
+ <x-forms.input disabled
+ helper="Enter a valid HTTP or HTTPS URL. Coolify will send POST requests to this endpoint when events occur."
+ required label="Webhook URL (POST)" value="Hidden (only admins can view)" />
+ @endcan
</div>
</form>
<h2 class="mt-4">Notification Settings</h2>
diff --cc tests/Feature/Authorization/TeamAuthorizationTest.php
index 0000000000,e99e55a2c1..82d8d2afcc
mode 000000,100644..100644
--- a/tests/Feature/Authorization/TeamAuthorizationTest.php
+++ b/tests/Feature/Authorization/TeamAuthorizationTest.php
@@@ -1,0 -1,327 +1,327 @@@
+ <?php
+
+ use App\Livewire\Team\Index as TeamIndex;
+ use App\Livewire\Team\Member as TeamMember;
+ use App\Models\InstanceSettings;
+ use App\Models\Team;
+ use App\Models\User;
+ use Illuminate\Foundation\Testing\RefreshDatabase;
+ use Livewire\Livewire;
+
+ uses(RefreshDatabase::class);
+
+ beforeEach(function () {
+ InstanceSettings::updateOrCreate(['id' => 0]);
+
+ $this->team = Team::factory()->create(['personal_team' => false]);
+
+ $this->owner = User::factory()->create();
+ $this->owner->teams()->attach($this->team, ['role' => 'owner']);
+
+ $this->admin = User::factory()->create();
+ $this->admin->teams()->attach($this->team, ['role' => 'admin']);
+
+ $this->member = User::factory()->create();
+ $this->member->teams()->attach($this->team, ['role' => 'member']);
+ });
+
+ // --- Team Policy: update ---
+
+ test('owner can update team', function () {
+ $this->actingAs($this->owner);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('update', $this->team))->toBeTrue();
+ });
+
+ test('admin can update team', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('update', $this->team))->toBeTrue();
+ });
+
+ test('member cannot update team', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('update', $this->team))->toBeFalse();
+ });
+
+ // --- Team Policy: delete ---
+
+ test('owner can delete team', function () {
+ $this->actingAs($this->owner);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('delete', $this->team))->toBeTrue();
+ });
+
+ test('admin can delete team', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('delete', $this->team))->toBeTrue();
+ });
+
+ test('member cannot delete team', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('delete', $this->team))->toBeFalse();
+ });
+
+ // --- Team Policy: manageMembers ---
+
+ test('owner can manage team members', function () {
+ $this->actingAs($this->owner);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('manageMembers', $this->team))->toBeTrue();
+ });
+
+ test('admin can manage team members', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('manageMembers', $this->team))->toBeTrue();
+ });
+
+ test('member cannot manage team members', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('manageMembers', $this->team))->toBeFalse();
+ });
+
+ // --- Team Policy: manageInvitations ---
+
+ test('owner can manage invitations', function () {
+ $this->actingAs($this->owner);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('manageInvitations', $this->team))->toBeTrue();
+ });
+
+ test('admin can manage invitations', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('manageInvitations', $this->team))->toBeTrue();
+ });
+
+ test('member cannot manage invitations', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('manageInvitations', $this->team))->toBeFalse();
+ });
+
+ // --- Team Index Livewire: update ---
+
+ test('member cannot submit team settings via policy', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('update', $this->team))->toBeFalse();
+ });
+
+ // --- Team Index Livewire: delete ---
+
+ test('member cannot delete team via index', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ Livewire::test(TeamIndex::class)
+ ->call('delete', 'password')
+ ->assertDispatched('error');
+
+ expect(Team::find($this->team->id))->not->toBeNull();
+ });
+
+ test('admin can delete team via policy', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('delete', $this->team))->toBeTrue();
+ });
+
+ // --- Team Member Livewire: role changes ---
+
+ test('member cannot change roles via team member component', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ Livewire::test(TeamMember::class, ['member' => $this->admin])
+ ->call('makeAdmin')
+ ->assertDispatched('error');
+ });
+
+ test('member cannot remove team members', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ Livewire::test(TeamMember::class, ['member' => $this->admin])
+ ->call('remove')
+ ->assertDispatched('error');
+ });
+
+ // --- Invitations & Invite Link (policy checks — views wrapped in @can render empty for members) ---
+
+ test('member cannot manage invitations via policy', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('manageInvitations', $this->team))->toBeFalse();
+ });
+
+ test('owner can manage invitations via policy', function () {
+ $this->actingAs($this->owner);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('manageInvitations', $this->team))->toBeTrue();
+ });
+
+ // --- Cross-team isolation ---
+
+ test('user from different team cannot update team', function () {
+ $otherTeam = Team::factory()->create();
+ $otherUser = User::factory()->create();
+ $otherUser->teams()->attach($otherTeam, ['role' => 'owner']);
+
+ $this->actingAs($otherUser);
+ session(['currentTeam' => $otherTeam]);
+
+ expect(auth()->user()->can('update', $this->team))->toBeFalse();
+ });
+
+ test('user from different team cannot manage members', function () {
+ $otherTeam = Team::factory()->create();
+ $otherUser = User::factory()->create();
+ $otherUser->teams()->attach($otherTeam, ['role' => 'owner']);
+
+ $this->actingAs($otherUser);
+ session(['currentTeam' => $otherTeam]);
+
+ expect(auth()->user()->can('manageMembers', $this->team))->toBeFalse();
+ });
+
+ // --- Team Policy: view ---
+
+ test('owner can view team', function () {
+ $this->actingAs($this->owner);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('view', $this->team))->toBeTrue();
+ });
+
+ test('admin can view team', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('view', $this->team))->toBeTrue();
+ });
+
+ test('member can view team', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('view', $this->team))->toBeTrue();
+ });
+
+ test('non-team member cannot view team', function () {
+ $outsider = User::factory()->create();
+ $this->actingAs($outsider);
+ session(['currentTeam' => $this->team]);
+
+ expect($outsider->can('view', $this->team))->toBeFalse();
+ });
+
+ // --- Team Policy: viewAdmin ---
+
+ test('owner can view admin panel', function () {
+ $this->actingAs($this->owner);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('viewAdmin', $this->team))->toBeTrue();
+ });
+
+ test('admin can view admin panel', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('viewAdmin', $this->team))->toBeTrue();
+ });
+
+ test('member cannot view admin panel', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ expect(auth()->user()->can('viewAdmin', $this->team))->toBeFalse();
+ });
+
+ test('non-team member cannot view admin panel', function () {
+ $outsider = User::factory()->create();
+ $this->actingAs($outsider);
+ session(['currentTeam' => $this->team]);
+
+ expect($outsider->can('viewAdmin', $this->team))->toBeFalse();
+ });
+
+ // --- Non-team member isolation ---
+
+ test('non-team member cannot update team', function () {
+ $outsider = User::factory()->create();
+ $this->actingAs($outsider);
+ session(['currentTeam' => $this->team]);
+
+ expect($outsider->can('update', $this->team))->toBeFalse();
+ });
+
+ test('non-team member cannot delete team', function () {
+ $outsider = User::factory()->create();
+ $this->actingAs($outsider);
+ session(['currentTeam' => $this->team]);
+
+ expect($outsider->can('delete', $this->team))->toBeFalse();
+ });
+
+ test('non-team member cannot manage members', function () {
+ $outsider = User::factory()->create();
+ $this->actingAs($outsider);
+ session(['currentTeam' => $this->team]);
+
+ expect($outsider->can('manageMembers', $this->team))->toBeFalse();
+ });
+
+ test('non-team member cannot manage invitations', function () {
+ $outsider = User::factory()->create();
+ $this->actingAs($outsider);
+ session(['currentTeam' => $this->team]);
+
+ expect($outsider->can('manageInvitations', $this->team))->toBeFalse();
+ });
+
+ // --- Team creation and model-level protection ---
+
+ test('member can create a new independent team', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ $newTeam = Team::create([
+ 'name' => 'New Team',
+ 'description' => 'Created by member',
+ 'personal_team' => false,
+ ]);
+
+ expect($newTeam)->toBeInstanceOf(Team::class)
+ ->and($newTeam->name)->toBe('New Team');
+ });
+
+ test('member cannot update an existing team at model level', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ expect(fn () => $this->team->update(['name' => 'Hacked']))
- ->toThrow(\Exception::class, 'You are not allowed to update this team.');
++ ->toThrow(Exception::class, 'You are not allowed to update this team.');
+ });
diff --cc tests/Feature/Jobs/CheckTraefikVersionJobTest.php
index cee1564855,cee1564855..86ebd8d169
--- a/tests/Feature/Jobs/CheckTraefikVersionJobTest.php
+++ b/tests/Feature/Jobs/CheckTraefikVersionJobTest.php
@@@ -1,11 -1,11 +1,15 @@@
<?php
++use App\Jobs\CheckTraefikVersionForServerJob;
use App\Models\Server;
use App\Models\Team;
use App\Notifications\Server\TraefikVersionOutdated;
++use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Testing\RefreshDatabase;
++use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Notification;
++use Illuminate\Support\Facades\Schema;
uses(RefreshDatabase::class);
@@@ -14,7 -14,7 +18,7 @@@ beforeEach(function ()
});
it('detects servers table has detected_traefik_version column', function () {
-- expect(\Illuminate\Support\Facades\Schema::hasColumn('servers', 'detected_traefik_version'))->toBeTrue();
++ expect(Schema::hasColumn('servers', 'detected_traefik_version'))->toBeTrue();
});
it('server model casts detected_traefik_version as string', function () {
@@@ -137,7 -137,7 +141,7 @@@ it('notification channels can be retrie
});
it('traefik version check command exists', function () {
-- $commands = \Illuminate\Support\Facades\Artisan::all();
++ $commands = Artisan::all();
expect($commands)->toHaveKey('traefik:check-version');
});
@@@ -181,16 -181,16 +185,16 @@@ it('groups servers by team correctly',
});
it('server check job exists and has correct structure', function () {
-- expect(class_exists(\App\Jobs\CheckTraefikVersionForServerJob::class))->toBeTrue();
++ expect(class_exists(CheckTraefikVersionForServerJob::class))->toBeTrue();
// Verify CheckTraefikVersionForServerJob has required properties
-- $reflection = new \ReflectionClass(\App\Jobs\CheckTraefikVersionForServerJob::class);
++ $reflection = new ReflectionClass(CheckTraefikVersionForServerJob::class);
expect($reflection->hasProperty('tries'))->toBeTrue();
expect($reflection->hasProperty('timeout'))->toBeTrue();
// Verify it implements ShouldQueue
-- $interfaces = class_implements(\App\Jobs\CheckTraefikVersionForServerJob::class);
-- expect($interfaces)->toContain(\Illuminate\Contracts\Queue\ShouldQueue::class);
++ $interfaces = class_implements(CheckTraefikVersionForServerJob::class);
++ expect($interfaces)->toContain(ShouldQueue::class);
});
it('sends immediate notifications when outdated traefik is detected', function () {
diff --cc tests/Feature/Jobs/CoolifyTaskRetryTest.php
index 0000000000,46e652051a..8562319af8
mode 000000,100644..100644
--- a/tests/Feature/Jobs/CoolifyTaskRetryTest.php
+++ b/tests/Feature/Jobs/CoolifyTaskRetryTest.php
@@@ -1,0 -1,65 +1,65 @@@
+ <?php
+
+ use App\Enums\ProcessStatus;
+ use App\Jobs\CoolifyTask;
+ use App\Models\Server;
+ use App\Models\Team;
+ use Illuminate\Foundation\Testing\RefreshDatabase;
+
+ uses(RefreshDatabase::class);
+
+ beforeEach(function () {
+ $team = Team::factory()->create();
+ Server::factory()->create(['team_id' => $team->id]);
+
+ $this->activity = activity()
+ ->withProperties([
+ 'server_uuid' => Server::first()->uuid,
+ 'command' => 'echo "test"',
+ 'type' => 'inline',
+ 'status' => ProcessStatus::QUEUED->value,
+ ])
+ ->event('inline')
+ ->log('[]');
+
+ $this->job = new CoolifyTask(
+ activity: $this->activity,
+ ignore_errors: false,
+ call_event_on_finish: null,
+ call_event_data: null,
+ );
+ });
+
+ test('has correct retry configuration', function () {
+ expect($this->job->tries)->toBe(3)
+ ->and($this->job->maxExceptions)->toBe(1)
+ ->and($this->job->timeout)->toBe(600)
+ ->and($this->job->backoff())->toBe([30, 90, 180]);
+ });
+
+ test('is queued on the high priority queue', function () {
+ expect($this->job->queue)->toBe('high');
+ });
+
+ test('marks activity as error on permanent failure', function () {
- $exception = new \RuntimeException('SSH connection failed');
++ $exception = new RuntimeException('SSH connection failed');
+
+ $this->job->failed($exception);
+
+ $this->activity->refresh();
+ $properties = $this->activity->properties;
+
+ expect($properties['status'])->toBe(ProcessStatus::ERROR->value)
+ ->and($properties['error'])->toBe('SSH connection failed')
+ ->and($properties)->toHaveKey('failed_at');
+ });
+
+ test('marks activity as error with default message when exception is null', function () {
+ $this->job->failed(null);
+
+ $this->activity->refresh();
+ $properties = $this->activity->properties;
+
+ expect($properties['status'])->toBe(ProcessStatus::ERROR->value)
+ ->and($properties['error'])->toBe('Job permanently failed');
+ });
diff --cc tests/Feature/Proxy/RestartProxyTest.php
index 5771a58f7c,2c30c98356..f4bad63eb6
--- a/tests/Feature/Proxy/RestartProxyTest.php
+++ b/tests/Feature/Proxy/RestartProxyTest.php
@@@ -1,139 -1,90 +1,91 @@@
<?php
- namespace Tests\Feature\Proxy;
-
- use App\Jobs\RestartProxyJob;
++use App\Enums\ProxyTypes;
+ use App\Models\InstanceSettings;
use App\Models\Server;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
- use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;
- use Tests\TestCase;
- class RestartProxyTest extends TestCase
+ uses(RefreshDatabase::class);
+
+ beforeEach(function () {
+ InstanceSettings::create(['id' => 0]);
+ });
+
+ function setupProxyUser(string $role): array
{
- use RefreshDatabase;
+ $team = Team::factory()->create();
+ $user = User::factory()->create();
+ $user->teams()->attach($team, ['role' => $role]);
- protected User $user;
+ $server = Server::factory()->create([
+ 'team_id' => $team->id,
+ 'name' => 'Test Server',
+ 'ip' => '192.168.1.100',
+ ]);
- protected Team $team;
+ return [$user, $team, $server];
+ }
- protected Server $server;
-
- protected function setUp(): void
- {
- parent::setUp();
-
- // Create test user and team
- $this->user = User::factory()->create();
- $this->team = Team::factory()->create(['name' => 'Test Team']);
- $this->user->teams()->attach($this->team);
-
- // Create test server
- $this->server = Server::factory()->create([
- 'team_id' => $this->team->id,
- 'name' => 'Test Server',
- 'ip' => '192.168.1.100',
- ]);
-
- // Authenticate user
- $this->actingAs($this->user);
- }
-
- public function test_restart_dispatches_job_for_all_servers()
- {
- Queue::fake();
-
- Livewire::test('server.navbar', ['server' => $this->server])
- ->call('restart');
-
- // Assert job was dispatched
- Queue::assertPushed(RestartProxyJob::class, function ($job) {
- return $job->server->id === $this->server->id;
- });
- }
-
- public function test_restart_dispatches_job_for_localhost_server()
- {
- Queue::fake();
-
- // Create localhost server (id = 0)
- $localhostServer = Server::factory()->create([
- 'id' => 0,
- 'team_id' => $this->team->id,
- 'name' => 'Localhost',
- 'ip' => 'host.docker.internal',
- ]);
-
- Livewire::test('server.navbar', ['server' => $localhostServer])
- ->call('restart');
-
- // Assert job was dispatched
- Queue::assertPushed(RestartProxyJob::class, function ($job) use ($localhostServer) {
- return $job->server->id === $localhostServer->id;
- });
- }
-
- public function test_restart_shows_info_message()
- {
- Queue::fake();
-
- Livewire::test('server.navbar', ['server' => $this->server])
- ->call('restart')
- ->assertDispatched('info', 'Proxy restart initiated. Monitor progress in activity logs.');
- }
-
- public function test_unauthorized_user_cannot_restart_proxy()
- {
- Queue::fake();
-
- // Create another user without access
- $unauthorizedUser = User::factory()->create();
- $this->actingAs($unauthorizedUser);
-
- Livewire::test('server.navbar', ['server' => $this->server])
- ->call('restart')
- ->assertForbidden();
-
- // Assert job was NOT dispatched
- Queue::assertNotPushed(RestartProxyJob::class);
- }
-
- public function test_restart_prevents_concurrent_jobs_via_without_overlapping()
- {
- Queue::fake();
-
- // Dispatch job twice
- Livewire::test('server.navbar', ['server' => $this->server])
- ->call('restart');
-
- Livewire::test('server.navbar', ['server' => $this->server])
- ->call('restart');
-
- // Assert job was pushed twice (WithoutOverlapping middleware will handle deduplication)
- Queue::assertPushed(RestartProxyJob::class, 2);
-
- // Get the jobs
- $jobs = Queue::pushed(RestartProxyJob::class);
-
- // Verify both jobs have WithoutOverlapping middleware
- foreach ($jobs as $job) {
- $middleware = $job['job']->middleware();
- $this->assertCount(1, $middleware);
- $this->assertInstanceOf(\Illuminate\Queue\Middleware\WithoutOverlapping::class, $middleware[0]);
- }
- }
-
- public function test_restart_uses_server_team_id()
- {
- Queue::fake();
-
- Livewire::test('server.navbar', ['server' => $this->server])
- ->call('restart');
-
- Queue::assertPushed(RestartProxyJob::class, function ($job) {
- return $job->server->team_id === $this->team->id;
- });
- }
+ function makeServerProxyRunning(Server $server): void
+ {
+ $server->settings()->update([
+ 'is_reachable' => true,
+ 'is_usable' => true,
+ ]);
+ $server->proxy->status = 'running';
- $server->proxy->type = \App\Enums\ProxyTypes::TRAEFIK->value;
++ $server->proxy->type = ProxyTypes::TRAEFIK->value;
+ $server->save();
+ $server->refresh();
}
+
+ test('member cannot see proxy restart and stop buttons', function () {
+ [$user, $team, $server] = setupProxyUser('member');
+ makeServerProxyRunning($server);
+
+ // Mock proxySet to bypass SQLite boolean casting issue with force_disabled
+ $mock = Mockery::mock($server)->makePartial();
+ $mock->shouldReceive('proxySet')->andReturn(true);
+
+ $this->actingAs($user);
+ session(['currentTeam' => $team]);
+
+ Livewire::test('server.navbar', ['server' => $mock])
+ ->assertDontSee('Restart Proxy')
+ ->assertDontSee('Stop Proxy');
+ });
+
+ test('admin can see proxy restart and stop buttons', function () {
+ [$user, $team, $server] = setupProxyUser('admin');
+ makeServerProxyRunning($server);
+
+ $mock = Mockery::mock($server)->makePartial();
+ $mock->shouldReceive('proxySet')->andReturn(true);
+
+ $this->actingAs($user);
+ session(['currentTeam' => $team]);
+
+ Livewire::test('server.navbar', ['server' => $mock])
+ ->assertSee('Restart Proxy')
+ ->assertSee('Stop Proxy');
+ });
+
+ test('member cannot see start proxy button', function () {
+ [$user, $team, $server] = setupProxyUser('member');
+
+ $server->proxy->status = 'exited';
- $server->proxy->type = \App\Enums\ProxyTypes::TRAEFIK->value;
++ $server->proxy->type = ProxyTypes::TRAEFIK->value;
+ $server->save();
+ $server->refresh();
+
+ $mock = Mockery::mock($server)->makePartial();
+ $mock->shouldReceive('proxySet')->andReturn(true);
+
+ $this->actingAs($user);
+ session(['currentTeam' => $team]);
+
+ Livewire::test('server.navbar', ['server' => $mock])
+ ->assertDontSee('Start Proxy');
+ });
diff --cc tests/Feature/Security/IpAllowlistTest.php
index 1b14b79e86,1b14b79e86..a95f1566b2
--- a/tests/Feature/Security/IpAllowlistTest.php
+++ b/tests/Feature/Security/IpAllowlistTest.php
@@@ -1,5 -1,5 +1,7 @@@
<?php
++use App\Rules\ValidIpOrCidr;
++
test('IP allowlist with single IPs', function () {
$testCases = [
['ip' => '192.168.1.100', 'allowlist' => ['192.168.1.100'], 'expected' => true],
@@@ -200,7 -200,7 +202,7 @@@ test('IP allowlist comma-separated stri
});
test('ValidIpOrCidr validation rule', function () {
-- $rule = new \App\Rules\ValidIpOrCidr;
++ $rule = new ValidIpOrCidr;
// Helper function to test validation
$validate = function ($value) use ($rule) {
@@@ -248,7 -248,7 +250,7 @@@
});
test('ValidIpOrCidr validation rule error messages', function () {
-- $rule = new \App\Rules\ValidIpOrCidr;
++ $rule = new ValidIpOrCidr;
// Helper function to get error message
$getError = function ($value) use ($rule) {
diff --cc tests/Feature/Security/TrustHostsMiddlewareTest.php
index 0000000000,5c60b30d68..9a44be14bc
mode 000000,100644..100644
--- a/tests/Feature/Security/TrustHostsMiddlewareTest.php
+++ b/tests/Feature/Security/TrustHostsMiddlewareTest.php
@@@ -1,0 -1,360 +1,361 @@@
+ <?php
+
+ use App\Http\Middleware\TrustHosts;
+ use App\Models\InstanceSettings;
++use Illuminate\Foundation\Testing\RefreshDatabase;
+ use Illuminate\Support\Facades\Cache;
+
-uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);
++uses(RefreshDatabase::class);
+
+ beforeEach(function () {
+ // Clear cache before each test to ensure isolation
+ Cache::forget('instance_settings_fqdn_host');
+ });
+
+ it('trusts the configured FQDN from InstanceSettings', function () {
+ // Create instance settings with FQDN
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://coolify.example.com']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ expect($hosts)->toContain('coolify.example.com');
+ });
+
+ it('rejects password reset request with malicious host header', function () {
+ // Set up instance settings with legitimate FQDN
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://coolify.example.com']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ // The malicious host should NOT be in the trusted hosts
+ expect($hosts)->not->toContain('coolify.example.com.evil.com');
+ expect($hosts)->toContain('coolify.example.com');
+ });
+
+ it('handles missing FQDN gracefully', function () {
+ // Create instance settings without FQDN
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => null]
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ // Should still return APP_URL pattern without throwing
+ expect($hosts)->not->toBeEmpty();
+ });
+
+ it('filters out null and empty values from trusted hosts', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => '']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ // Should not contain empty strings or null
+ foreach ($hosts as $host) {
+ if ($host !== null) {
+ expect($host)->not->toBeEmpty();
+ }
+ }
+ });
+
+ it('extracts host from FQDN with protocol and port', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://coolify.example.com:8443']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ expect($hosts)->toContain('coolify.example.com');
+ });
+
+ it('handles exception during InstanceSettings fetch', function () {
+ // Drop the instance_settings table to simulate installation
- \Schema::dropIfExists('instance_settings');
++ Schema::dropIfExists('instance_settings');
+
+ $middleware = new TrustHosts($this->app);
+
+ // Should not throw an exception
+ $hosts = $middleware->hosts();
+
+ expect($hosts)->not->toBeEmpty();
+ });
+
+ it('trusts IP addresses with port', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'http://65.21.3.91:8000']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ expect($hosts)->toContain('65.21.3.91');
+ });
+
+ it('trusts IP addresses without port', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'http://192.168.1.100']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ expect($hosts)->toContain('192.168.1.100');
+ });
+
+ it('rejects malicious host when using IP address', function () {
+ // Simulate an instance using IP address
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'http://65.21.3.91:8000']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ // The malicious host attempting to mimic the IP should NOT be trusted
+ expect($hosts)->not->toContain('65.21.3.91.evil.com');
+ expect($hosts)->not->toContain('evil.com');
+ expect($hosts)->toContain('65.21.3.91');
+ });
+
+ it('trusts IPv6 addresses', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'http://[2001:db8::1]:8000']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ // IPv6 addresses are enclosed in brackets, getHost() should handle this
+ expect($hosts)->toContain('[2001:db8::1]');
+ });
+
+ it('invalidates cache when FQDN is updated', function () {
+ // Set initial FQDN
+ $settings = InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://old-domain.com']
+ );
+
+ // First call should cache it
+ $middleware = new TrustHosts($this->app);
+ $hosts1 = $middleware->hosts();
+ expect($hosts1)->toContain('old-domain.com');
+
+ // Verify cache exists
+ expect(Cache::has('instance_settings_fqdn_host'))->toBeTrue();
+
+ // Update FQDN - should trigger cache invalidation
+ $settings->fqdn = 'https://new-domain.com';
+ $settings->save();
+
+ // Cache should be cleared
+ expect(Cache::has('instance_settings_fqdn_host'))->toBeFalse();
+
+ // New call should return updated host
+ $middleware2 = new TrustHosts($this->app);
+ $hosts2 = $middleware2->hosts();
+ expect($hosts2)->toContain('new-domain.com');
+ expect($hosts2)->not->toContain('old-domain.com');
+ });
+
+ it('caches trusted hosts to avoid database queries on every request', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://coolify.example.com']
+ );
+
+ // Clear cache first
+ Cache::forget('instance_settings_fqdn_host');
+
+ // First call - should query database and cache result
+ $middleware1 = new TrustHosts($this->app);
+ $hosts1 = $middleware1->hosts();
+
+ // Verify result is cached
+ expect(Cache::has('instance_settings_fqdn_host'))->toBeTrue();
+ expect(Cache::get('instance_settings_fqdn_host'))->toBe('coolify.example.com');
+
+ // Subsequent calls should use cache (no DB query)
+ $middleware2 = new TrustHosts($this->app);
+ $hosts2 = $middleware2->hosts();
+
+ expect($hosts1)->toBe($hosts2);
+ expect($hosts2)->toContain('coolify.example.com');
+ });
+
+ it('caches negative results when no FQDN is configured', function () {
+ // Create instance settings without FQDN
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => null]
+ );
+
+ // Clear cache first
+ Cache::forget('instance_settings_fqdn_host');
+
+ // First call - should query database and cache empty string sentinel
+ $middleware1 = new TrustHosts($this->app);
+ $hosts1 = $middleware1->hosts();
+
+ // Verify empty string sentinel is cached (not null, which wouldn't be cached)
+ expect(Cache::has('instance_settings_fqdn_host'))->toBeTrue();
+ expect(Cache::get('instance_settings_fqdn_host'))->toBe('');
+
+ // Subsequent calls should use cached sentinel value
+ $middleware2 = new TrustHosts($this->app);
+ $hosts2 = $middleware2->hosts();
+
+ expect($hosts1)->toBe($hosts2);
+ // Should only contain APP_URL pattern, not any FQDN
+ expect($hosts2)->not->toBeEmpty();
+ });
+
+ it('skips host validation for terminal auth routes', function () {
+ // These routes should be accessible with any Host header (for internal container communication)
+ $response = $this->postJson('/terminal/auth', [], [
+ 'Host' => 'coolify:8080', // Internal Docker host
+ ]);
+
+ // Should not get 400 Bad Host (might get 401 Unauthorized instead)
+ expect($response->status())->not->toBe(400);
+ });
+
+ it('skips host validation for terminal auth ips route', function () {
+ // These routes should be accessible with any Host header (for internal container communication)
+ $response = $this->postJson('/terminal/auth/ips', [], [
+ 'Host' => 'soketi:6002', // Another internal Docker host
+ ]);
+
+ // Should not get 400 Bad Host (might get 401 Unauthorized instead)
+ expect($response->status())->not->toBe(400);
+ });
+
+ it('still enforces host validation for non-terminal routes', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://coolify.example.com']
+ );
+
+ // Regular routes should still validate Host header
+ $response = $this->get('/', [
+ 'Host' => 'evil.com',
+ ]);
+
+ // Should get 400 Bad Host for untrusted host
+ expect($response->status())->toBe(400);
+ });
+
+ it('skips host validation for API routes', function () {
+ // All API routes use token-based auth (Sanctum), not host validation
+ // They should be accessible from any host (mobile apps, CLI tools, scripts)
+
+ // Test health check endpoint
+ $response = $this->get('/api/health', [
+ 'Host' => 'internal-lb.local',
+ ]);
+ expect($response->status())->not->toBe(400);
+
+ // Test v1 health check
+ $response = $this->get('/api/v1/health', [
+ 'Host' => '10.0.0.5',
+ ]);
+ expect($response->status())->not->toBe(400);
+
+ // Test feedback endpoint
+ $response = $this->post('/api/feedback', [], [
+ 'Host' => 'mobile-app.local',
+ ]);
+ expect($response->status())->not->toBe(400);
+ });
+
+ it('trusts localhost when FQDN is configured', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://coolify.example.com']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ expect($hosts)->toContain('localhost');
+ });
+
+ it('trusts 127.0.0.1 when FQDN is configured', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://coolify.example.com']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ expect($hosts)->toContain('127.0.0.1');
+ });
+
+ it('trusts IPv6 loopback when FQDN is configured', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://coolify.example.com']
+ );
+
+ $middleware = new TrustHosts($this->app);
+ $hosts = $middleware->hosts();
+
+ expect($hosts)->toContain('[::1]');
+ });
+
+ it('allows local access via localhost when FQDN is configured and request uses localhost host header', function () {
+ InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['fqdn' => 'https://coolify.example.com']
+ );
+
+ $response = $this->get('/', [
+ 'Host' => 'localhost',
+ ]);
+
+ // Should NOT be rejected as untrusted host (would be 400)
+ expect($response->status())->not->toBe(400);
+ });
+
+ it('skips host validation for webhook endpoints', function () {
+ // All webhook routes are under /webhooks/* prefix (see RouteServiceProvider)
+ // and use cryptographic signature validation instead of host validation
+
+ // Test GitHub webhook
+ $response = $this->post('/webhooks/source/github/events', [], [
+ 'Host' => 'github-webhook-proxy.local',
+ ]);
+ expect($response->status())->not->toBe(400);
+
+ // Test GitLab webhook
+ $response = $this->post('/webhooks/source/gitlab/events/manual', [], [
+ 'Host' => 'gitlab.example.com',
+ ]);
+ expect($response->status())->not->toBe(400);
+
+ // Test Stripe webhook
+ $response = $this->post('/webhooks/payments/stripe/events', [], [
+ 'Host' => 'stripe-webhook-forwarder.local',
+ ]);
+ expect($response->status())->not->toBe(400);
+ });
diff --cc tests/Pest.php
index cec77b86f4,67bcbda81e..81df3649b1
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@@ -2,6 -2,6 +2,7 @@@
use App\Models\Server;
use Illuminate\Support\Once;
++use Tests\TestCase;
/*
|--------------------------------------------------------------------------
@@@ -13,7 -13,7 +14,7 @@@
| need to change it using the "uses()" function to bind a different classes or traits.
|
*/
--uses(Tests\TestCase::class)->in('Feature', 'v4/Feature', 'v4/Browser');
++uses(TestCase::class)->in('Feature', 'v4/Feature', 'v4/Browser');
/*
|--------------------------------------------------------------------------