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..66729de 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; @@ -81,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(), @@ -92,6 +97,7 @@ public function boot(): void StorageRoundTripCheck::new(), EntraClientSecretCheck::new(), PostmarkTokenCheck::new(), + TurnstileKeysCheck::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..5e5bd35 --- /dev/null +++ b/tests/Feature/Health/ScheduleCheckTest.php @@ -0,0 +1,39 @@ +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 () { + 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 () { + runArtisan('health:schedule-check-heartbeat')->assertSuccessful(); + + expect(scheduleCheck()->run()->status->value)->toBe('ok'); +})->group('feature', 'health'); + +test('flushing the default cache keeps the schedule heartbeat', function () { + config(['cache.default' => 'database']); + + runArtisan('health:schedule-check-heartbeat')->assertSuccessful(); + + Cache::flush(); + + expect(scheduleCheck()->run()->status->value)->toBe('ok'); +})->group('feature', 'health'); 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');