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
112 changes: 112 additions & 0 deletions app/Checks/TurnstileKeysCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

declare(strict_types=1);

namespace App\Checks;

use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Spatie\Health\Checks\Check;
use Spatie\Health\Checks\Result;
use Throwable;

/**
* Verifies the Cloudflare Turnstile keys behind the protected forms. 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, so every submit
* is rejected), when Cloudflare cannot be reached (the form rule rejects then
* too) and when production runs on Cloudflare test keys. Reports ok when the
* app does not use Turnstile.
*
* @see https://developers.cloudflare.com/turnstile/get-started/server-side-validation/
*/
final class TurnstileKeysCheck extends Check
{
public const string VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';

/** Real keys start with 0x; 1x, 2x and 3x are Cloudflare's test keys. */
private const string PRODUCTION_KEY_PREFIX = '0x';

public function run(): Result
{
$siteKey = $this->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<string>
*/
private function errorCodes(Response $response): array
{
$codes = $response->json('error-codes');

return is_array($codes) ? array_values(array_filter($codes, is_string(...))) : [];
}
}
8 changes: 7 additions & 1 deletion app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(),
Expand All @@ -92,6 +97,7 @@ public function boot(): void
StorageRoundTripCheck::new(),
EntraClientSecretCheck::new(),
PostmarkTokenCheck::new(),
TurnstileKeysCheck::new(),
]);
}

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

];
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('health_cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->bigInteger('expiration')->index();
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('health_cache');
}
};
39 changes: 39 additions & 0 deletions tests/Feature/Health/ScheduleCheckTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Cache;
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 () {
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');
84 changes: 84 additions & 0 deletions tests/Unit/Checks/TurnstileKeysCheckTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

declare(strict_types=1);

use App\Checks\TurnstileKeysCheck;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Spatie\Health\Enums\Status;

beforeEach(function () {
config(['services.turnstile.site_key' => '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');