From 033752e9241d526f8894d093183cfd5c6a320184 Mon Sep 17 00:00:00 2001 From: "Sebastian BURGIN-FIX (ext)" Date: Thu, 29 Oct 2026 08:36:04 +0100 Subject: [PATCH 1/2] feat(forms): protect network request and internship application with Cloudflare Turnstile The network request and internship application forms are the public, unauthenticated POSTs of the site. The honeypot and per-IP throttle stay; Turnstile adds a server-side verified bot check alongside them. - TurnstileRule verifies the token against Cloudflare siteverify (5 s timeout) and fails on missing, invalid or unverifiable tokens - widget and check are active only when TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY are set, so local development and CI need no keys - both GET pages already use DoNotCacheResponse, so no cached copy can serve a stale widget - CSP allows challenges.cloudflare.com for scripts and frames - the token is neither stored nor mailed; the controllers only read email - signed application and manage routes are unchanged Co-Authored-By: Claude Opus 5.5 --- .env.example | 4 + .../Jobs/ApplicationRequestStoreRequest.php | 2 + .../Network/NetworkRequestStoreRequest.php | 2 + app/Rules/TurnstileRule.php | 67 +++++++++++++++++ app/Security/Presets/MyCspPreset.php | 7 +- config/services.php | 7 ++ lang/de_CH.json | 1 + lang/en_CH.json | 1 + .../views/app/jobs/partials/apply.blade.php | 2 + resources/views/app/network/request.blade.php | 2 + .../views/components/form/turnstile.blade.php | 17 +++++ tests/Browser/TurnstileTest.php | 74 +++++++++++++++++++ .../Jobs/ApplicationRequestControllerTest.php | 68 +++++++++++++++++ .../Network/NetworkRequestControllerTest.php | 66 +++++++++++++++++ tests/Unit/Rules/TurnstileRuleTest.php | 69 +++++++++++++++++ tests/Unit/Security/MyCspPresetTest.php | 12 +++ 16 files changed, 400 insertions(+), 1 deletion(-) create mode 100644 app/Rules/TurnstileRule.php create mode 100644 resources/views/components/form/turnstile.blade.php create mode 100644 tests/Browser/TurnstileTest.php create mode 100644 tests/Unit/Rules/TurnstileRuleTest.php diff --git a/.env.example b/.env.example index 883c8bdd..68e01f9b 100644 --- a/.env.example +++ b/.env.example @@ -73,6 +73,10 @@ CODEBAR_ANALYTICS_URL=https://analytics.codebar.ch LITELLM_URL=https://llm.codebar.net LITELLM_MASTER_KEY= GITHUB_TOKEN= +# Cloudflare Turnstile for the network request and internship forms (check stays off without a secret). +# Cloudflare test keys that always pass: 1x00000000000000000000AA / 1x0000000000000000000000000000000AA +TURNSTILE_SITE_KEY= +TURNSTILE_SECRET_KEY= # Where a failing health check reports to. Unset means no notification is sent. HEALTH_NOTIFICATION_EMAIL= diff --git a/app/Http/Requests/Jobs/ApplicationRequestStoreRequest.php b/app/Http/Requests/Jobs/ApplicationRequestStoreRequest.php index de085326..1a1dc6b3 100644 --- a/app/Http/Requests/Jobs/ApplicationRequestStoreRequest.php +++ b/app/Http/Requests/Jobs/ApplicationRequestStoreRequest.php @@ -4,6 +4,7 @@ namespace App\Http\Requests\Jobs; +use App\Rules\TurnstileRule; use Illuminate\Foundation\Http\FormRequest; class ApplicationRequestStoreRequest extends FormRequest @@ -20,6 +21,7 @@ public function rules(): array { return [ 'email' => ['required', 'email', 'max:255'], + ...TurnstileRule::rules(), ]; } } diff --git a/app/Http/Requests/Network/NetworkRequestStoreRequest.php b/app/Http/Requests/Network/NetworkRequestStoreRequest.php index 666a34f9..8f7231ab 100644 --- a/app/Http/Requests/Network/NetworkRequestStoreRequest.php +++ b/app/Http/Requests/Network/NetworkRequestStoreRequest.php @@ -4,6 +4,7 @@ namespace App\Http\Requests\Network; +use App\Rules\TurnstileRule; use Illuminate\Foundation\Http\FormRequest; class NetworkRequestStoreRequest extends FormRequest @@ -20,6 +21,7 @@ public function rules(): array { return [ 'email' => ['required', 'email', 'max:255'], + ...TurnstileRule::rules(), ]; } } diff --git a/app/Rules/TurnstileRule.php b/app/Rules/TurnstileRule.php new file mode 100644 index 00000000..172381ab --- /dev/null +++ b/app/Rules/TurnstileRule.php @@ -0,0 +1,67 @@ +> + */ + public static function rules(): array + { + return filled(config('services.turnstile.secret_key')) + ? [self::FIELD => [new self]] + : []; + } + + public function validate(string $attribute, mixed $value, Closure $fail): void + { + if (! is_string($value) || $value === '') { + $fail(__('The spam check failed. Please reload the page and try again.')); + + return; + } + + try { + $response = Http::asForm() + ->timeout(5) + ->post(self::VERIFY_URL, [ + 'secret' => config('services.turnstile.secret_key'), + 'response' => $value, + 'remoteip' => request()->ip(), + ]); + } catch (ConnectionException) { + $fail(__('The spam check failed. Please reload the page and try again.')); + + return; + } + + if ($response->json('success') !== true) { + $fail(__('The spam check failed. Please reload the page and try again.')); + } + } +} diff --git a/app/Security/Presets/MyCspPreset.php b/app/Security/Presets/MyCspPreset.php index dae317c6..e2ca3c14 100644 --- a/app/Security/Presets/MyCspPreset.php +++ b/app/Security/Presets/MyCspPreset.php @@ -19,6 +19,7 @@ public function configure(Policy $policy): void $scriptSources = array_filter([ Keyword::SELF, 'analytics.codebar.ch', + 'challenges.cloudflare.com', $cdnHost ?: null, ]); @@ -28,7 +29,11 @@ public function configure(Policy $policy): void $policy->add(Directive::FRAME_ANCESTORS, Keyword::SELF); - $policy->add(Directive::FRAME, 'player.vimeo.com'); + $policy->add(Directive::FRAME, [ + 'player.vimeo.com', + // Cloudflare Turnstile renders its challenge in an iframe. + 'challenges.cloudflare.com', + ]); $policy->add(Directive::UPGRADE_INSECURE_REQUESTS, Value::NO_VALUE); diff --git a/config/services.php b/config/services.php index 94987c59..595999c8 100644 --- a/config/services.php +++ b/config/services.php @@ -24,4 +24,11 @@ 'token' => env('GITHUB_TOKEN'), ], + // Bot protection for the public network request and internship forms; leaving the + // secret empty disables the check (local development, CI). + 'turnstile' => [ + 'site_key' => env('TURNSTILE_SITE_KEY'), + 'secret_key' => env('TURNSTILE_SECRET_KEY'), + ], + ]; diff --git a/lang/de_CH.json b/lang/de_CH.json index fe1e838b..7f1ad88a 100644 --- a/lang/de_CH.json +++ b/lang/de_CH.json @@ -390,6 +390,7 @@ "The company image is a raw upload — please convert it to Cloudinary.": "Das Firmenbild ist ein Roh-Upload — bitte nach Cloudinary konvertieren.", "The document has been removed.": "Das Dokument wurde entfernt.", "The largest hackathon in the Basel region": "Der grösste Hackathon der Region Basel", + "The spam check failed. Please reload the page and try again.": "Die Spam-Prüfung ist fehlgeschlagen. Bitte lade die Seite neu und versuche es erneut.", "The tools and technologies we work with every day — deliberately chosen, and mastered in real depth over the years.": "Die Werkzeuge und Technologien, mit denen wir täglich arbeiten — bewusst gewählt und über Jahre in der Tiefe beherrscht.", "This is your personal link to your application. It is valid for 7 days — after that, simply enter your email address again on the job page to receive a fresh one.": "Das ist dein persönlicher Link zu deiner Bewerbung. Er ist 7 Tage gültig – danach gibst du einfach nochmals deine E-Mail-Adresse auf der Stellenseite ein und erhältst einen neuen.", "Thursday": "Donnerstag", diff --git a/lang/en_CH.json b/lang/en_CH.json index d588efa8..2c6e9637 100644 --- a/lang/en_CH.json +++ b/lang/en_CH.json @@ -386,6 +386,7 @@ "The company image is a raw upload — please convert it to Cloudinary.": "The company image is a raw upload — please convert it to Cloudinary.", "The document has been removed.": "The document has been removed.", "The largest hackathon in the Basel region": "The largest hackathon in the Basel region", + "The spam check failed. Please reload the page and try again.": "The spam check failed. Please reload the page and try again.", "The tools and technologies we work with every day — deliberately chosen, and mastered in real depth over the years.": "The tools and technologies we work with every day — deliberately chosen, and mastered in real depth over the years.", "This is your personal link to your application. It is valid for 7 days — after that, simply enter your email address again on the job page to receive a fresh one.": "This is your personal link to your application. It is valid for 7 days — after that, simply enter your email address again on the job page to receive a fresh one.", "Thursday": "Thursday", diff --git a/resources/views/app/jobs/partials/apply.blade.php b/resources/views/app/jobs/partials/apply.blade.php index 109f9be1..b4d9e51e 100644 --- a/resources/views/app/jobs/partials/apply.blade.php +++ b/resources/views/app/jobs/partials/apply.blade.php @@ -12,6 +12,8 @@ + +

