From 139738c5b47aac5c2554ba3b04de3d54455a651b Mon Sep 17 00:00:00 2001 From: "Sebastian BURGIN-FIX (ext)" Date: Fri, 30 Oct 2026 08:07:32 +0100 Subject: [PATCH 1/3] feat(health): add TurnstileKeysCheck for Cloudflare Turnstile Verifies the Turnstile keys hourly so a broken form is caught before visitors run into it. Sends a dummy token to siteverify: a valid secret answers invalid-input-response, a wrong one invalid-input-secret. Fails when the secret is rejected, when a secret is set without a site key (the widget cannot render, every submit is rejected), when Cloudflare is unreachable (the form rule rejects then too) and when production runs on test keys. Warns when a site key has no secret (forms unprotected). Reports ok when Turnstile is not configured. Same check as codebar-ag/laravel-start#139, registered after PostmarkTokenCheck. Co-Authored-By: Claude Opus 5.5 --- app/Checks/TurnstileKeysCheck.php | 112 +++++++++++++++++++ app/Providers/AppServiceProvider.php | 2 + tests/Unit/Checks/TurnstileKeysCheckTest.php | 84 ++++++++++++++ 3 files changed, 198 insertions(+) create mode 100644 app/Checks/TurnstileKeysCheck.php create mode 100644 tests/Unit/Checks/TurnstileKeysCheckTest.php diff --git a/app/Checks/TurnstileKeysCheck.php b/app/Checks/TurnstileKeysCheck.php new file mode 100644 index 0000000..971d002 --- /dev/null +++ b/app/Checks/TurnstileKeysCheck.php @@ -0,0 +1,112 @@ +key('services.turnstile.site_key'); + $secretKey = $this->key('services.turnstile.secret_key'); + $result = Result::make(); + + if ($siteKey === '' && $secretKey === '') { + return $result->shortSummary('not configured')->ok(); + } + + if ($secretKey === '') { + return $result->shortSummary('no secret key') + ->warning('TURNSTILE_SITE_KEY is set without TURNSTILE_SECRET_KEY: the forms are not protected against spam.'); + } + + if ($siteKey === '') { + return $result->shortSummary('no site key') + ->failed('TURNSTILE_SECRET_KEY is set without TURNSTILE_SITE_KEY: the widget cannot render, so every form submit is rejected.'); + } + + if (app()->isProduction() && ! $this->isProductionKey($siteKey, $secretKey)) { + return $result->shortSummary('test keys') + ->failed('Production uses Cloudflare Turnstile test keys: they either let every bot through or reject every submit.'); + } + + try { + $response = Http::asForm()->timeout(3)->post(self::VERIFY_URL, [ + 'secret' => $secretKey, + 'response' => 'health-check', + ]); + } catch (Throwable $exception) { + return $result->shortSummary('cloudflare unreachable') + ->failed("Cloudflare Turnstile request failed, so form submits are rejected too: {$exception->getMessage()}"); + } + + $errors = $this->errorCodes($response); + + if (in_array('invalid-input-secret', $errors, true)) { + return $result->shortSummary('secret rejected') + ->failed('Cloudflare rejected TURNSTILE_SECRET_KEY, so every form submit is rejected.'); + } + + if ($response->json('metadata.result_with_testing_key') === true) { + return $result->shortSummary('test keys')->ok(); + } + + if (in_array('invalid-input-response', $errors, true)) { + return $result->shortSummary('secret valid')->ok(); + } + + return $result->shortSummary("http {$response->status()}") + ->failed('Unexpected Cloudflare Turnstile answer: '.($errors === [] ? $response->status() : implode(', ', $errors)).'.'); + } + + private function key(string $configKey): string + { + $value = config($configKey); + + return is_string($value) ? trim($value) : ''; + } + + private function isProductionKey(string ...$keys): bool + { + foreach ($keys as $key) { + if (! str_starts_with($key, self::PRODUCTION_KEY_PREFIX)) { + return false; + } + } + + return true; + } + + /** + * @return list + */ + private function errorCodes(Response $response): array + { + $codes = $response->json('error-codes'); + + return is_array($codes) ? array_values(array_filter($codes, is_string(...))) : []; + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 688622a..3d93865 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -15,6 +15,7 @@ use App\Checks\ProductionConfigCheck; use App\Checks\SchedulePolicyCheck; use App\Checks\StorageRoundTripCheck; +use App\Checks\TurnstileKeysCheck; use App\Models\AiModel; use App\Models\Network; use App\Models\NetworkUser; @@ -92,6 +93,7 @@ public function boot(): void StorageRoundTripCheck::new(), EntraClientSecretCheck::new(), PostmarkTokenCheck::new(), + TurnstileKeysCheck::new(), ]); } diff --git a/tests/Unit/Checks/TurnstileKeysCheckTest.php b/tests/Unit/Checks/TurnstileKeysCheckTest.php new file mode 100644 index 0000000..97695b1 --- /dev/null +++ b/tests/Unit/Checks/TurnstileKeysCheckTest.php @@ -0,0 +1,84 @@ + '0x4AAAAAAAsite', 'services.turnstile.secret_key' => '0x4AAAAAAAsecret']); +}); + +it('passes when Cloudflare accepts the secret', function () { + Http::fake([TurnstileKeysCheck::VERIFY_URL => Http::response(['success' => false, 'error-codes' => ['invalid-input-response']])]); + + $result = (new TurnstileKeysCheck)->run(); + + expect($result->status->equals(Status::ok()))->toBeTrue() + ->and($result->shortSummary)->toBe('secret valid'); + Http::assertSent(fn (Request $request): bool => $request['secret'] === '0x4AAAAAAAsecret' && $request['response'] === 'health-check'); +})->group('unit', 'checks'); + +it('fails when Cloudflare rejects the secret', function () { + Http::fake([TurnstileKeysCheck::VERIFY_URL => Http::response(['success' => false, 'error-codes' => ['invalid-input-secret']], 400)]); + + expect((new TurnstileKeysCheck)->run()->shortSummary)->toBe('secret rejected'); +})->group('unit', 'checks'); + +it('passes without a request when Turnstile is not configured', function () { + config(['services.turnstile.site_key' => null, 'services.turnstile.secret_key' => null]); + Http::fake(); + + expect((new TurnstileKeysCheck)->run()->status->equals(Status::ok()))->toBeTrue(); + Http::assertNothingSent(); +})->group('unit', 'checks'); + +it('fails when the secret is set without a site key', function () { + config(['services.turnstile.site_key' => '']); + Http::fake(); + + expect((new TurnstileKeysCheck)->run()->status->equals(Status::failed()))->toBeTrue(); + Http::assertNothingSent(); +})->group('unit', 'checks'); + +it('warns when the site key is set without a secret', function () { + config(['services.turnstile.secret_key' => '']); + Http::fake(); + + expect((new TurnstileKeysCheck)->run()->status->equals(Status::warning()))->toBeTrue(); + Http::assertNothingSent(); +})->group('unit', 'checks'); + +it('fails when production runs on test keys', function () { + app()->detectEnvironment(fn (): string => 'production'); + config(['services.turnstile.site_key' => '1x00000000000000000000AA', 'services.turnstile.secret_key' => '1x0000000000000000000000000000000AA']); + Http::fake(); + + $summary = (new TurnstileKeysCheck)->run()->shortSummary; + app()->detectEnvironment(fn (): string => 'testing'); + + expect($summary)->toBe('test keys'); + Http::assertNothingSent(); +})->group('unit', 'checks'); + +it('passes with test keys outside production', function () { + config(['services.turnstile.site_key' => '1x00000000000000000000AA', 'services.turnstile.secret_key' => '1x0000000000000000000000000000000AA']); + Http::fake([TurnstileKeysCheck::VERIFY_URL => Http::response(['success' => true, 'error-codes' => [], 'metadata' => ['result_with_testing_key' => true]])]); + + expect((new TurnstileKeysCheck)->run()->status->equals(Status::ok()))->toBeTrue(); +})->group('unit', 'checks'); + +it('fails when Cloudflare cannot be reached', function () { + Http::fake(fn () => throw new ConnectionException('timeout')); + + expect((new TurnstileKeysCheck)->run()->shortSummary)->toBe('cloudflare unreachable'); +})->group('unit', 'checks'); + +it('reports the HTTP status on an unexpected answer', function () { + Http::fake([TurnstileKeysCheck::VERIFY_URL => Http::response('', 500)]); + + expect((new TurnstileKeysCheck)->run()->getNotificationMessage())->toContain('500'); +})->group('unit', 'checks'); From ee8829aa650ab975963ee55eea558264b4d887b6 Mon Sep 17 00:00:00 2001 From: "Sebastian BURGIN-FIX (ext)" Date: Sat, 31 Oct 2026 10:51:04 +0100 Subject: [PATCH 2/3] fix(health): keep the schedule heartbeat in its own cache table The Schedule check read its heartbeat from the default cache store, which Cache::flush(), cache:clear and optimize:clear (deploy command) wipe; on Redis that empties the whole Redis database, on the database driver the whole cache table. Oh Dear then reports "The schedule did not run yet" until the next hourly beat. The heartbeat now lives in a dedicated "health" store backed by the health_cache table, which nothing flushes. Same fix as codebar-ag/web.thejungledog b04f83e8. Co-Authored-By: Claude Fable 5.1 --- app/Providers/AppServiceProvider.php | 6 +++- config/cache.php | 30 +++++++++++++++++ ...10_31_120000_create_health_cache_table.php | 30 +++++++++++++++++ tests/Feature/Health/ScheduleCheckTest.php | 33 +++++++++++++++++++ 4 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 database/migrations/2026_10_31_120000_create_health_cache_table.php create mode 100644 tests/Feature/Health/ScheduleCheckTest.php diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 3d93865..66729de 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -82,7 +82,11 @@ public function boot(): void DatabaseCheck::new(), DatabaseConnectionCountCheck::new(), CacheCheck::new(), - ScheduleCheck::new()->heartbeatMaxAgeInMinutes(120), + // A database store, because the heartbeat is written by the scheduler and the + // deploy command but read by a web request: on Laravel Cloud these run in + // separate containers, and a file cache is local to each of them. Not the + // default store: Cache::flush() and optimize:clear would wipe it. + ScheduleCheck::new()->useCacheStore('health')->heartbeatMaxAgeInMinutes(120), SecurityAdvisoriesCheck::new(), NightwatchIssuesCheck::new()->if(filled(config('default.nightwatch.api_token')) && filled(config('default.nightwatch.application_id'))), JobsCheck::new(), diff --git a/config/cache.php b/config/cache.php index 1cf9e53..19868b9 100644 --- a/config/cache.php +++ b/config/cache.php @@ -18,6 +18,36 @@ | */ + /* + |-------------------------------------------------------------------------- + | Cache Stores + |-------------------------------------------------------------------------- + | + | Merged into the framework's default stores. Only the stores this + | application adds or changes are listed here. + | + */ + + 'stores' => [ + + 'database' => [ + 'driver' => 'database', + 'connection' => env('DB_CACHE_CONNECTION'), + 'table' => env('DB_CACHE_TABLE', 'cache'), + 'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'), + 'lock_table' => env('DB_CACHE_LOCK_TABLE'), + ], + + // Holds the schedule heartbeat only. Its own table, because Cache::flush() and + // optimize:clear empty the whole table of the default store. + 'health' => [ + 'driver' => 'database', + 'connection' => env('DB_CACHE_CONNECTION'), + 'table' => 'health_cache', + ], + + ], + 'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel'), '_').'_cache_'), ]; diff --git a/database/migrations/2026_10_31_120000_create_health_cache_table.php b/database/migrations/2026_10_31_120000_create_health_cache_table.php new file mode 100644 index 0000000..00a92c7 --- /dev/null +++ b/database/migrations/2026_10_31_120000_create_health_cache_table.php @@ -0,0 +1,30 @@ +string('key')->primary(); + $table->mediumText('value'); + $table->bigInteger('expiration')->index(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('health_cache'); + } +}; diff --git a/tests/Feature/Health/ScheduleCheckTest.php b/tests/Feature/Health/ScheduleCheckTest.php new file mode 100644 index 0000000..7a13faa --- /dev/null +++ b/tests/Feature/Health/ScheduleCheckTest.php @@ -0,0 +1,33 @@ +artisan('health:schedule-check-heartbeat')->assertSuccessful(); + + expect(Cache::store('health')->get('health:checks:schedule:latestHeartbeatAt'))->not->toBeNull(); +})->group('feature', 'health'); + +test('schedule check reads the heartbeat from the health cache store', function () { + $this->artisan('health:schedule-check-heartbeat')->assertSuccessful(); + + $check = collect(Health::registeredChecks())->first(fn ($check) => $check instanceof ScheduleCheck); + + expect($check->run()->status->value)->toBe('ok'); +})->group('feature', 'health'); + +test('flushing the default cache keeps the schedule heartbeat', function () { + config(['cache.default' => 'database']); + + $this->artisan('health:schedule-check-heartbeat')->assertSuccessful(); + + Cache::flush(); + + $check = collect(Health::registeredChecks())->first(fn ($check) => $check instanceof ScheduleCheck); + + expect($check->run()->status->value)->toBe('ok'); +})->group('feature', 'health'); From 686546a3477a026f06526d495c90c76a39a02d9a Mon Sep 17 00:00:00 2001 From: "Sebastian BURGIN-FIX (ext)" Date: Sat, 31 Oct 2026 11:29:21 +0100 Subject: [PATCH 3/3] test(health): make the schedule heartbeat test Larastan-clean Level 10 analyses tests/: use the typed runArtisan() wrapper instead of $this->artisan() and narrow the registered check before calling run(). Co-Authored-By: Claude Fable 5.1 --- tests/Feature/Health/ScheduleCheckTest.php | 24 ++++++++++++++-------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/tests/Feature/Health/ScheduleCheckTest.php b/tests/Feature/Health/ScheduleCheckTest.php index 7a13faa..5e5bd35 100644 --- a/tests/Feature/Health/ScheduleCheckTest.php +++ b/tests/Feature/Health/ScheduleCheckTest.php @@ -6,28 +6,34 @@ use Spatie\Health\Checks\Checks\ScheduleCheck; use Spatie\Health\Facades\Health; +function scheduleCheck(): ScheduleCheck +{ + $check = Health::registeredChecks()->first(fn ($check) => $check instanceof ScheduleCheck); + + expect($check)->toBeInstanceOf(ScheduleCheck::class); + + /** @var ScheduleCheck $check */ + return $check; +} + test('schedule heartbeat is stored in the health cache store', function () { - $this->artisan('health:schedule-check-heartbeat')->assertSuccessful(); + runArtisan('health:schedule-check-heartbeat')->assertSuccessful(); expect(Cache::store('health')->get('health:checks:schedule:latestHeartbeatAt'))->not->toBeNull(); })->group('feature', 'health'); test('schedule check reads the heartbeat from the health cache store', function () { - $this->artisan('health:schedule-check-heartbeat')->assertSuccessful(); + runArtisan('health:schedule-check-heartbeat')->assertSuccessful(); - $check = collect(Health::registeredChecks())->first(fn ($check) => $check instanceof ScheduleCheck); - - expect($check->run()->status->value)->toBe('ok'); + expect(scheduleCheck()->run()->status->value)->toBe('ok'); })->group('feature', 'health'); test('flushing the default cache keeps the schedule heartbeat', function () { config(['cache.default' => 'database']); - $this->artisan('health:schedule-check-heartbeat')->assertSuccessful(); + runArtisan('health:schedule-check-heartbeat')->assertSuccessful(); Cache::flush(); - $check = collect(Health::registeredChecks())->first(fn ($check) => $check instanceof ScheduleCheck); - - expect($check->run()->status->value)->toBe('ok'); + expect(scheduleCheck()->run()->status->value)->toBe('ok'); })->group('feature', 'health');