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.

fix(settings): harden OIDC, email, and log drain flows

Andras Bacsai21333f02f9b5
diff --git a/app/Auth/Oidc/OidcConfig.php b/app/Auth/Oidc/OidcConfig.php
index 93a88868aa..04cb4effe5 100644
--- a/app/Auth/Oidc/OidcConfig.php
+++ b/app/Auth/Oidc/OidcConfig.php
@@ -28,7 +28,7 @@ final readonly class OidcConfig
redirectUri: filled($setting->redirect_uri) ? $setting->redirect_uri : route('auth.callback', 'oidc'),
scopes: $setting->scopeList(),
usePkce: $setting->use_pkce ?? true,
- clockSkewSeconds: $setting->clock_skew_seconds ?: 60,
+ clockSkewSeconds: $setting->clock_skew_seconds ?? 60,
);
}
}
diff --git a/app/Auth/Oidc/OidcDiscoveryService.php b/app/Auth/Oidc/OidcDiscoveryService.php
index 0d35ff45cb..3a39f33cfd 100644
--- a/app/Auth/Oidc/OidcDiscoveryService.php
+++ b/app/Auth/Oidc/OidcDiscoveryService.php
@@ -12,6 +12,8 @@ class OidcDiscoveryService
{
public function discover(string $issuerUrl): OidcDiscoveryDocument
{
+ $this->assertHttpsUrl($issuerUrl, new OidcDiscoveryException('Issuer URL must be an absolute HTTPS URL.'));
+
$issuerUrl = rtrim($issuerUrl, '/');
$cacheKey = 'oidc:discovery:'.hash('sha256', $issuerUrl);
@@ -49,6 +51,8 @@ class OidcDiscoveryService
*/
public function jwks(string $jwksUri): array
{
+ $this->assertHttpsUrl($jwksUri, new OidcJwksException('JWKS URI must be an absolute HTTPS URL.'));
+
$cacheKey = 'oidc:jwks:'.hash('sha256', $jwksUri);
return Cache::remember($cacheKey, 21600, function () use ($jwksUri): array {
@@ -70,4 +74,13 @@ class OidcDiscoveryService
return $json;
});
}
+
+ private function assertHttpsUrl(string $url, Throwable $exception): void
+ {
+ $parts = parse_url($url);
+
+ if (($parts['scheme'] ?? null) !== 'https' || ! is_string($parts['host'] ?? null) || $parts['host'] === '') {
+ throw $exception;
+ }
+ }
}
diff --git a/app/Auth/Oidc/OidcTokenValidator.php b/app/Auth/Oidc/OidcTokenValidator.php
index 98dc6d4c00..ee13cf712e 100644
--- a/app/Auth/Oidc/OidcTokenValidator.php
+++ b/app/Auth/Oidc/OidcTokenValidator.php
@@ -41,10 +41,22 @@ class OidcTokenValidator
$this->assertAudience($claims, $clientId);
$this->assertTimestamps($claims, $clockSkewSeconds);
$this->assertNonce($claims, $expectedNonce);
+ $this->assertSubject($claims);
return $claims;
}
+ /**
+ * @param array<string, mixed> $claims
+ */
+ private function assertSubject(array $claims): void
+ {
+ $subject = $claims['sub'] ?? null;
+ if (! is_string($subject) || $subject === '') {
+ throw new OidcTokenException('id_token subject is missing or invalid.');
+ }
+ }
+
/**
* @return array{0: array<string, mixed>, 1: array<string, mixed>, 2: string, 3: string}
*/
@@ -104,6 +116,10 @@ class OidcTokenValidator
throw new OidcTokenException('id_token audience does not include configured client id.');
}
+ if (count($audience) > 1 && (! isset($claims['azp']) || $claims['azp'] !== $clientId)) {
+ throw new OidcTokenException('id_token azp is required when aud contains multiple values and must match configured client id.');
+ }
+
if (isset($claims['azp']) && $claims['azp'] !== $clientId) {
throw new OidcTokenException('id_token azp does not match configured client id.');
}
diff --git a/app/Auth/Oidc/Socialite/OidcProvider.php b/app/Auth/Oidc/Socialite/OidcProvider.php
index 65a476d45d..34bb2a1124 100644
--- a/app/Auth/Oidc/Socialite/OidcProvider.php
+++ b/app/Auth/Oidc/Socialite/OidcProvider.php
@@ -18,6 +18,8 @@ use Laravel\Socialite\Two\ProviderInterface;
class OidcProvider extends AbstractProvider implements ProviderInterface
{
+ private const int OIDC_FLOW_TTL_MINUTES = 10;
+
/**
* @var array<int, string>
*/
@@ -65,12 +67,12 @@ class OidcProvider extends AbstractProvider implements ProviderInterface
{
$config = $this->getConfig();
$nonce = Str::random(40);
- $this->request->session()->put($this->nonceSessionKey(), $nonce);
+ $this->putOidcFlowValue($this->nonceSessionKey($state), $nonce);
$extra = ['nonce' => $nonce];
if ($config->usePkce) {
$verifier = $this->generateCodeVerifier();
- $this->request->session()->put($this->verifierSessionKey(), $verifier);
+ $this->putOidcFlowValue($this->verifierSessionKey($state), $verifier);
$extra['code_challenge'] = $this->codeChallenge($verifier);
$extra['code_challenge_method'] = 'S256';
}
@@ -94,6 +96,8 @@ class OidcProvider extends AbstractProvider implements ProviderInterface
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$token,
],
+ RequestOptions::CONNECT_TIMEOUT => 5,
+ RequestOptions::TIMEOUT => 10,
]);
$decoded = json_decode((string) $response->getBody(), true);
@@ -135,12 +139,17 @@ class OidcProvider extends AbstractProvider implements ProviderInterface
$discovery = $this->resolveDiscovery();
$config = $this->getConfig();
+ $expectedNonce = $this->pullOidcFlowValue($this->nonceSessionKey((string) $this->request->input('state')));
+ if ($expectedNonce === null) {
+ throw new OidcException('OIDC login session expired. Please try again.');
+ }
+
$claims = $this->tokenValidator->validate(
idToken: $idToken,
discovery: $discovery,
jwks: $this->discoveryService->jwks($discovery->jwksUri),
clientId: $config->clientId,
- expectedNonce: $this->request->session()->pull($this->nonceSessionKey()),
+ expectedNonce: $expectedNonce,
clockSkewSeconds: $config->clockSkewSeconds,
);
@@ -164,8 +173,8 @@ class OidcProvider extends AbstractProvider implements ProviderInterface
{
$fields = $this->getTokenFields($code);
if ($this->getConfig()->usePkce) {
- $verifier = $this->request->session()->pull($this->verifierSessionKey());
- if (is_string($verifier) && $verifier !== '') {
+ $verifier = $this->pullOidcFlowValue($this->verifierSessionKey((string) $this->request->input('state')));
+ if ($verifier !== null) {
$fields['code_verifier'] = $verifier;
}
}
@@ -173,6 +182,8 @@ class OidcProvider extends AbstractProvider implements ProviderInterface
$response = $this->getHttpClient()->post($this->getTokenUrl(), [
RequestOptions::HEADERS => ['Accept' => 'application/json'],
RequestOptions::FORM_PARAMS => $fields,
+ RequestOptions::CONNECT_TIMEOUT => 5,
+ RequestOptions::TIMEOUT => 10,
]);
$decoded = json_decode((string) $response->getBody(), true);
@@ -209,13 +220,43 @@ class OidcProvider extends AbstractProvider implements ProviderInterface
return $name === '' ? null : $name;
}
- protected function nonceSessionKey(): string
+ protected function putOidcFlowValue(string $key, string $value): void
+ {
+ $this->request->session()->put($key, [
+ 'value' => $value,
+ 'expires_at' => now()->addMinutes(self::OIDC_FLOW_TTL_MINUTES)->timestamp,
+ ]);
+ }
+
+ protected function pullOidcFlowValue(string $key): ?string
+ {
+ $entry = $this->request->session()->pull($key);
+
+ if (! is_array($entry)) {
+ return null;
+ }
+
+ $value = $entry['value'] ?? null;
+ $expiresAt = $entry['expires_at'] ?? null;
+
+ if (! is_string($value) || $value === '' || ! is_int($expiresAt)) {
+ return null;
+ }
+
+ if ($expiresAt < now()->timestamp) {
+ return null;
+ }
+
+ return $value;
+ }
+
+ protected function nonceSessionKey(string $state): string
{
- return 'oidc.nonce';
+ return "oidc.nonce.{$state}";
}
- protected function verifierSessionKey(): string
+ protected function verifierSessionKey(string $state): string
{
- return 'oidc.code_verifier';
+ return "oidc.code_verifier.{$state}";
}
}
diff --git a/app/Livewire/Notifications/Discord.php b/app/Livewire/Notifications/Discord.php
index 845c25a540..c29bcbb1b1 100644
--- a/app/Livewire/Notifications/Discord.php
+++ b/app/Livewire/Notifications/Discord.php
@@ -163,7 +163,7 @@ class Discord extends Component
}
}
- public function toggleDiscordEnabled()
+ public function toggleDiscordEnabled(): void
{
try {
$this->resetErrorBag();
@@ -183,7 +183,7 @@ class Discord extends Component
} catch (\Throwable $e) {
$this->syncData();
- return handleError($e, $this);
+ handleError($e, $this);
}
}
diff --git a/app/Livewire/Notifications/Telegram.php b/app/Livewire/Notifications/Telegram.php
index ebb49e0a93..7d11cc7252 100644
--- a/app/Livewire/Notifications/Telegram.php
+++ b/app/Livewire/Notifications/Telegram.php
@@ -246,7 +246,7 @@ class Telegram extends Component
}
}
- public function toggleTelegramEnabled()
+ public function toggleTelegramEnabled(): void
{
try {
$this->resetErrorBag();
@@ -268,7 +268,7 @@ class Telegram extends Component
} catch (\Throwable $e) {
$this->syncData();
- return handleError($e, $this);
+ handleError($e, $this);
} finally {
$this->dispatch('refresh');
}
diff --git a/app/Livewire/Server/LogDrains.php b/app/Livewire/Server/LogDrains.php
index 18d07ea905..58ca7b71bd 100644
--- a/app/Livewire/Server/LogDrains.php
+++ b/app/Livewire/Server/LogDrains.php
@@ -177,8 +177,12 @@ class LogDrains extends Component
}
}
- public function toggleLogDrain(string $type)
+ public function toggleLogDrain(string $type): void
{
+ $previousNewRelicEnabled = $this->server->settings->is_logdrain_newrelic_enabled;
+ $previousAxiomEnabled = $this->server->settings->is_logdrain_axiom_enabled;
+ $previousCustomEnabled = $this->server->settings->is_logdrain_custom_enabled;
+
try {
$this->authorize('update', $this->server);
$this->resetErrorBag();
@@ -204,9 +208,15 @@ class LogDrains extends Component
$this->dispatch('success', 'Log drain service stopped.');
}
} catch (\Throwable $e) {
+ // Restore the previously persisted enabled flags so the UI/DB never
+ // claim a runtime state that the Start/StopLogDrain action failed to apply.
+ $this->server->settings->is_logdrain_newrelic_enabled = $previousNewRelicEnabled;
+ $this->server->settings->is_logdrain_axiom_enabled = $previousAxiomEnabled;
+ $this->server->settings->is_logdrain_custom_enabled = $previousCustomEnabled;
+ $this->server->settings->save();
$this->syncData();
- return handleError($e, $this);
+ handleError($e, $this);
}
}
diff --git a/app/Livewire/SettingsEmail.php b/app/Livewire/SettingsEmail.php
index 9e00936059..a7b1c605f8 100644
--- a/app/Livewire/SettingsEmail.php
+++ b/app/Livewire/SettingsEmail.php
@@ -187,6 +187,10 @@ class SettingsEmail extends Component
try {
$this->validateSmtpSettings();
+ if ($this->smtpEnabled) {
+ $this->settings->resend_enabled = $this->resendEnabled = false;
+ }
+
$this->settings->smtp_enabled = $this->smtpEnabled;
$this->settings->smtp_host = $this->smtpHost;
$this->settings->smtp_port = $this->smtpPort;
@@ -212,6 +216,10 @@ class SettingsEmail extends Component
try {
$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;
$this->settings->smtp_from_address = $this->smtpFromAddress;
diff --git a/app/Livewire/SettingsOauth.php b/app/Livewire/SettingsOauth.php
index 24eddfaf9b..a3025f5938 100644
--- a/app/Livewire/SettingsOauth.php
+++ b/app/Livewire/SettingsOauth.php
@@ -2,11 +2,15 @@
namespace App\Livewire;
+use App\Models\InstanceSettings;
use App\Models\OauthSetting;
+use Illuminate\Validation\ValidationException;
use Livewire\Component;
class SettingsOauth extends Component
{
+ public InstanceSettings $settings;
+
public $oauth_settings_map;
public ?string $selectedProvider = null;
@@ -54,8 +58,9 @@ class SettingsOauth extends Component
return redirect()->route('home');
}
+ $this->settings = instanceSettings();
$this->selectedProvider = $provider;
- $this->disable_registration_when_oauth_enabled = (bool) instanceSettings()->disable_registration_when_oauth_enabled;
+ $this->disable_registration_when_oauth_enabled = (bool) $this->settings->disable_registration_when_oauth_enabled;
$this->oauth_settings_map = OauthSetting::all()->sortBy('provider')->reduce(function ($carry, $setting) {
$carry[$setting->provider] = $this->oauthSettingToArray($setting);
@@ -271,10 +276,23 @@ class SettingsOauth extends Component
public function submit(): void
{
- $this->updateOauthSettings($this->selectedProvider);
+ try {
+ $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);
+ }
+ }
- if ($this->selectedProvider === null) {
- $this->dispatch('success', 'Instance settings updated successfully!');
+ handleError($e, $this);
}
}
}
diff --git a/app/Services/Auth/OauthLoginService.php b/app/Services/Auth/OauthLoginService.php
index feb36211c0..25c9c465b2 100644
--- a/app/Services/Auth/OauthLoginService.php
+++ b/app/Services/Auth/OauthLoginService.php
@@ -18,8 +18,8 @@ class OauthLoginService
public function login(string $provider, object $oauthUser, OauthSetting $oauthSetting): User
{
$email = strtolower(trim((string) $oauthUser->email));
- if ($email === '') {
- throw new HttpException(403, 'OAuth provider did not return an email address');
+ if ($email === '' || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
+ throw new HttpException(403, 'OAuth provider did not return a valid email address');
}
$user = $provider === 'oidc'
diff --git a/resources/views/livewire/server/log-drains.blade.php b/resources/views/livewire/server/log-drains.blade.php
index a36d2febd9..1d1bd9838c 100644
--- a/resources/views/livewire/server/log-drains.blade.php
+++ b/resources/views/livewire/server/log-drains.blade.php
@@ -25,7 +25,7 @@
Disable New Relic
</x-forms.button>
@elseif ($isLogDrainAxiomEnabled || $isLogDrainCustomEnabled)
- <x-forms.button disabled>
+ <x-forms.button canGate="update" :canResource="$server" disabled>
Enable New Relic
</x-forms.button>
@else
@@ -72,7 +72,7 @@
Disable Axiom
</x-forms.button>
@elseif ($isLogDrainNewRelicEnabled || $isLogDrainCustomEnabled)
- <x-forms.button disabled>
+ <x-forms.button canGate="update" :canResource="$server" disabled>
Enable Axiom
</x-forms.button>
@else
@@ -113,7 +113,7 @@
Disable Custom FluentBit
</x-forms.button>
@elseif ($isLogDrainNewRelicEnabled || $isLogDrainAxiomEnabled)
- <x-forms.button disabled>
+ <x-forms.button canGate="update" :canResource="$server" disabled>
Enable Custom FluentBit
</x-forms.button>
@else
diff --git a/resources/views/livewire/settings-email.blade.php b/resources/views/livewire/settings-email.blade.php
index eb9cb1b6b0..2b07bc713d 100644
--- a/resources/views/livewire/settings-email.blade.php
+++ b/resources/views/livewire/settings-email.blade.php
@@ -36,14 +36,14 @@
<div class="flex items-center gap-2">
<h3>SMTP Server</h3>
@if ($smtpEnabled)
- <x-forms.button type="submit">
+ <x-forms.button canGate="update" :canResource="$settings" type="submit">
Save
</x-forms.button>
- <x-forms.button wire:click="toggleSmtp">
+ <x-forms.button canGate="update" :canResource="$settings" wire:click="toggleSmtp">
Disable SMTP Server
</x-forms.button>
@else
- <x-forms.button isHighlighted wire:click="toggleSmtp">
+ <x-forms.button canGate="update" :canResource="$settings" isHighlighted wire:click="toggleSmtp">
Enable SMTP Server
</x-forms.button>
@endif
@@ -70,14 +70,14 @@
<div class="flex items-center gap-2">
<h3>Resend</h3>
@if ($resendEnabled)
- <x-forms.button type="submit">
+ <x-forms.button canGate="update" :canResource="$settings" type="submit">
Save
</x-forms.button>
- <x-forms.button wire:click="toggleResend">
+ <x-forms.button canGate="update" :canResource="$settings" wire:click="toggleResend">
Disable Resend
</x-forms.button>
@else
- <x-forms.button isHighlighted wire:click="toggleResend">
+ <x-forms.button canGate="update" :canResource="$settings" isHighlighted wire:click="toggleResend">
Enable Resend
</x-forms.button>
@endif
diff --git a/resources/views/livewire/settings-oauth.blade.php b/resources/views/livewire/settings-oauth.blade.php
index 82ad9d5810..8308e88d06 100644
--- a/resources/views/livewire/settings-oauth.blade.php
+++ b/resources/views/livewire/settings-oauth.blade.php
@@ -31,7 +31,8 @@
helper="When enabled, the normal registration page is hidden if at least one OAuth provider is enabled. OAuth providers can still create users if their provider-specific registration option allows it." />
</div>
<div class="w-full max-w-2xl">
- <x-forms.checkbox id="disable_registration_when_oauth_enabled"
+ <x-forms.checkbox canGate="update" :canResource="$settings"
+ id="disable_registration_when_oauth_enabled"
label="Disable password registration when OAuth is enabled"
instantSave="saveRegistrationPolicy" fullWidth />
</div>
@@ -47,14 +48,16 @@
<div class="flex items-center gap-2 pb-2">
<h2>{{ $oauth_setting['label'] }}</h2>
@if ($oauth_setting['enabled'])
- <x-forms.button type="submit">
+ <x-forms.button canGate="update" :canResource="$settings" type="submit">
Save
</x-forms.button>
- <x-forms.button wire:click="toggleProvider('{{ $oauth_setting['provider'] }}')">
+ <x-forms.button canGate="update" :canResource="$settings"
+ wire:click="toggleProvider('{{ $oauth_setting['provider'] }}')">
Disable {{ $oauth_setting['label'] }}
</x-forms.button>
@else
- <x-forms.button isHighlighted wire:click="toggleProvider('{{ $oauth_setting['provider'] }}')">
+ <x-forms.button canGate="update" :canResource="$settings" isHighlighted
+ wire:click="toggleProvider('{{ $oauth_setting['provider'] }}')">
Enable {{ $oauth_setting['label'] }}
</x-forms.button>
@endif
@@ -64,19 +67,24 @@
<div class="flex flex-col gap-2 pt-4">
<div>
<div class="flex flex-col w-full gap-2 xl:flex-row">
- <x-forms.input id="oauth_settings_map.{{ $oauth_setting['provider'] }}.client_id"
+ <x-forms.input canGate="update" :canResource="$settings"
+ id="oauth_settings_map.{{ $oauth_setting['provider'] }}.client_id"
label="Client ID" />
- <x-forms.input id="oauth_settings_map.{{ $oauth_setting['provider'] }}.client_secret"
+ <x-forms.input canGate="update" :canResource="$settings"
+ id="oauth_settings_map.{{ $oauth_setting['provider'] }}.client_secret"
type="password" label="Client Secret" autocomplete="new-password" />
- <x-forms.input id="oauth_settings_map.{{ $oauth_setting['provider'] }}.redirect_uri"
+ <x-forms.input canGate="update" :canResource="$settings"
+ id="oauth_settings_map.{{ $oauth_setting['provider'] }}.redirect_uri"
placeholder="{{ route('auth.callback', $oauth_setting['provider']) }}"
label="Redirect URI" />
@if ($oauth_setting['provider'] == 'azure')
- <x-forms.input id="oauth_settings_map.{{ $oauth_setting['provider'] }}.tenant"
+ <x-forms.input canGate="update" :canResource="$settings"
+ id="oauth_settings_map.{{ $oauth_setting['provider'] }}.tenant"
label="Tenant" />
@endif
@if ($oauth_setting['provider'] == 'google')
- <x-forms.input id="oauth_settings_map.{{ $oauth_setting['provider'] }}.tenant"
+ <x-forms.input canGate="update" :canResource="$settings"
+ id="oauth_settings_map.{{ $oauth_setting['provider'] }}.tenant"
helper="Optional parameter that supplies a hosted domain (HD) to Google, which<br>triggers a login hint to be displayed on the OAuth screen with this domain.<br><br><a class='underline dark:text-warning text-coollabs' href='https://developers.google.com/identity/openid-connect/openid-connect#hd-param' target='_blank'>Google Documentation</a>"
label="Tenant" />
@endif
@@ -85,40 +93,44 @@
$oauth_setting['provider'] == 'clerk' ||
$oauth_setting['provider'] == 'zitadel' ||
$oauth_setting['provider'] == 'gitlab')
- <x-forms.input id="oauth_settings_map.{{ $oauth_setting['provider'] }}.base_url"
+ <x-forms.input canGate="update" :canResource="$settings"
+ id="oauth_settings_map.{{ $oauth_setting['provider'] }}.base_url"
label="Base URL" />
@endif
@if ($oauth_setting['provider'] == 'oidc')
- <x-forms.input id="oauth_settings_map.{{ $oauth_setting['provider'] }}.base_url"
+ <x-forms.input canGate="update" :canResource="$settings"
+ id="oauth_settings_map.{{ $oauth_setting['provider'] }}.base_url"
label="Issuer URL"
helper="OpenID Provider issuer URL, for example https://example.okta.com. Coolify uses this URL to discover authorization, token, userinfo, and JWKS endpoints." />
@endif
</div>
@if ($oauth_setting['provider'] == 'oidc')
<div class="flex flex-col w-full gap-2 pt-2 xl:flex-row">
- <x-forms.input id="oauth_settings_map.{{ $oauth_setting['provider'] }}.custom_label"
+ <x-forms.input canGate="update" :canResource="$settings"
+ id="oauth_settings_map.{{ $oauth_setting['provider'] }}.custom_label"
label="Login Button Label" placeholder="Login with SSO" />
- <x-forms.input id="oauth_settings_map.{{ $oauth_setting['provider'] }}.scopes"
+ <x-forms.input canGate="update" :canResource="$settings"
+ id="oauth_settings_map.{{ $oauth_setting['provider'] }}.scopes"
label="Scopes"
helper="Must include openid. Common Okta scopes: openid email profile groups." />
- <x-forms.input
+ <x-forms.input canGate="update" :canResource="$settings"
id="oauth_settings_map.{{ $oauth_setting['provider'] }}.clock_skew_seconds"
type="number" label="Clock Skew (seconds)" />
</div>
<div class="flex flex-col gap-2 pt-2">
<div class="md:w-96">
- <x-forms.checkbox
+ <x-forms.checkbox canGate="update" :canResource="$settings"
id="oauth_settings_map.{{ $oauth_setting['provider'] }}.allow_registration"
label="Allow OIDC user creation"
helper="When enabled, a successful OIDC login can create a Coolify user even if normal password registration is disabled." />
</div>
<div class="md:w-96">
- <x-forms.checkbox
+ <x-forms.checkbox canGate="update" :canResource="$settings"
id="oauth_settings_map.{{ $oauth_setting['provider'] }}.require_email_verified"
label="Require verified email" />
</div>
<div class="md:w-96">
- <x-forms.checkbox
+ <x-forms.checkbox canGate="update" :canResource="$settings"
id="oauth_settings_map.{{ $oauth_setting['provider'] }}.use_pkce"
label="Use PKCE" />
</div>
diff --git a/resources/views/livewire/settings/advanced.blade.php b/resources/views/livewire/settings/advanced.blade.php
index ba9c929ece..25a961fb5d 100644
--- a/resources/views/livewire/settings/advanced.blade.php
+++ b/resources/views/livewire/settings/advanced.blade.php
@@ -42,7 +42,8 @@
</div>
@endif
<div class="md:w-96">
- <x-forms.checkbox instantSave id="disable_registration_when_oauth_enabled"
+ <x-forms.checkbox instantSave canGate="update" canResource="$settings"
+ id="disable_registration_when_oauth_enabled"
helper="When enabled, the normal registration page is hidden if at least one OAuth provider is enabled. OAuth providers can still create users if their provider-specific registration option allows it."
label="Disable Registration When OAuth Is Enabled" />
</div>
diff --git a/tests/Feature/LogDrain/LogDrainToggleRollbackTest.php b/tests/Feature/LogDrain/LogDrainToggleRollbackTest.php
new file mode 100644
index 0000000000..994c96398b
--- /dev/null
+++ b/tests/Feature/LogDrain/LogDrainToggleRollbackTest.php
@@ -0,0 +1,45 @@
+<?php
+
+use App\Actions\Server\StartLogDrain;
+use App\Livewire\Server\LogDrains;
+use App\Models\Server;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Livewire\Livewire;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ $this->user = User::factory()->create();
+ $this->team = $this->user->teams()->first();
+ $this->server = Server::factory()->create(['team_id' => $this->team->id]);
+
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->team]);
+});
+
+it('reverts the persisted enabled flag when starting the log drain fails', function () {
+ StartLogDrain::mock()->shouldReceive('handle')->andThrow(new RuntimeException('runtime boom'));
+
+ expect($this->server->settings->fresh()->is_logdrain_newrelic_enabled)->toBeFalsy();
+
+ Livewire::test(LogDrains::class, ['server_uuid' => $this->server->uuid])
+ ->set('logDrainNewRelicLicenseKey', 'abc123')
+ ->set('logDrainNewRelicBaseUri', 'https://log-api.newrelic.com')
+ ->call('toggleLogDrain', 'newrelic')
+ ->assertSet('isLogDrainNewRelicEnabled', false);
+
+ expect($this->server->settings->fresh()->is_logdrain_newrelic_enabled)->toBeFalsy();
+});
+
+it('keeps the enabled flag persisted when starting the log drain succeeds', function () {
+ StartLogDrain::mock()->shouldReceive('handle')->andReturn('ok');
+
+ Livewire::test(LogDrains::class, ['server_uuid' => $this->server->uuid])
+ ->set('logDrainNewRelicLicenseKey', 'abc123')
+ ->set('logDrainNewRelicBaseUri', 'https://log-api.newrelic.com')
+ ->call('toggleLogDrain', 'newrelic')
+ ->assertSet('isLogDrainNewRelicEnabled', true);
+
+ expect($this->server->settings->fresh()->is_logdrain_newrelic_enabled)->toBeTruthy();
+});
diff --git a/tests/Feature/OauthControllerTest.php b/tests/Feature/OauthControllerTest.php
index 4a54030bd7..27660a6bb3 100644
--- a/tests/Feature/OauthControllerTest.php
+++ b/tests/Feature/OauthControllerTest.php
@@ -80,4 +80,6 @@ it('rejects oauth logins when the provider does not return an email address', fu
})->with([
'null email' => [null],
'blank email' => [' '],
+ 'malformed email' => ['not-an-email'],
+ 'missing domain' => ['user@'],
]);
diff --git a/tests/Feature/OidcOauthControllerTest.php b/tests/Feature/OidcOauthControllerTest.php
index 4199eca5fa..b37694bbc4 100644
--- a/tests/Feature/OidcOauthControllerTest.php
+++ b/tests/Feature/OidcOauthControllerTest.php
@@ -113,6 +113,7 @@ it('creates the root user when oidc provisions the first account', function () {
$response->assertRedirect('/');
$this->assertDatabaseHas('users', ['id' => 0, 'email' => '[email protected]']);
$this->assertDatabaseHas('team_user', ['team_id' => 0, 'user_id' => 0, 'role' => 'owner']);
+ expect(InstanceSettings::find(0)->is_registration_enabled)->toBeFalse();
});
it('rejects callbacks for disabled oidc provider', function () {
diff --git a/tests/Feature/SettingsEmailProviderExclusivityTest.php b/tests/Feature/SettingsEmailProviderExclusivityTest.php
new file mode 100644
index 0000000000..7e6b6ff232
--- /dev/null
+++ b/tests/Feature/SettingsEmailProviderExclusivityTest.php
@@ -0,0 +1,64 @@
+<?php
+
+use App\Livewire\SettingsEmail;
+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 () {
+ $this->settings = new InstanceSettings;
+ $this->settings->id = 0;
+ $this->settings->save();
+ $this->rootTeam = Team::factory()->create(['id' => 0]);
+ $this->user = User::factory()->create();
+ $this->user->teams()->attach($this->rootTeam, ['role' => 'owner']);
+
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->rootTeam]);
+});
+
+test('enabling SMTP disables Resend in storage', function () {
+ $this->settings->update([
+ 'resend_enabled' => true,
+ 'resend_api_key' => 're_test_key',
+ 'smtp_from_address' => '[email protected]',
+ 'smtp_from_name' => 'Coolify',
+ ]);
+
+ Livewire::test(SettingsEmail::class)
+ ->set('smtpHost', 'smtp.example.com')
+ ->set('smtpPort', '587')
+ ->set('smtpEncryption', 'starttls')
+ ->set('smtpFromAddress', '[email protected]')
+ ->set('smtpFromName', 'Coolify')
+ ->call('toggleSmtp');
+
+ $this->settings->refresh();
+ expect($this->settings->smtp_enabled)->toBeTrue();
+ expect($this->settings->resend_enabled)->toBeFalse();
+});
+
+test('enabling Resend disables SMTP in storage', function () {
+ $this->settings->update([
+ 'smtp_enabled' => true,
+ 'smtp_host' => 'smtp.example.com',
+ 'smtp_port' => '587',
+ 'smtp_encryption' => 'starttls',
+ 'smtp_from_address' => '[email protected]',
+ 'smtp_from_name' => 'Coolify',
+ ]);
+
+ Livewire::test(SettingsEmail::class)
+ ->set('resendApiKey', 're_test_key')
+ ->set('smtpFromAddress', '[email protected]')
+ ->set('smtpFromName', 'Coolify')
+ ->call('toggleResend');
+
+ $this->settings->refresh();
+ expect($this->settings->resend_enabled)->toBeTrue();
+ expect($this->settings->smtp_enabled)->toBeFalse();
+});
diff --git a/tests/Feature/SettingsOauthTest.php b/tests/Feature/SettingsOauthTest.php
index e547cde983..0d25ce0f37 100644
--- a/tests/Feature/SettingsOauthTest.php
+++ b/tests/Feature/SettingsOauthTest.php
@@ -215,6 +215,25 @@ it('keeps provider disabled in the ui when enable validation fails', function ()
expect(OauthSetting::where('provider', 'authentik')->first()->enabled)->toBeFalse();
});
+it('disables an enabled provider gracefully when required fields become incomplete', function () {
+ actingAsInstanceAdmin();
+
+ OauthSetting::where('provider', 'authentik')->first()->forceFill([
+ 'enabled' => true,
+ 'client_id' => 'authentik-client',
+ 'client_secret' => 'authentik-secret',
+ 'base_url' => 'https://authentik.example.com',
+ ])->save();
+
+ Livewire::test(SettingsOauth::class, ['provider' => 'authentik'])
+ ->set('oauth_settings_map.authentik.client_secret', '')
+ ->call('submit')
+ ->assertDispatched('error')
+ ->assertSet('oauth_settings_map.authentik.enabled', false);
+
+ expect(OauthSetting::where('provider', 'authentik')->first()->enabled)->toBeFalse();
+});
+
it('toggles provider enabled state from the action button', function () {
actingAsInstanceAdmin();
diff --git a/tests/Unit/OidcDiscoveryServiceTest.php b/tests/Unit/OidcDiscoveryServiceTest.php
index 9d2c7167b9..79173a4153 100644
--- a/tests/Unit/OidcDiscoveryServiceTest.php
+++ b/tests/Unit/OidcDiscoveryServiceTest.php
@@ -55,3 +55,17 @@ it('rejects jwks responses without keys', function () {
app(OidcDiscoveryService::class)->jwks('https://idp.example.com/jwks');
})->throws(OidcJwksException::class);
+
+it('rejects non-https issuer urls', function () {
+ Cache::flush();
+ Http::fake();
+
+ app(OidcDiscoveryService::class)->discover('http://idp.example.com');
+})->throws(OidcDiscoveryException::class, 'Issuer URL must be an absolute HTTPS URL.');
+
+it('rejects non-https jwks uris', function () {
+ Cache::flush();
+ Http::fake();
+
+ app(OidcDiscoveryService::class)->jwks('http://idp.example.com/jwks');
+})->throws(OidcJwksException::class, 'JWKS URI must be an absolute HTTPS URL.');
diff --git a/tests/Unit/OidcProviderPkceTest.php b/tests/Unit/OidcProviderPkceTest.php
new file mode 100644
index 0000000000..9726f08b0c
--- /dev/null
+++ b/tests/Unit/OidcProviderPkceTest.php
@@ -0,0 +1,152 @@
+<?php
+
+use App\Auth\Oidc\OidcConfig;
+use App\Auth\Oidc\OidcDiscoveryDocument;
+use App\Auth\Oidc\OidcDiscoveryService;
+use App\Auth\Oidc\OidcTokenValidator;
+use App\Auth\Oidc\Socialite\OidcProvider;
+use GuzzleHttp\Client;
+use GuzzleHttp\Handler\MockHandler;
+use GuzzleHttp\HandlerStack;
+use GuzzleHttp\Middleware;
+use GuzzleHttp\Psr7\Response;
+use Illuminate\Http\Request;
+use Illuminate\Session\ArraySessionHandler;
+use Illuminate\Session\Store;
+use Illuminate\Support\Carbon;
+use Mockery\MockInterface;
+use Tests\TestCase;
+
+uses(TestCase::class);
+
+class TestOidcProviderWithExposedAuthUrl extends OidcProvider
+{
+ public function authUrlForState(string $state): string
+ {
+ return $this->getAuthUrl($state);
+ }
+}
+
+function oidc_provider_discovery_document(): OidcDiscoveryDocument
+{
+ return new OidcDiscoveryDocument(
+ issuer: 'https://idp.example.com',
+ authorizationEndpoint: 'https://idp.example.com/oauth2/authorize',
+ tokenEndpoint: 'https://idp.example.com/oauth2/token',
+ userinfoEndpoint: 'https://idp.example.com/oauth2/userinfo',
+ jwksUri: 'https://idp.example.com/.well-known/jwks.json',
+ );
+}
+
+function oidc_provider_session(): Store
+{
+ $session = new Store('testing', new ArraySessionHandler(1200));
+ $session->start();
+
+ return $session;
+}
+
+function oidc_provider_request(Store $session, string $state = 'state-value'): Request
+{
+ $request = Request::create('/auth/oidc/callback', 'GET', ['state' => $state]);
+ $request->setLaravelSession($session);
+
+ return $request;
+}
+
+function oidc_provider(Request $request): TestOidcProviderWithExposedAuthUrl
+{
+ /** @var OidcDiscoveryService&MockInterface $discoveryService */
+ $discoveryService = Mockery::mock(OidcDiscoveryService::class);
+ $discoveryService->shouldReceive('discover')
+ ->byDefault()
+ ->with('https://idp.example.com')
+ ->andReturn(oidc_provider_discovery_document());
+
+ /** @var OidcTokenValidator&MockInterface $tokenValidator */
+ $tokenValidator = Mockery::mock(OidcTokenValidator::class);
+
+ return (new TestOidcProviderWithExposedAuthUrl(
+ $request,
+ $discoveryService,
+ $tokenValidator,
+ 'client-id',
+ 'client-secret',
+ 'https://coolify.example.com/auth/oidc/callback',
+ ))->setConfig(new OidcConfig(
+ issuerUrl: 'https://idp.example.com',
+ clientId: 'client-id',
+ clientSecret: 'client-secret',
+ redirectUri: 'https://coolify.example.com/auth/oidc/callback',
+ usePkce: true,
+ ));
+}
+
+it('stores oidc nonce and pkce verifier with a ten minute expiry', function () {
+ Carbon::setTestNow('2026-06-15 12:00:00');
+
+ try {
+ $session = oidc_provider_session();
+ $provider = oidc_provider(oidc_provider_request($session));
+
+ $provider->authUrlForState('state-value');
+
+ $nonceEntry = $session->get('oidc.nonce.state-value');
+ $verifierEntry = $session->get('oidc.code_verifier.state-value');
+
+ expect($nonceEntry)->toBeArray()
+ ->and($nonceEntry['value'])->toBeString()->not->toBeEmpty()
+ ->and($nonceEntry['expires_at'])->toBe(now()->addMinutes(10)->timestamp)
+ ->and($verifierEntry)->toBeArray()
+ ->and($verifierEntry['value'])->toBeString()->not->toBeEmpty()
+ ->and($verifierEntry['expires_at'])->toBe(now()->addMinutes(10)->timestamp);
+ } finally {
+ Carbon::setTestNow();
+ }
+});
+
+it('sends a fresh oidc pkce verifier during token exchange', function () {
+ $session = oidc_provider_session();
+ $session->put('oidc.code_verifier.state-value', [
+ 'value' => 'fresh-verifier',
+ 'expires_at' => now()->addMinute()->timestamp,
+ ]);
+
+ $provider = oidc_provider(oidc_provider_request($session));
+ $history = [];
+ $handler = HandlerStack::create(new MockHandler([
+ new Response(200, [], json_encode(['access_token' => 'access-token', 'id_token' => 'id-token'], JSON_THROW_ON_ERROR)),
+ ]));
+ $handler->push(Middleware::history($history));
+ $provider->setHttpClient(new Client(['handler' => $handler]));
+
+ $provider->getAccessTokenResponse('authorization-code');
+
+ parse_str((string) $history[0]['request']->getBody(), $tokenRequestFields);
+
+ expect($tokenRequestFields['code_verifier'] ?? null)->toBe('fresh-verifier')
+ ->and($session->has('oidc.code_verifier.state-value'))->toBeFalse();
+});
+
+it('does not send an expired oidc pkce verifier during token exchange', function () {
+ $session = oidc_provider_session();
+ $session->put('oidc.code_verifier.state-value', [
+ 'value' => 'expired-verifier',
+ 'expires_at' => now()->subSecond()->timestamp,
+ ]);
+
+ $provider = oidc_provider(oidc_provider_request($session));
+ $history = [];
+ $handler = HandlerStack::create(new MockHandler([
+ new Response(200, [], json_encode(['access_token' => 'access-token', 'id_token' => 'id-token'], JSON_THROW_ON_ERROR)),
+ ]));
+ $handler->push(Middleware::history($history));
+ $provider->setHttpClient(new Client(['handler' => $handler]));
+
+ $provider->getAccessTokenResponse('authorization-code');
+
+ parse_str((string) $history[0]['request']->getBody(), $tokenRequestFields);
+
+ expect($tokenRequestFields)->not->toHaveKey('code_verifier')
+ ->and($session->has('oidc.code_verifier.state-value'))->toBeFalse();
+});
diff --git a/tests/Unit/OidcTokenValidatorTest.php b/tests/Unit/OidcTokenValidatorTest.php
index 6be325a0ad..e2546efe18 100644
--- a/tests/Unit/OidcTokenValidatorTest.php
+++ b/tests/Unit/OidcTokenValidatorTest.php
@@ -111,6 +111,9 @@ it('rejects invalid token claims', function (array $claimOverrides, string $mess
'expired token' => [['exp' => time() - 3600], 'expired'],
'future issued at' => [['iat' => time() + 3600], 'issued'],
'nonce mismatch' => [['nonce' => 'wrong-nonce'], 'nonce'],
+ 'missing subject' => [['sub' => null], 'subject'],
+ 'empty subject' => [['sub' => ''], 'subject'],
+ 'non-string subject' => [['sub' => 123], 'subject'],
]);
it('rejects a bad signature and unknown key id', function (string $kid) {