Beautiful Open-Source Form Builder
[codex] Remediate security report findings (#1107)
Julien Nahumd093726ae304
diff --git a/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.php b/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.phpindex bd2fafd8d..43721e2e6 100644--- a/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.php+++ b/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.php@@ -81,6 +81,7 @@ class StoreOidcConnectionRequest extends FormRequestif (!is_array($options)) {$options = [];}+$options['require_state'] = true;$this->merge(['options' => $options]);}diff --git a/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.php b/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.phpindex eae173e19..78766d41b 100644--- a/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.php+++ b/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.php@@ -65,4 +65,5 @@ class UpdateOidcConnectionRequest extends FormRequest'enabled' => ['sometimes', 'boolean'],];}+}diff --git a/api/app/Http/Controllers/Auth/SsoController.php b/api/app/Http/Controllers/Auth/SsoController.phpindex e26b52ee4..f5817db2e 100644--- a/api/app/Http/Controllers/Auth/SsoController.php+++ b/api/app/Http/Controllers/Auth/SsoController.php@@ -5,6 +5,7 @@ namespace App\Http\Controllers\Auth;use App\Enterprise\Oidc\ConnectionManager;use App\Enterprise\Oidc\Exceptions\OidcAccountLinkRequiredException;use App\Enterprise\Oidc\IdTokenVerifier;+use App\Enterprise\Oidc\Models\IdentityConnection;use App\Enterprise\Oidc\OidcLinkService;use App\Http\Controllers\Auth\Traits\ManagesJWT;use App\Http\Controllers\Controller;@@ -18,6 +19,11 @@ use Symfony\Component\HttpKernel\Exception\HttpException;class SsoController extends Controller{use ManagesJWT;++ private const STATE_CACHE_PREFIX = 'oidc_login_state:';+ private const STATE_TTL_SECONDS = 600;+ private const STATE_VERIFIER_HEADER = 'X-OIDC-State-Verifier';+public function __construct(private ConnectionManager $connectionManager,private ProvisioningService $provisioningService,@@ -30,7 +36,7 @@ class SsoController extends Controller* Get redirect URL for OIDC provider authentication.* Returns JSON response so frontend can handle redirect and errors.*/- public function redirect(string $slug)+ public function redirect(Request $request, string $slug){$connection = $this->connectionManager->getConnectionBySlug($slug);@@ -49,19 +55,28 @@ class SsoController extends Controllertry {$driver = $this->connectionManager->buildDriver($connection);+ $state = null;+ $stateVerifier = null;- $requireState = (bool) data_get($connection->options, 'require_state', false);- if ($requireState) {+ if ($this->requiresState($connection)) {$state = Str::random(32);- Cache::put("oidc_state_{$state}", true, 600);+ $stateVerifier = Str::random(64);+ $this->storeState($connection, $state, $stateVerifier);$driver->setState($state);}$redirectUrl = $driver->getRedirectUrl();- return response()->json([+ $payload = ['redirect_url' => $redirectUrl,- ]);+ ];++ if ($state && $stateVerifier) {+ $payload['state'] = $state;+ $payload['state_verifier'] = $stateVerifier;+ }++ return response()->json($payload);} catch (\Exception $e) {Log::error('OIDC redirect failed', ['slug' => $slug,@@ -93,8 +108,7 @@ class SsoController extends Controller}try {- $requireState = (bool) data_get($connection->options, 'require_state', false);- if ($requireState) {+ if ($this->requiresState($connection)) {$state = $request->input('state');if (!$state) {return response()->json([@@ -102,8 +116,9 @@ class SsoController extends Controller], 400);}- $stateValid = Cache::pull("oidc_state_{$state}");- if (!$stateValid) {+ $stateVerifier = $request->header(self::STATE_VERIFIER_HEADER);++ if (!$this->consumeState($connection, (string) $state, is_string($stateVerifier) ? $stateVerifier : null)) {return response()->json(['message' => 'Invalid state. Please try again.',], 400);@@ -258,8 +273,8 @@ class SsoController extends Controller// Find enabled OIDC connection matching domain// Domain is stored directly on the connection record- $connection = \App\Enterprise\Oidc\Models\IdentityConnection::enabled()- ->where('type', \App\Enterprise\Oidc\Models\IdentityConnection::TYPE_OIDC)+ $connection = IdentityConnection::enabled()+ ->where('type', IdentityConnection::TYPE_OIDC)->where('domain', $domain)->first();@@ -284,4 +299,46 @@ class SsoController extends Controller$parts = explode('@', strtolower(trim($email)));return count($parts) === 2 ? $parts[1] : null;}++ private function requiresState(IdentityConnection $connection): bool+ {+ return data_get($connection->options, 'require_state', true) !== false;+ }++ private function storeState(IdentityConnection $connection, string $state, string $stateVerifier): void+ {+ Cache::put($this->stateCacheKey($state), [+ 'connection_id' => $connection->id,+ 'verifier_hash' => hash('sha256', $stateVerifier),+ ], self::STATE_TTL_SECONDS);+ }++ private function consumeState(IdentityConnection $connection, string $state, ?string $stateVerifier): bool+ {+ if (!$stateVerifier) {+ return false;+ }++ $storedState = Cache::get($this->stateCacheKey($state));+ if (!is_array($storedState)) {+ return false;+ }++ if ((int) ($storedState['connection_id'] ?? 0) !== $connection->id) {+ return false;+ }++ if (!hash_equals((string) ($storedState['verifier_hash'] ?? ''), hash('sha256', $stateVerifier))) {+ return false;+ }++ Cache::forget($this->stateCacheKey($state));++ return true;+ }++ private function stateCacheKey(string $state): string+ {+ return self::STATE_CACHE_PREFIX.$state;+ }}diff --git a/api/app/Http/Requests/Integration/Zapier/StoreFormZapierWebhookRequest.php b/api/app/Http/Requests/Integration/Zapier/StoreFormZapierWebhookRequest.phpindex 72b2e5ee3..f95ac3465 100644--- a/api/app/Http/Requests/Integration/Zapier/StoreFormZapierWebhookRequest.php+++ b/api/app/Http/Requests/Integration/Zapier/StoreFormZapierWebhookRequest.php@@ -4,6 +4,7 @@ namespace App\Http\Requests\Integration\Zapier;use App\Models\Forms\Form;use App\Models\Integration\FormZapierWebhook;+use App\Rules\PublicWebhookUrlRule;use Illuminate\Foundation\Http\FormRequest;class StoreFormZapierWebhookRequest extends FormRequest@@ -17,7 +18,7 @@ class StoreFormZapierWebhookRequest extends FormRequest{return ['form_slug' => 'required|exists:forms,slug',- 'hook_url' => 'required|string|url',+ 'hook_url' => ['required', 'string', 'url', new PublicWebhookUrlRule()],];}diff --git a/api/app/Http/Requests/Zapier/CreateIntegrationRequest.php b/api/app/Http/Requests/Zapier/CreateIntegrationRequest.phpindex 0717502e7..31fa7fb34 100644--- a/api/app/Http/Requests/Zapier/CreateIntegrationRequest.php+++ b/api/app/Http/Requests/Zapier/CreateIntegrationRequest.php@@ -3,6 +3,7 @@namespace App\Http\Requests\Zapier;use App\Models\Forms\Form;+use App\Rules\PublicWebhookUrlRule;use Illuminate\Foundation\Http\FormRequest;use Illuminate\Validation\Rule;@@ -18,6 +19,7 @@ class CreateIntegrationRequest extends FormRequest'hookUrl' => ['required','url',+ new PublicWebhookUrlRule(),],];}diff --git a/api/app/Integrations/Handlers/AbstractIntegrationHandler.php b/api/app/Integrations/Handlers/AbstractIntegrationHandler.phpindex 62ad3f559..fbfc1371b 100644--- a/api/app/Integrations/Handlers/AbstractIntegrationHandler.php+++ b/api/app/Integrations/Handlers/AbstractIntegrationHandler.php@@ -9,6 +9,7 @@ use App\Models\Integration\FormIntegrationsEvent;use App\Service\Forms\FormSubmissionFormatter;use App\Service\Forms\FormLogicConditionChecker;use App\Service\Forms\SubmissionUrlService;+use App\Service\Security\PublicWebhookUrl;use Illuminate\Http\Client\RequestException;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;@@ -98,7 +99,11 @@ abstract class AbstractIntegrationHandlerreturn;}- Http::throw()->post($this->getWebhookUrl(), $this->getWebhookData());+ $url = $this->getWebhookUrl();++ Http::throw()+ ->withOptions(PublicWebhookUrl::requestOptions($url))+ ->post($url, $this->getWebhookData());}abstract public static function getValidationRules(?Form $form): array;diff --git a/api/app/Integrations/Handlers/ActivepiecesIntegration.php b/api/app/Integrations/Handlers/ActivepiecesIntegration.phpindex 4db447fa6..7d5d763b9 100644--- a/api/app/Integrations/Handlers/ActivepiecesIntegration.php+++ b/api/app/Integrations/Handlers/ActivepiecesIntegration.php@@ -3,13 +3,14 @@namespace App\Integrations\Handlers;use App\Models\Forms\Form;+use App\Rules\PublicWebhookUrlRule;class ActivepiecesIntegration extends AbstractIntegrationHandler{public static function getValidationRules(?Form $form): array{return [- 'webhook_url' => 'required|url',+ 'webhook_url' => ['required', 'url', new PublicWebhookUrlRule()],'provider_url' => 'nullable|url',];}diff --git a/api/app/Integrations/Handlers/N8nIntegration.php b/api/app/Integrations/Handlers/N8nIntegration.phpindex e0151c450..76aa10f1a 100644--- a/api/app/Integrations/Handlers/N8nIntegration.php+++ b/api/app/Integrations/Handlers/N8nIntegration.php@@ -3,13 +3,14 @@namespace App\Integrations\Handlers;use App\Models\Forms\Form;+use App\Rules\PublicWebhookUrlRule;class N8nIntegration extends AbstractIntegrationHandler{public static function getValidationRules(?Form $form): array{return [- 'webhook_url' => 'required|url',+ 'webhook_url' => ['required', 'url', new PublicWebhookUrlRule()],'provider_url' => 'nullable|url',];}diff --git a/api/app/Integrations/Handlers/WebhookIntegration.php b/api/app/Integrations/Handlers/WebhookIntegration.phpindex 366fe5076..2c1e6f987 100644--- a/api/app/Integrations/Handlers/WebhookIntegration.php+++ b/api/app/Integrations/Handlers/WebhookIntegration.php@@ -3,6 +3,8 @@namespace App\Integrations\Handlers;use App\Models\Forms\Form;+use App\Rules\PublicWebhookUrlRule;+use App\Service\Security\PublicWebhookUrl;use Illuminate\Support\Facades\Http;class WebhookIntegration extends AbstractIntegrationHandler@@ -28,7 +30,7 @@ class WebhookIntegration extends AbstractIntegrationHandlerpublic static function getValidationRules(?Form $form): array{return [- 'webhook_url' => 'required|url',+ 'webhook_url' => ['required', 'url', new PublicWebhookUrlRule()],'webhook_secret' => 'nullable|string|min:12','webhook_headers' => ['nullable',@@ -137,6 +139,7 @@ class WebhookIntegration extends AbstractIntegrationHandlerHttp::throw()->timeout(5)+ ->withOptions(PublicWebhookUrl::requestOptions($this->getWebhookUrl()))->withHeaders($headers)->withBody($payload, 'application/json')->post($this->getWebhookUrl());diff --git a/api/app/Models/Integration/FormZapierWebhook.php b/api/app/Models/Integration/FormZapierWebhook.phpindex 9eb341041..e58f4749c 100644--- a/api/app/Models/Integration/FormZapierWebhook.php+++ b/api/app/Models/Integration/FormZapierWebhook.php@@ -4,6 +4,7 @@ namespace App\Models\Integration;use App\Integrations\Handlers\ZapierIntegration;use App\Models\Forms\Form;+use App\Service\Security\PublicWebhookUrl;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Support\Facades\Http;use Illuminate\Database\Eloquent\Model;@@ -31,7 +32,7 @@ class FormZapierWebhook extends Modelpublic function triggerHook(array $data){- Http::throw()->post(+ Http::throw()->withOptions(PublicWebhookUrl::requestOptions($this->hook_url))->post($this->hook_url,ZapierIntegration::formatWebhookData($this->form, $data));diff --git a/api/app/Rules/PublicWebhookUrlRule.php b/api/app/Rules/PublicWebhookUrlRule.phpnew file mode 100644index 000000000..bb326c623--- /dev/null+++ b/api/app/Rules/PublicWebhookUrlRule.php@@ -0,0 +1,23 @@+<?php++namespace App\Rules;++use App\Service\Security\PublicWebhookUrl;+use Closure;+use Illuminate\Contracts\Validation\ValidationRule;++class PublicWebhookUrlRule implements ValidationRule+{+ public function validate(string $attribute, mixed $value, Closure $fail): void+ {+ if (!is_string($value)) {+ $fail('The :attribute must be a valid URL.');+ return;+ }++ $message = PublicWebhookUrl::validate($value);+ if ($message !== null) {+ $fail($message);+ }+ }+}diff --git a/api/app/Service/Security/PublicWebhookUrl.php b/api/app/Service/Security/PublicWebhookUrl.phpnew file mode 100644index 000000000..6c9dfcf75--- /dev/null+++ b/api/app/Service/Security/PublicWebhookUrl.php@@ -0,0 +1,154 @@+<?php++namespace App\Service\Security;++use InvalidArgumentException;++class PublicWebhookUrl+{+ public static function assertSafe(string $url): void+ {+ self::validatedIp($url);+ }++ /**+ * @return array<string, mixed>+ */+ public static function requestOptions(string $url): array+ {+ $options = [+ 'allow_redirects' => false,+ ];++ $ip = self::validatedIp($url);+ if ($ip === null) {+ return $options;+ }++ $host = trim((string) parse_url($url, PHP_URL_HOST), '[]');+ $port = parse_url($url, PHP_URL_PORT) ?: 443;++ $options['curl'] = [+ CURLOPT_RESOLVE => [+ sprintf('%s:%d:%s', $host, $port, self::formatCurlResolveIp($ip)),+ ],+ ];++ return $options;+ }++ public static function validate(string $url): ?string+ {+ try {+ self::validatedIp($url);+ } catch (InvalidArgumentException $e) {+ return $e->getMessage();+ }++ return null;+ }++ private static function validatedIp(string $url): ?string+ {+ if (config('opnform.webhooks.allow_private_urls', false)) {+ self::assertUrlShape($url);++ return null;+ }++ $shapeError = self::validateUrlShape($url);+ if ($shapeError !== null) {+ throw new InvalidArgumentException($shapeError);+ }++ $host = parse_url($url, PHP_URL_HOST);+ if (!is_string($host) || $host === '') {+ throw new InvalidArgumentException('The webhook URL host is invalid.');+ }++ $ips = self::resolveHost($host);+ if ($ips === []) {+ throw new InvalidArgumentException('The webhook URL host could not be resolved.');+ }++ foreach ($ips as $ip) {+ if (!self::isPublicIp($ip)) {+ throw new InvalidArgumentException('The webhook URL must resolve only to public IP addresses.');+ }+ }++ return $ips[0];+ }++ private static function validateUrlShape(string $url): ?string+ {+ if (!filter_var($url, FILTER_VALIDATE_URL)) {+ return 'The webhook URL must be a valid URL.';+ }++ if (strtolower((string) parse_url($url, PHP_URL_SCHEME)) !== 'https') {+ return 'The webhook URL must use HTTPS.';+ }++ if (parse_url($url, PHP_URL_USER) !== null || parse_url($url, PHP_URL_PASS) !== null) {+ return 'The webhook URL cannot contain embedded credentials.';+ }++ return null;+ }++ private static function assertUrlShape(string $url): void+ {+ $message = self::validateUrlShape($url);++ if ($message !== null) {+ throw new InvalidArgumentException($message);+ }+ }++ /**+ * @return array<int, string>+ */+ private static function resolveHost(string $host): array+ {+ $host = trim($host, '[]');++ if (filter_var($host, FILTER_VALIDATE_IP)) {+ return [$host];+ }++ if (strtolower(rtrim($host, '.')) === 'localhost') {+ return ['127.0.0.1'];+ }++ $records = @dns_get_record($host, DNS_A + DNS_AAAA);+ if (!is_array($records)) {+ return [];+ }++ $ips = [];+ foreach ($records as $record) {+ foreach (['ip', 'ipv6'] as $key) {+ if (isset($record[$key]) && filter_var($record[$key], FILTER_VALIDATE_IP)) {+ $ips[] = $record[$key];+ }+ }+ }++ return array_values(array_unique($ips));+ }++ private static function isPublicIp(string $ip): bool+ {+ return filter_var(+ $ip,+ FILTER_VALIDATE_IP,+ FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE+ ) !== false;+ }++ private static function formatCurlResolveIp(string $ip): string+ {+ return str_contains($ip, ':') ? '['.$ip.']' : $ip;+ }+}diff --git a/api/config/opnform.php b/api/config/opnform.phpindex 1a4ef1ba2..11f0e639a 100644--- a/api/config/opnform.php+++ b/api/config/opnform.php@@ -10,4 +10,7 @@ return ['custom_code' => ['enable_self_hosted' => env('CUSTOM_CODE_ENABLE_SELF_HOSTED', false),],+ 'webhooks' => [+ 'allow_private_urls' => env('WEBHOOKS_ALLOW_PRIVATE_URLS', false),+ ],];diff --git a/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.php b/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.phpindex 4f904709c..c620fbbf4 100644--- a/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.php+++ b/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.php@@ -11,6 +11,28 @@ require_once __DIR__ . '/../../../TestHelpers/OidcTestHelpers.php';uses(TestHelpers::class);uses()->group('oidc', 'feature');+if (!function_exists('cacheOidcState')) {+ function cacheOidcState(IdentityConnection $connection, string $state, string $verifier = 'valid-state-verifier', int $ttlSeconds = 600): string+ {+ Cache::put("oidc_login_state:{$state}", [+ 'connection_id' => $connection->id,+ 'verifier_hash' => hash('sha256', $verifier),+ ], $ttlSeconds);++ return $verifier;+ }+}++if (!function_exists('oidcVerifierHeaders')) {+ function oidcVerifierHeaders(string $verifier): array+ {+ return [+ 'Accept' => 'application/json',+ 'X-OIDC-State-Verifier' => $verifier,+ ];+ }+}+afterEach(function () {Mockery::close();Cache::flush();@@ -23,8 +45,18 @@ describe('SsoController - Redirect', function () {'enabled' => true,]);+ $capturedState = null;+// Mock the driver to return a redirect URL$mockDriver = Mockery::mock(\App\Enterprise\Oidc\Adapters\OAuthOidcDriver::class);+ $mockDriver->shouldReceive('setState')+ ->once()+ ->with(Mockery::on(function ($state) use (&$capturedState) {+ $capturedState = $state;++ return is_string($state) && strlen($state) === 32;+ }))+ ->andReturnSelf();$mockDriver->shouldReceive('getRedirectUrl')->andReturn('https://idp.example.com/authorize');$mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);@@ -43,6 +75,48 @@ describe('SsoController - Redirect', function () {$response->assertJson(['redirect_url' => 'https://idp.example.com/authorize',]);++ $stateVerifier = $response->json('state_verifier');+ $storedState = Cache::get("oidc_login_state:{$capturedState}");++ expect($response->json('state'))->toBe($capturedState)+ ->and($stateVerifier)->toBeString()+ ->and(strlen($stateVerifier))->toBe(64)+ ->and($storedState['connection_id'])->toBe($connection->id)+ ->and(hash_equals($storedState['verifier_hash'], hash('sha256', $stateVerifier)))->toBeTrue();+ });++ it('does not add state when explicitly disabled on the connection', function () {+ $connection = IdentityConnection::factory()->create([+ 'slug' => 'state-disabled',+ 'enabled' => true,+ 'options' => [+ 'require_state' => false,+ ],+ ]);++ $mockDriver = Mockery::mock(\App\Enterprise\Oidc\Adapters\OAuthOidcDriver::class);+ $mockDriver->shouldNotReceive('setState');+ $mockDriver->shouldReceive('getRedirectUrl')->andReturn('https://idp.example.com/authorize');++ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);+ $mockConnectionManager->shouldReceive('getConnectionBySlug')+ ->with('state-disabled')+ ->andReturn($connection);+ $mockConnectionManager->shouldReceive('buildDriver')+ ->with($connection)+ ->andReturn($mockDriver);++ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);++ $response = $this->postJson("/auth/{$connection->slug}/redirect");++ $response->assertSuccessful();+ $response->assertJson([+ 'redirect_url' => 'https://idp.example.com/authorize',+ ]);+ expect($response->json('state'))->toBeNull()+ ->and($response->json('state_verifier'))->toBeNull();});it('returns 404 for non-existent connection', function () {@@ -251,8 +325,11 @@ describe('SsoController - Callback', function () {$this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);$this->app->instance(\App\Enterprise\Oidc\IdTokenVerifier::class, $mockIdTokenVerifier);- $response = $this->getJson("/auth/test-sso/callback", [- 'Accept' => 'application/json',+ $state = 'new-user-state-token';+ $stateVerifier = cacheOidcState($connection, $state);++ $response = $this->getJson("/auth/test-sso/callback?state={$state}", [+ ...oidcVerifierHeaders($stateVerifier),]);$response->assertSuccessful();@@ -271,13 +348,10 @@ describe('SsoController - Callback', function () {expect($response->json('new_user'))->toBeTrue();});- it('rejects callback when state is required but missing', function () {+ it('rejects callback when state is missing', function () {$connection = IdentityConnection::factory()->create(['slug' => 'state-required','enabled' => true,- 'options' => [- 'require_state' => true,- ],]);$response = $this->getJson("/auth/{$connection->slug}/callback", [@@ -288,17 +362,148 @@ describe('SsoController - Callback', function () {expect($response->json('message'))->toContain('Missing or invalid state');});- it('accepts callback when state is valid and required', function () {+ it('rejects callback when state verifier is missing', function () {$connection = IdentityConnection::factory()->create([- 'slug' => 'state-valid',+ 'slug' => 'state-required',+ 'enabled' => true,+ ]);++ $state = 'missing-verifier-state';+ cacheOidcState($connection, $state);++ $response = $this->getJson("/auth/{$connection->slug}/callback?state={$state}", [+ 'Accept' => 'application/json',+ ]);++ $response->assertStatus(400);+ expect($response->json('message'))->toContain('Invalid state');+ });++ it('rejects callback when state was not issued by the OIDC login flow', function () {+ $connection = IdentityConnection::factory()->create([+ 'slug' => 'state-required',+ 'enabled' => true,+ ]);++ $state = 'attacker-session-state';+ Cache::put("oidc_state_{$state}", true, 600);++ $response = $this->getJson("/auth/{$connection->slug}/callback?state={$state}", [+ ...oidcVerifierHeaders('attacker-verifier'),+ ]);++ $response->assertStatus(400);+ expect($response->json('message'))->toContain('Invalid state');+ });++ it('rejects callback when state verifier does not match', function () {+ $connection = IdentityConnection::factory()->create([+ 'slug' => 'state-required',+ 'enabled' => true,+ ]);++ $state = 'wrong-verifier-state';+ cacheOidcState($connection, $state, 'correct-verifier');++ $response = $this->getJson("/auth/{$connection->slug}/callback?state={$state}", [+ ...oidcVerifierHeaders('wrong-verifier'),+ ]);++ $response->assertStatus(400);+ expect($response->json('message'))->toContain('Invalid state');+ expect(Cache::get("oidc_login_state:{$state}"))->not->toBeNull();+ });++ it('rejects callback when state belongs to a different connection', function () {+ $connection = IdentityConnection::factory()->create([+ 'slug' => 'state-required',+ 'enabled' => true,+ ]);+ $otherConnection = IdentityConnection::factory()->create([+ 'slug' => 'other-state-owner',+ 'enabled' => true,+ ]);++ $state = 'other-connection-state';+ $stateVerifier = cacheOidcState($otherConnection, $state);++ $response = $this->getJson("/auth/{$connection->slug}/callback?state={$state}", [+ ...oidcVerifierHeaders($stateVerifier),+ ]);++ $response->assertStatus(400);+ expect($response->json('message'))->toContain('Invalid state');+ });++ it('rejects callback when state has expired in the current session', function () {+ $connection = IdentityConnection::factory()->create([+ 'slug' => 'state-required',+ 'enabled' => true,+ ]);++ $state = 'expired-state';+ $stateVerifier = cacheOidcState($connection, $state, 'expired-verifier', -1);++ $response = $this->getJson("/auth/{$connection->slug}/callback?state={$state}", [+ ...oidcVerifierHeaders($stateVerifier),+ ]);++ $response->assertStatus(400);+ expect($response->json('message'))->toContain('Invalid state');+ });++ it('accepts callback without state when explicitly disabled on the connection', function () {+ $connection = IdentityConnection::factory()->create([+ 'slug' => 'state-disabled','enabled' => true,'options' => [- 'require_state' => true,+ 'require_state' => false,],]);+ $socialiteUser = createMockSocialiteUser(+ email: '[email protected]',+ name: 'No State User'+ );+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-no-state');+ $idToken = createMockIdToken($idTokenClaims);++ $mockDriver = Mockery::mock(\App\Enterprise\Oidc\Adapters\OAuthOidcDriver::class);+ $mockDriver->shouldReceive('setRedirectUrl')->andReturnSelf();+ $mockDriver->shouldReceive('getUser')->andReturn($socialiteUser);+ $mockDriver->shouldReceive('getIdToken')->andReturn($idToken);++ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);+ $mockConnectionManager->shouldReceive('getConnectionBySlug')+ ->with('state-disabled')+ ->andReturn($connection);+ $mockConnectionManager->shouldReceive('buildDriver')+ ->with($connection)+ ->andReturn($mockDriver);++ $mockIdTokenVerifier = Mockery::mock(\App\Enterprise\Oidc\IdTokenVerifier::class);+ $mockIdTokenVerifier->shouldReceive('verifySignature')+ ->with($connection, $idToken)+ ->andReturnNull();++ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);+ $this->app->instance(\App\Enterprise\Oidc\IdTokenVerifier::class, $mockIdTokenVerifier);++ $response = $this->getJson("/auth/{$connection->slug}/callback", [+ 'Accept' => 'application/json',+ ]);++ $response->assertSuccessful();+ });++ it('accepts callback when state is valid', function () {+ $connection = IdentityConnection::factory()->create([+ 'slug' => 'state-valid',+ 'enabled' => true,+ ]);+$state = 'state-token-12345678';- \Illuminate\Support\Facades\Cache::put("oidc_state_{$state}", true, 600);+ $stateVerifier = cacheOidcState($connection, $state);$socialiteUser = createMockSocialiteUser(email: '[email protected]',@@ -329,10 +534,11 @@ describe('SsoController - Callback', function () {$this->app->instance(\App\Enterprise\Oidc\IdTokenVerifier::class, $mockIdTokenVerifier);$response = $this->getJson("/auth/{$connection->slug}/callback?state={$state}", [- 'Accept' => 'application/json',+ ...oidcVerifierHeaders($stateVerifier),]);$response->assertSuccessful();+ expect(Cache::get("oidc_login_state:{$state}"))->toBeNull();});it('returns 404 for non-existent connection', function () {@@ -391,8 +597,11 @@ describe('SsoController - Callback', function () {$this->app->instance(\App\Enterprise\Oidc\IdTokenVerifier::class, $mockIdTokenVerifier);$this->app->instance(\App\Enterprise\Oidc\ProvisioningService::class, $mockProvisioningService);- $response = $this->getJson("/auth/test-sso/callback", [- 'Accept' => 'application/json',+ $state = 'provisioning-error-state-token';+ $stateVerifier = cacheOidcState($connection, $state);++ $response = $this->getJson("/auth/test-sso/callback?state={$state}", [+ ...oidcVerifierHeaders($stateVerifier),]);$response->assertStatus(400);@@ -469,8 +678,11 @@ describe('SsoController - Callback', function () {$this->app->instance(\App\Enterprise\Oidc\IdTokenVerifier::class, $mockIdTokenVerifier);$this->app->instance(\App\Enterprise\Oidc\ProvisioningService::class, $mockProvisioningService);- $response = $this->getJson("/auth/test-sso/callback", [- 'Accept' => 'application/json',+ $state = 'blocked-user-state-token';+ $stateVerifier = cacheOidcState($connection, $state);++ $response = $this->getJson("/auth/test-sso/callback?state={$state}", [+ ...oidcVerifierHeaders($stateVerifier),]);$response->assertForbidden();diff --git a/api/tests/Feature/Forms/FormIntegrationEventTest.php b/api/tests/Feature/Forms/FormIntegrationEventTest.phpindex d21619ce6..088d1b39b 100644--- a/api/tests/Feature/Forms/FormIntegrationEventTest.php+++ b/api/tests/Feature/Forms/FormIntegrationEventTest.php@@ -42,7 +42,7 @@ it('prevents fetching another form integration events via mismatched form and in'integration_id' => 'webhook','logic' => null,'data' => [- 'webhook_url' => 'https://victim.example/webhook'+ 'webhook_url' => 'https://example.com/victim-webhook']])->assertSuccessful();diff --git a/api/tests/Feature/Forms/FormIntegrationTest.php b/api/tests/Feature/Forms/FormIntegrationTest.phpindex e667bcf67..0b2f0d942 100644--- a/api/tests/Feature/Forms/FormIntegrationTest.php+++ b/api/tests/Feature/Forms/FormIntegrationTest.php@@ -58,7 +58,7 @@ it('prevents updating another form integration via mismatched form and integrati'integration_id' => 'webhook','logic' => null,'data' => [- 'webhook_url' => 'https://victim.example/webhook'+ 'webhook_url' => 'https://example.com/victim-webhook']])->assertSuccessful();@@ -74,12 +74,12 @@ it('prevents updating another form integration via mismatched form and integrati'integration_id' => 'webhook','logic' => null,'data' => [- 'webhook_url' => 'https://attacker.example/steal'+ 'webhook_url' => 'https://example.com/attacker-webhook']])->assertStatus(404);$victimIntegration = \App\Models\Integration\FormIntegration::findOrFail((int) $victimIntegrationId);- expect($victimIntegration->data->webhook_url)->toBe('https://victim.example/webhook');+ expect($victimIntegration->data->webhook_url)->toBe('https://example.com/victim-webhook');});it('prevents deleting another form integration via mismatched form and integration ids', function () {@@ -92,7 +92,7 @@ it('prevents deleting another form integration via mismatched form and integrati'integration_id' => 'webhook','logic' => null,'data' => [- 'webhook_url' => 'https://victim.example/webhook'+ 'webhook_url' => 'https://example.com/victim-webhook']])->assertSuccessful();@@ -207,6 +207,68 @@ it('can create form integration with checkbox logic', function () {});describe('Webhook Integration', function () {+ it('rejects webhook urls that point to private or metadata addresses', function () {+ $user = $this->actingAsProUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ foreach ([+ 'http://169.254.169.254/latest/meta-data/',+ 'https://169.254.169.254/latest/meta-data/',+ 'https://127.0.0.1/webhook',+ 'https://localhost/webhook',+ 'https://10.0.0.5/webhook',+ ] as $url) {+ $this->postJson(route('open.forms.integrations.create', $form), [+ 'status' => 'active',+ 'integration_id' => 'webhook',+ 'logic' => null,+ 'data' => [+ 'webhook_url' => $url,+ ],+ ])+ ->assertStatus(422)+ ->assertJsonValidationErrors(['data.webhook_url']);+ }+ });++ it('revalidates stored webhook urls before dispatching them', function () {+ Http::fake();++ $user = $this->actingAsProUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace, [+ 'properties' => [+ [+ 'id' => 'name',+ 'name' => 'Name',+ 'type' => 'text',+ 'hidden' => false,+ 'required' => true,+ ],+ ],+ ]);++ $integration = \App\Models\Integration\FormIntegration::factory()+ ->for($form)+ ->create([+ 'integration_id' => 'webhook',+ 'status' => \App\Models\Integration\FormIntegration::STATUS_ACTIVE,+ 'data' => [+ 'webhook_url' => 'https://127.0.0.1/webhook',+ ],+ ]);++ $this->postJson(route('forms.answer', $form->slug), $this->generateFormSubmissionData($form))+ ->assertSuccessful();++ Http::assertNothingSent();+ $this->assertDatabaseHas('form_integrations_events', [+ 'integration_id' => $integration->id,+ 'status' => \App\Models\Integration\FormIntegrationsEvent::STATUS_ERROR,+ ]);+ });+it('includes form and submission ids in the webhook payload', function () {Http::fake(['https://example.com/*' => Http::response(['ok' => true], 200),diff --git a/api/tests/Feature/Security/PublicWebhookUrlTest.php b/api/tests/Feature/Security/PublicWebhookUrlTest.phpnew file mode 100644index 000000000..2306895dc--- /dev/null+++ b/api/tests/Feature/Security/PublicWebhookUrlTest.php@@ -0,0 +1,27 @@+<?php++use App\Service\Security\PublicWebhookUrl;++it('pins the validated destination ip for webhook requests', function () {+ config(['opnform.webhooks.allow_private_urls' => false]);++ $options = PublicWebhookUrl::requestOptions('https://93.184.216.34/webhook');++ expect($options['allow_redirects'])->toBeFalse()+ ->and($options['curl'][CURLOPT_RESOLVE])->toBe(['93.184.216.34:443:93.184.216.34']);+});++it('does not pin destinations when private webhook urls are explicitly allowed', function () {+ config(['opnform.webhooks.allow_private_urls' => true]);++ $options = PublicWebhookUrl::requestOptions('https://127.0.0.1/webhook');++ expect($options)->toBe(['allow_redirects' => false]);+});++it('rejects link local metadata addresses', function () {+ config(['opnform.webhooks.allow_private_urls' => false]);++ expect(PublicWebhookUrl::validate('https://169.254.169.254/latest/meta-data/'))+ ->toBe('The webhook URL must resolve only to public IP addresses.');+});diff --git a/api/tests/Feature/Zapier/IntegrationsTest.php b/api/tests/Feature/Zapier/IntegrationsTest.phpindex b6c6e9064..d2b0c2e0c 100644--- a/api/tests/Feature/Zapier/IntegrationsTest.php+++ b/api/tests/Feature/Zapier/IntegrationsTest.php@@ -54,6 +54,27 @@ test('cannot create an integration without a corresponding ability', function ()assertDatabaseCount('form_integrations', 0);});+test('cannot create an integration with a private hook url', function () {+ $user = User::factory()->create();+ $workspace = createUserWorkspace($user);++ $form = createForm($user, $workspace, ['title' => 'First form']);++ Sanctum::actingAs(+ $user,+ ['manage-integrations']+ );++ post(route('zapier.webhooks.store'), [+ 'form_id' => $form->id,+ 'hookUrl' => 'https://169.254.169.254/latest/meta-data/'+ ])+ ->assertStatus(422)+ ->assertJsonValidationErrors('hookUrl');++ assertDatabaseCount('form_integrations', 0);+});+test('cannot create an integration for other users form', function () {$user = User::factory()->create();diff --git a/client/api/oidc.js b/client/api/oidc.jsindex 82bc0f359..cd11a2d5e 100644--- a/client/api/oidc.js+++ b/client/api/oidc.js@@ -21,18 +21,23 @@ export const oidcApi = {getOptionsForEmail: (email) => apiService.post('/auth/oidc/options', { email }),// OIDC callback - processes authorization code and returns token/user- callback: (slug, queryParams) => {+ callback: (slug, queryParams, stateVerifier = null) => {// Build query string from paramsconst queryString = new URLSearchParams(queryParams).toString()const url = `/auth/${slug}/callback${queryString ? '?' + queryString : ''}`+ const headers = {+ 'Accept': 'application/json'+ }++ if (stateVerifier) {+ headers['X-OIDC-State-Verifier'] = stateVerifier+ }+// Use GET with Accept: application/json header to get JSON responsereturn apiService.get(url, {- headers: {- 'Accept': 'application/json'- }+ headers})},link: (linkToken) => apiService.post('/auth/oidc/link', { link_token: linkToken }),}-diff --git a/client/components/pages/auth/components/LoginForm.vue b/client/components/pages/auth/components/LoginForm.vueindex 9207ce19c..67c8a5ddd 100644--- a/client/components/pages/auth/components/LoginForm.vue+++ b/client/components/pages/auth/components/LoginForm.vue@@ -117,6 +117,7 @@import ForgotPasswordModal from "../ForgotPasswordModal.vue"import GoogleOneTap from "~/components/vendor/GoogleOneTap.vue"import { WindowMessageTypes } from "~/composables/useWindowMessage"+import { storeOidcStateVerifier } from "~/lib/oidc/state-verifier"// Propsconst props = defineProps({@@ -191,6 +192,7 @@ const checkOidcOptions = async () => {const redirectResponse = await form.post(`/auth/${response.slug}/redirect`)if (redirectResponse.redirect_url) {+ storeOidcStateVerifier(response.slug, redirectResponse.state, redirectResponse.state_verifier)// Redirect to OIDC providerwindow.location.href = redirectResponse.redirect_urlreturndiff --git a/client/lib/oidc/connection-options.js b/client/lib/oidc/connection-options.jsindex 0e7a4061e..3953a7ff6 100644--- a/client/lib/oidc/connection-options.js+++ b/client/lib/oidc/connection-options.js@@ -1,5 +1,5 @@export const getOidcRequireStateDefault = () => trueexport const getOidcRequireStateForEdit = (options) => {- return options?.require_state ?? false+ return options?.require_state ?? true}diff --git a/client/lib/oidc/state-verifier.js b/client/lib/oidc/state-verifier.jsnew file mode 100644index 000000000..6f3d34efb--- /dev/null+++ b/client/lib/oidc/state-verifier.js@@ -0,0 +1,32 @@+const stateVerifierStorageKey = (slug, state) => `oidc_state_verifier:${slug}:${state}`++export const storeOidcStateVerifier = (slug, state, verifier) => {+ if (import.meta.server || !slug || !state || !verifier) {+ return+ }++ try {+ sessionStorage.setItem(stateVerifierStorageKey(slug, state), verifier)+ } catch {+ // Ignore storage failures. The callback API will reject the state if the verifier cannot be saved.+ }+}++export const consumeOidcStateVerifier = (slug, state) => {+ if (import.meta.server || !slug || !state) {+ return null+ }++ try {+ const key = stateVerifierStorageKey(slug, state)+ const verifier = sessionStorage.getItem(key)++ if (verifier) {+ sessionStorage.removeItem(key)+ }++ return verifier+ } catch {+ return null+ }+}diff --git a/client/pages/auth/[slug]/callback.vue b/client/pages/auth/[slug]/callback.vueindex b9e490ced..fff2a999b 100644--- a/client/pages/auth/[slug]/callback.vue+++ b/client/pages/auth/[slug]/callback.vue@@ -46,6 +46,7 @@<script setup>import { oidcApi } from "~/api"+import { consumeOidcStateVerifier } from "~/lib/oidc/state-verifier"const router = useRouter()const route = useRoute()@@ -67,11 +68,13 @@ const handleCallback = async () => {queryParams[key] = route.query[key]}})+ const state = Array.isArray(route.query.state) ? route.query.state[0] : route.query.state+ const stateVerifier = consumeOidcStateVerifier(slug, state)// Call the OIDC callback endpoint to process authorization codelet responsetry {- response = await oidcApi.callback(slug, queryParams)+ response = await oidcApi.callback(slug, queryParams, stateVerifier)} catch (error) {// Handle 422 responses that indicate 2FA is required (not validation errors)const twoFactorResponse = handleTwoFactorError(error)@@ -164,4 +167,3 @@ onMounted(() => {})})</script>-diff --git a/client/test/unit/oidc-connection-options.test.ts b/client/test/unit/oidc-connection-options.test.tsindex 194ad266a..830fe8c0c 100644--- a/client/test/unit/oidc-connection-options.test.ts+++ b/client/test/unit/oidc-connection-options.test.ts@@ -6,9 +6,9 @@ describe('oidc connection options', () => {expect(getOidcRequireStateDefault()).toBe(true)})- it('returns false when require_state is missing', () => {- expect(getOidcRequireStateForEdit(undefined)).toBe(false)- expect(getOidcRequireStateForEdit({})).toBe(false)+ it('returns true when require_state is missing', () => {+ expect(getOidcRequireStateForEdit(undefined)).toBe(true)+ expect(getOidcRequireStateForEdit({})).toBe(true)})it('returns stored require_state for existing connections', () => {diff --git a/docs/api-reference/integrations/create-webhook-integration.mdx b/docs/api-reference/integrations/create-webhook-integration.mdxindex c1d1c1efd..a5c98c42c 100644--- a/docs/api-reference/integrations/create-webhook-integration.mdx+++ b/docs/api-reference/integrations/create-webhook-integration.mdx@@ -29,7 +29,7 @@ Configuration object containing webhook details.<Expandable title="data properties"><ParamField body="webhook_url" type="string" required>-The URL where form submissions will be sent. Must be a valid HTTP/HTTPS URL.+The URL where form submissions will be sent. Must be a valid HTTPS URL that resolves only to public IP addresses. Private, loopback, link-local, and cloud metadata addresses are rejected.</ParamField><ParamField body="webhook_secret" type="string">@@ -112,14 +112,14 @@ curl -X POST 'https://api.opnform.com/open/forms/123/integrations' \`404 Not Found` β Form not found.-`422 Unprocessable Entity` β Validation error (e.g., invalid webhook URL, webhook_secret too short, blocked header).+`422 Unprocessable Entity` β Validation error (e.g., invalid or non-public webhook URL, webhook_secret too short, blocked header).<ResponseExample>```json Error{"message": "The given data was invalid.","errors": {- "data.webhook_url": ["The webhook url must be a valid URL."],+ "data.webhook_url": ["The webhook URL must use HTTPS."],"data.webhook_secret": ["The webhook secret must be at least 12 characters."],"data.webhook_headers": ["The 'Authorization' header cannot be customized for security reasons."]}@@ -131,6 +131,8 @@ curl -X POST 'https://api.opnform.com/open/forms/123/integrations' \If you provide a `webhook_secret` when creating the webhook, OpnForm will sign each webhook request with an HMAC-SHA256 signature. This allows you to verify that the webhook came from OpnForm and hasn't been tampered with.+Webhook URLs are validated when they are saved and again before each delivery. OpnForm does not follow webhook redirects, and private network destinations are blocked unless the instance operator explicitly enables private webhook URLs for a self-hosted deployment.+Each webhook request will include:- **`X-Webhook-Signature` header**: Contains the signature in format `sha256=HEXADECIMAL_VALUE`diff --git a/docs/api-reference/integrations/update-webhook-integration.mdx b/docs/api-reference/integrations/update-webhook-integration.mdxindex 350e4dc13..bb7f57688 100644--- a/docs/api-reference/integrations/update-webhook-integration.mdx+++ b/docs/api-reference/integrations/update-webhook-integration.mdx@@ -33,7 +33,7 @@ Configuration object containing webhook details. All fields are optional.<Expandable title="data properties"><ParamField body="webhook_url" type="string">-The updated URL where form submissions will be sent. Must be a valid HTTP/HTTPS URL.+The updated URL where form submissions will be sent. Must be a valid HTTPS URL that resolves only to public IP addresses. Private, loopback, link-local, and cloud metadata addresses are rejected.</ParamField><ParamField body="webhook_secret" type="string">@@ -108,6 +108,7 @@ curl -X PUT 'https://api.opnform.com/open/forms/123/integrations/42' \{"message": "The given data was invalid.","errors": {+ "data.webhook_url": ["The webhook URL must use HTTPS."],"data.webhook_secret": ["The webhook secret must be at least 12 characters."],"data.webhook_headers": ["The 'Authorization' header cannot be customized for security reasons."]}@@ -117,6 +118,8 @@ curl -X PUT 'https://api.opnform.com/open/forms/123/integrations/42' \## Security+Webhook URLs are validated when they are saved and again before each delivery. OpnForm does not follow webhook redirects, and private network destinations are blocked unless the instance operator explicitly enables private webhook URLs for a self-hosted deployment.+### Secret RotationWhen updating the `webhook_secret`, the new secret will be used for all future webhook requests. Existing webhook attempts with the old secret will fail validation on the receiver's end.diff --git a/docs/configuration/oidc-sso.mdx b/docs/configuration/oidc-sso.mdxindex 86346620e..75a159394 100644--- a/docs/configuration/oidc-sso.mdx+++ b/docs/configuration/oidc-sso.mdx@@ -252,6 +252,12 @@ OpnForm is compatible with any OIDC-compliant identity provider, including:In production, all OIDC redirects require HTTPS. Ensure your application is served over HTTPS before configuring OIDC.+### State Validation++OpnForm generates and validates an OIDC `state` value by default for login redirects. Callback requests without a valid, unexpired state are rejected to prevent login CSRF.++State validation can be disabled explicitly on an OIDC connection by setting `options.require_state` to `false`, but this is not recommended unless required for a legacy identity provider.+### Account LinkingFor security, OpnForm prevents automatic linking of existing accounts. If a user with the same email already exists but isn't linked to the OIDC connection, authentication will fail with a message to contact the administrator.