A plain sha256 of an IPv4 address can be reversed by trying all addresses. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
50 lines
1.6 KiB
PHP
50 lines
1.6 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Service;
|
|
|
|
use Cake\Cache\Cache;
|
|
use Cake\Utility\Security;
|
|
|
|
/**
|
|
* Very small fixed-window rate limiter backed by the "throttle" cache config.
|
|
* Used to limit poll creation and recovery mails per client IP (per hour) and
|
|
* participant answers per client IP (per minute).
|
|
*/
|
|
class ThrottleService
|
|
{
|
|
public const WINDOW_SECONDS = 3600;
|
|
|
|
/**
|
|
* Registers a hit and returns whether the action is still allowed.
|
|
*
|
|
* @param string $bucket Logical action, e.g. "create"
|
|
* @param string $identifier Client identifier, e.g. IP address
|
|
* @param int $limit Allowed hits per window; <= 0 disables throttling
|
|
* @param int $windowSeconds Length of the window
|
|
* @return bool
|
|
*/
|
|
public function attempt(string $bucket, string $identifier, int $limit, int $windowSeconds = self::WINDOW_SECONDS): bool
|
|
{
|
|
if ($limit <= 0) {
|
|
return true;
|
|
}
|
|
|
|
// Keyed hash: a plain sha256 of an IPv4 address can be reversed by trying all 2^32 addresses.
|
|
$key = 'throttle_' . $bucket . '_' . hash_hmac('sha256', $identifier, 'throttle|' . Security::getSalt());
|
|
$now = time();
|
|
/** @var array{start: int, hits: int}|null $state */
|
|
$state = Cache::read($key, 'throttle');
|
|
if (!is_array($state) || $state['start'] + $windowSeconds <= $now) {
|
|
$state = ['start' => $now, 'hits' => 0];
|
|
}
|
|
if ($state['hits'] >= $limit) {
|
|
return false;
|
|
}
|
|
$state['hits']++;
|
|
Cache::write($key, $state, 'throttle');
|
|
|
|
return true;
|
|
}
|
|
}
|