diff --git a/resources/views/app/network/request.blade.php b/resources/views/app/network/request.blade.php index 03d46307..8ac7fe7a 100644 --- a/resources/views/app/network/request.blade.php +++ b/resources/views/app/network/request.blade.php @@ -20,6 +20,8 @@ + + diff --git a/resources/views/components/form/turnstile.blade.php b/resources/views/components/form/turnstile.blade.php new file mode 100644 index 00000000..0fd6624e --- /dev/null +++ b/resources/views/components/form/turnstile.blade.php @@ -0,0 +1,17 @@ +{{-- Cloudflare Turnstile bot check for public forms. Renders nothing without a site key, + so local development and CI keep working; TurnstileRule verifies the token the widget + writes into a hidden cf-turnstile-response input. Only use it on pages behind + DoNotCacheResponse, or a cached copy would keep serving the old widget state. --}} +@if(filled(config('services.turnstile.site_key'))) +

merge(['class' => 'mt-4']) }}> + +
+ + @error(\App\Rules\TurnstileRule::FIELD) +

{{ $message }}

+ @enderror +
+@endif diff --git a/tests/Browser/TurnstileTest.php b/tests/Browser/TurnstileTest.php new file mode 100644 index 00000000..ffd01ca9 --- /dev/null +++ b/tests/Browser/TurnstileTest.php @@ -0,0 +1,74 @@ + false, + 'services.turnstile.site_key' => TURNSTILE_TEST_SITE_KEY, + 'services.turnstile.secret_key' => $secret, + ]); + + $page = visit($path); + + // The widget solves the challenge asynchronously and writes the token into a hidden input. + $token = 'document.querySelector(\'input[name="'.TurnstileRule::FIELD.'"]\')?.value'; + + foreach (range(1, 20) as $attempt) { + if (filled($page->script($token))) { + break; + } + + $page->wait(0.5); + } + + $page->assertScript($token.'.length > 0'); + + return $page; +} + +it('sends the network link once turnstile has passed', function () { + Bus::fake([SendNetworkManageLinkJob::class]); + + visitWithTurnstile('/netzwerk/request', TURNSTILE_TEST_SECRET_PASSES) + ->type('email', 'vincenzo@example.com') + ->click('main form button[type="submit"]') + ->assertSee(__('If the email address is registered, we have sent you a link.', [], 'de_CH')) + ->assertNoJavaScriptErrors(); + + Bus::assertDispatched(SendNetworkManageLinkJob::class); +})->group('browser', 'turnstile'); + +it('rejects the internship request when cloudflare refuses the token', function () { + JobPosition::factory()->create([ + 'key' => Application::JOB_KEY_INTERNSHIP, + 'status' => JobPositionStatusEnum::Open, + 'route_name' => 'jobs.internship.show', + ]); + + visitWithTurnstile('/stellen/praktikum', TURNSTILE_TEST_SECRET_FAILS) + ->type('input[name="email"]', 'mina@example.com') + ->click('form[action$="/stellen/praktikum"] button[type="submit"]') + ->assertSee(__('The spam check failed. Please reload the page and try again.', [], 'de_CH')); + + assertDatabaseCount('applications', 0); +})->group('browser', 'turnstile'); diff --git a/tests/Feature/Controllers/Jobs/ApplicationRequestControllerTest.php b/tests/Feature/Controllers/Jobs/ApplicationRequestControllerTest.php index 1bb070d0..6be120f5 100644 --- a/tests/Feature/Controllers/Jobs/ApplicationRequestControllerTest.php +++ b/tests/Feature/Controllers/Jobs/ApplicationRequestControllerTest.php @@ -8,8 +8,12 @@ use App\Jobs\Applications\SendApplicationLinkJob; use App\Models\Application; use App\Models\JobPosition; +use App\Rules\TurnstileRule; +use Illuminate\Http\Client\ConnectionException; +use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Crypt; +use Illuminate\Support\Facades\Http; use function Pest\Laravel\assertDatabaseCount; use function Pest\Laravel\get; @@ -191,3 +195,67 @@ Bus::assertNotDispatched(SendApplicationLinkJob::class); assertDatabaseCount('applications', 0); })->group('applications'); + +it('renders the turnstile widget on the internship page when a site key is configured', function () { + config(['services.turnstile.site_key' => 'test-site-key']); + + get(route('de-ch.jobs.internship.show')) + ->assertOk() + ->assertSee('challenges.cloudflare.com/turnstile/v0/api.js', false) + ->assertSee('data-sitekey="test-site-key"', false) + ->assertSee('data-language="de"', false); +})->group('applications', 'turnstile'); + +it('omits the turnstile widget on the internship page without a site key', function () { + config(['services.turnstile.site_key' => null]); + + get(route('de-ch.jobs.internship.show')) + ->assertOk() + ->assertDontSee('cf-turnstile', false); +})->group('applications', 'turnstile'); + +it('creates the application when the turnstile token is valid', function () { + Bus::fake(); + config(['services.turnstile.secret_key' => 'test-secret']); + Http::fake([TurnstileRule::VERIFY_URL => Http::response(['success' => true])]); + + post(route('de-ch.jobs.internship.request.store'), [ + 'email' => 'mina@example.com', + TurnstileRule::FIELD => 'valid-token', + ]) + ->assertSessionHasNoErrors() + ->assertRedirect(route('de-ch.jobs.internship.show')); + + assertDatabaseCount('applications', 1); + Bus::assertDispatched(SendApplicationLinkJob::class); + Http::assertSent(fn (Request $request) => $request['secret'] === 'test-secret' + && $request['response'] === 'valid-token'); +})->group('applications', 'turnstile'); + +it('rejects the application request when the turnstile token is missing, rejected or unverifiable', function (array $payload, Closure $fake) { + Bus::fake(); + config(['services.turnstile.secret_key' => 'test-secret']); + $fake(); + + post(route('de-ch.jobs.internship.request.store'), ['email' => 'mina@example.com', ...$payload]) + ->assertSessionHasErrors([TurnstileRule::FIELD => __('The spam check failed. Please reload the page and try again.')]); + + Bus::assertNotDispatched(SendApplicationLinkJob::class); + assertDatabaseCount('applications', 0); +})->with([ + 'missing' => [[], fn () => Http::fake()], + 'rejected' => [[TurnstileRule::FIELD => 'forged-token'], fn () => Http::fake([TurnstileRule::VERIFY_URL => Http::response(['success' => false])])], + 'unreachable' => [[TurnstileRule::FIELD => 'valid-token'], fn () => Http::fake(fn () => throw new ConnectionException('timeout'))], +])->group('applications', 'turnstile'); + +it('skips the turnstile check when no secret is configured', function () { + Bus::fake(); + config(['services.turnstile.secret_key' => null]); + Http::fake(); + + post(route('de-ch.jobs.internship.request.store'), ['email' => 'mina@example.com']) + ->assertSessionHasNoErrors(); + + assertDatabaseCount('applications', 1); + Http::assertNothingSent(); +})->group('applications', 'turnstile'); diff --git a/tests/Feature/Controllers/Network/NetworkRequestControllerTest.php b/tests/Feature/Controllers/Network/NetworkRequestControllerTest.php index ad391370..445d27f2 100644 --- a/tests/Feature/Controllers/Network/NetworkRequestControllerTest.php +++ b/tests/Feature/Controllers/Network/NetworkRequestControllerTest.php @@ -6,7 +6,11 @@ use App\Jobs\Network\SendNetworkManageLinkJob; use App\Models\NetworkUser; use App\Notifications\NetworkManageLinkNotification; +use App\Rules\TurnstileRule; +use Illuminate\Http\Client\ConnectionException; +use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Bus; +use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Notification; use function Pest\Laravel\get; @@ -106,3 +110,65 @@ function (NetworkManageLinkNotification $notification) use ($networkUser) { Bus::assertNotDispatched(SendNetworkManageLinkJob::class); })->group('network'); + +it('renders the turnstile widget when a site key is configured', function () { + config(['services.turnstile.site_key' => 'test-site-key']); + + get(route('en-ch.network.request.index')) + ->assertOk() + ->assertSee('challenges.cloudflare.com/turnstile/v0/api.js', false) + ->assertSee('data-sitekey="test-site-key"', false) + ->assertSee('data-language="en"', false); +})->group('network', 'turnstile'); + +it('omits the turnstile widget without a site key', function () { + config(['services.turnstile.site_key' => null]); + + get(route('de-ch.network.request.index')) + ->assertOk() + ->assertDontSee('cf-turnstile', false); +})->group('network', 'turnstile'); + +it('dispatches the manage link job when the turnstile token is valid', function () { + Bus::fake(); + config(['services.turnstile.secret_key' => 'test-secret']); + Http::fake([TurnstileRule::VERIFY_URL => Http::response(['success' => true])]); + + post(route('de-ch.network.request.store'), [ + 'email' => 'vincenzo@example.com', + TurnstileRule::FIELD => 'valid-token', + ]) + ->assertSessionHasNoErrors() + ->assertRedirect(route('de-ch.network.request.index')); + + Bus::assertDispatched(SendNetworkManageLinkJob::class); + Http::assertSent(fn (Request $request) => $request['secret'] === 'test-secret' + && $request['response'] === 'valid-token'); +})->group('network', 'turnstile'); + +it('rejects the request when the turnstile token is missing, rejected or unverifiable', function (array $payload, Closure $fake) { + Bus::fake(); + config(['services.turnstile.secret_key' => 'test-secret']); + $fake(); + + post(route('de-ch.network.request.store'), ['email' => 'vincenzo@example.com', ...$payload]) + ->assertSessionHasErrors([TurnstileRule::FIELD => __('The spam check failed. Please reload the page and try again.')]); + + Bus::assertNotDispatched(SendNetworkManageLinkJob::class); +})->with([ + 'missing' => [[], fn () => Http::fake()], + 'rejected' => [[TurnstileRule::FIELD => 'forged-token'], fn () => Http::fake([TurnstileRule::VERIFY_URL => Http::response(['success' => false])])], + 'unreachable' => [[TurnstileRule::FIELD => 'valid-token'], fn () => Http::fake(fn () => throw new ConnectionException('timeout'))], +])->group('network', 'turnstile'); + +it('skips the turnstile check when no secret is configured', function () { + Bus::fake(); + config(['services.turnstile.secret_key' => null]); + Http::fake(); + + post(route('de-ch.network.request.store'), ['email' => 'vincenzo@example.com']) + ->assertSessionHasNoErrors(); + + Bus::assertDispatched(SendNetworkManageLinkJob::class); + Http::assertNothingSent(); +})->group('network', 'turnstile'); diff --git a/tests/Unit/Rules/TurnstileRuleTest.php b/tests/Unit/Rules/TurnstileRuleTest.php new file mode 100644 index 00000000..62bed393 --- /dev/null +++ b/tests/Unit/Rules/TurnstileRuleTest.php @@ -0,0 +1,69 @@ + $data + */ +function turnstileFails(array $data): bool +{ + return Validator::make($data, [TurnstileRule::FIELD => [new TurnstileRule]])->fails(); +} + +beforeEach(function () { + config(['services.turnstile.secret_key' => 'test-secret']); +}); + +it('passes when cloudflare confirms the token', function () { + Http::fake([TurnstileRule::VERIFY_URL => Http::response(['success' => true])]); + + expect(turnstileFails([TurnstileRule::FIELD => 'valid-token']))->toBeFalse(); + + Http::assertSent(fn (Request $request) => $request['secret'] === 'test-secret' + && $request['response'] === 'valid-token'); +})->group('unit', 'turnstile'); + +it('fails when cloudflare rejects the token', function () { + Http::fake([TurnstileRule::VERIFY_URL => Http::response(['success' => false, 'error-codes' => ['invalid-input-response']])]); + + expect(turnstileFails([TurnstileRule::FIELD => 'forged-token']))->toBeTrue(); +})->group('unit', 'turnstile'); + +it('fails without calling cloudflare when the token is missing', function () { + Http::fake(); + + expect(turnstileFails([]))->toBeTrue(); + + Http::assertNothingSent(); +})->group('unit', 'turnstile'); + +it('fails without calling cloudflare when the token is empty or not a string', function (mixed $token) { + Http::fake(); + + expect(turnstileFails([TurnstileRule::FIELD => $token]))->toBeTrue(); + + Http::assertNothingSent(); +})->with([ + 'empty' => [''], + 'not a string' => [['x']], +])->group('unit', 'turnstile'); + +it('fails when cloudflare is unreachable', function () { + Http::fake(fn () => throw new ConnectionException('timeout')); + + expect(turnstileFails([TurnstileRule::FIELD => 'valid-token']))->toBeTrue(); +})->group('unit', 'turnstile'); + +it('adds the rule only when a secret is configured', function () { + expect(TurnstileRule::rules())->toHaveKey(TurnstileRule::FIELD); + + config(['services.turnstile.secret_key' => null]); + + expect(TurnstileRule::rules())->toBe([]); +})->group('unit', 'turnstile'); diff --git a/tests/Unit/Security/MyCspPresetTest.php b/tests/Unit/Security/MyCspPresetTest.php index b2b2277d..6fb21e29 100644 --- a/tests/Unit/Security/MyCspPresetTest.php +++ b/tests/Unit/Security/MyCspPresetTest.php @@ -31,3 +31,15 @@ ->toMatch('/script-src [^;]*analytics\.codebar\.ch/') ->toMatch('/connect-src [^;]*analytics\.codebar\.ch/'); })->group('unit', 'security'); + +it('allows the cloudflare turnstile script and challenge frame', function () { + $policy = new Policy; + + (new MyCspPreset)->configure($policy); + + expect($policy->getContents()) + ->toMatch('/script-src [^;]*challenges\.cloudflare\.com/') + ->toMatch('/script-src-elem [^;]*challenges\.cloudflare\.com/') + ->toMatch('/frame-src [^;]*challenges\.cloudflare\.com/') + ->toMatch('/frame-src [^;]*player\.vimeo\.com/'); +})->group('unit', 'security'); From eb05bfea156ecdf26a8b6525c9716e02e1e6aa47 Mon Sep 17 00:00:00 2001 From: "Sebastian BURGIN-FIX (ext)" Date: Thu, 29 Oct 2026 09:16:17 +0100 Subject: [PATCH 2/2] test: keep Cloudflare Turnstile off in the test suite A developer .env with real TURNSTILE_* keys switched the check on for every form test that posts without a token. phpunit now blanks both keys; tests that cover Turnstile enable it themselves. Co-Authored-By: Claude Opus 5.5 --- phpunit.xml.dist | 2 ++ 1 file changed, 2 insertions(+) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index e953638e..20e7fe02 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -34,6 +34,8 @@ + +