Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
2 changes: 2 additions & 0 deletions app/Http/Requests/Jobs/ApplicationRequestStoreRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace App\Http\Requests\Jobs;

use App\Rules\TurnstileRule;
use Illuminate\Foundation\Http\FormRequest;

class ApplicationRequestStoreRequest extends FormRequest
Expand All @@ -20,6 +21,7 @@ public function rules(): array
{
return [
'email' => ['required', 'email', 'max:255'],
...TurnstileRule::rules(),
];
}
}
2 changes: 2 additions & 0 deletions app/Http/Requests/Network/NetworkRequestStoreRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace App\Http\Requests\Network;

use App\Rules\TurnstileRule;
use Illuminate\Foundation\Http\FormRequest;

class NetworkRequestStoreRequest extends FormRequest
Expand All @@ -20,6 +21,7 @@ public function rules(): array
{
return [
'email' => ['required', 'email', 'max:255'],
...TurnstileRule::rules(),
];
}
}
67 changes: 67 additions & 0 deletions app/Rules/TurnstileRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

declare(strict_types=1);

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;

/**
* Verifies a Cloudflare Turnstile token server-side.
*
* @see https://developers.cloudflare.com/turnstile/get-started/server-side-validation/
*/
class TurnstileRule implements ValidationRule
{
public const string FIELD = 'cf-turnstile-response';

public const string VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';

/**
* Run even when the field is missing, so a bot cannot skip the check by omitting the token.
*/
public bool $implicit = true;

/**
* Adds the rule only when a secret is configured, so local development and CI
* work without Cloudflare keys.
*
* @return array<string, list<self>>
*/
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.'));
}
}
}
7 changes: 6 additions & 1 deletion app/Security/Presets/MyCspPreset.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public function configure(Policy $policy): void
$scriptSources = array_filter([
Keyword::SELF,
'analytics.codebar.ch',
'challenges.cloudflare.com',
$cdnHost ?: null,
]);

Expand All @@ -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);

Expand Down
7 changes: 7 additions & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
],

];
1 change: 1 addition & 0 deletions lang/de_CH.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions lang/en_CH.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 2 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
</exclude>
</source>
<php>
<env name="TURNSTILE_SITE_KEY" value=""/>
<env name="TURNSTILE_SECRET_KEY" value=""/>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
Expand Down
2 changes: 2 additions & 0 deletions resources/views/app/jobs/partials/apply.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

<x-ui.button :label="__('Start my application')" class="w-full sm:w-auto"/>
</div>

<x-form.turnstile/>
</form>

<p class="mt-4 text-sm text-muted">
Expand Down
2 changes: 2 additions & 0 deletions resources/views/app/network/request.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
<x-form.input name="email" type="email" required autofocus/>
</x-form.field>

<x-form.turnstile/>

<x-form.actions>
<x-ui.button :label="__('Request link')"/>
</x-form.actions>
Expand Down
17 changes: 17 additions & 0 deletions resources/views/components/form/turnstile.blade.php
Original file line number Diff line number Diff line change
@@ -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')))
<div {{ $attributes->merge(['class' => 'mt-4']) }}>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<div class="cf-turnstile"
data-sitekey="{{ config('services.turnstile.site_key') }}"
data-language="{{ str(app()->getLocale())->before('_') }}"
data-size="flexible"></div>

@error(\App\Rules\TurnstileRule::FIELD)
<p id="cf-turnstile-response-error" class="mt-1.5 text-sm text-red-600">{{ $message }}</p>
@enderror
</div>
@endif
74 changes: 74 additions & 0 deletions tests/Browser/TurnstileTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

declare(strict_types=1);

use App\Enums\JobPositionStatusEnum;
use App\Jobs\Network\SendNetworkManageLinkJob;
use App\Models\Application;
use App\Models\JobPosition;
use App\Rules\TurnstileRule;
use Illuminate\Support\Facades\Bus;
use Pest\Browser\Api\PendingAwaitablePage;

use function Pest\Laravel\assertDatabaseCount;

/*
* Runs against the real Cloudflare Turnstile API with Cloudflare's documented test keys,
* which work on any hostname: https://developers.cloudflare.com/turnstile/troubleshooting/testing/
*/
const TURNSTILE_TEST_SITE_KEY = '1x00000000000000000000AA';
const TURNSTILE_TEST_SECRET_PASSES = '1x0000000000000000000000000000000AA';
const TURNSTILE_TEST_SECRET_FAILS = '2x0000000000000000000000000000000AA';

function visitWithTurnstile(string $path, string $secret): PendingAwaitablePage
{
config([
'honeypot.valid_from_timestamp' => 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');
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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');
Loading
Loading