Implemented: editor uploads are constrained to safe image files inside
the upload tree, and public form submissions are size-bounded and rate-limited
This commit is contained in:
@@ -7,22 +7,44 @@ use Plugi\Extensions\Form\Finishers\FinishersRepository;
|
||||
|
||||
class SubmissionHandler
|
||||
{
|
||||
public const MAX_REQUEST_BYTES = 65536;
|
||||
public const MAX_FIELD_BYTES = 16384;
|
||||
public const MAX_FIELDS = 100;
|
||||
|
||||
private $formsRepository;
|
||||
private $finishersRepository;
|
||||
private $rateLimiter;
|
||||
|
||||
public function __construct($formsRepository = null, $finishersRepository = null)
|
||||
public function __construct($formsRepository = null, $finishersRepository = null, $rateLimiter = null)
|
||||
{
|
||||
$this->formsRepository = $formsRepository ?? new DefinitionsRepository();
|
||||
$this->finishersRepository = $finishersRepository ?? new FinishersRepository();
|
||||
$this->rateLimiter = $rateLimiter ?? new SubmissionRateLimiter();
|
||||
}
|
||||
|
||||
public function handle($formId, string $rawData): array
|
||||
{
|
||||
if (strlen($rawData) > self::MAX_REQUEST_BYTES) {
|
||||
return $this->failure(413, ['The submission is too large.']);
|
||||
}
|
||||
|
||||
$formId = filter_var($formId, FILTER_VALIDATE_INT);
|
||||
if ($formId === false || $formId < 1) {
|
||||
return $this->failure(400, ['A valid form id is required.']);
|
||||
}
|
||||
|
||||
$clientIp = $_SERVER['REMOTE_ADDR'] ?? '';
|
||||
if (!is_string($clientIp) || filter_var($clientIp, FILTER_VALIDATE_IP) === false) {
|
||||
$clientIp = 'unknown';
|
||||
}
|
||||
try {
|
||||
if (!$this->rateLimiter->consume($formId, $clientIp)) {
|
||||
return $this->failure(429, ['Too many submissions. Please try again later.']);
|
||||
}
|
||||
} catch (\Throwable $exception) {
|
||||
return $this->failure(503, ['Submissions are temporarily unavailable.']);
|
||||
}
|
||||
|
||||
try {
|
||||
$form = $this->formsRepository->findWithId($formId);
|
||||
} catch (\Throwable $exception) {
|
||||
@@ -125,6 +147,10 @@ class SubmissionHandler
|
||||
$knownFields = [];
|
||||
$supportedTypes = ['text', 'email', 'textarea', 'checkbox', 'radio', 'select'];
|
||||
|
||||
if (count($submittedFields) > self::MAX_FIELDS) {
|
||||
return ['The submission contains too many fields.'];
|
||||
}
|
||||
|
||||
foreach ($formFields as $field) {
|
||||
if (!is_array($field) || !isset($field['name']) || !is_string($field['name']) || trim($field['name']) === '' || !isset($field['label']) || !is_string($field['label']) || !isset($field['type']) || !is_string($field['type']) || !in_array($field['type'], $supportedTypes, true)) {
|
||||
return ['The form contains an invalid field configuration.'];
|
||||
@@ -160,6 +186,20 @@ class SubmissionHandler
|
||||
if (!is_string($name) || !array_key_exists($name, $knownFields)) {
|
||||
return ['The submission contains an unknown field.'];
|
||||
}
|
||||
$value = $submittedFields[$name];
|
||||
if (is_string($value) && strlen($value) > self::MAX_FIELD_BYTES) {
|
||||
return ['A submitted field is too large.'];
|
||||
}
|
||||
if (is_array($value)) {
|
||||
if (count($value) > self::MAX_FIELDS) {
|
||||
return ['A submitted field contains too many values.'];
|
||||
}
|
||||
foreach ($value as $item) {
|
||||
if (is_string($item) && strlen($item) > self::MAX_FIELD_BYTES) {
|
||||
return ['A submitted field is too large.'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($knownFields as $name => $field) {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace Plugi\Extensions\Form;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class SubmissionRateLimiter
|
||||
{
|
||||
private const MAX_SUBMISSIONS = 5;
|
||||
private const WINDOW_SECONDS = 600;
|
||||
|
||||
private $db;
|
||||
private string $table;
|
||||
|
||||
public function __construct($db = null)
|
||||
{
|
||||
global $phpb_db;
|
||||
|
||||
$this->db = $db ?? $phpb_db ?? null;
|
||||
$prefix = preg_replace('/[^a-zA-Z0-9_]/', '', $_ENV['DATABASE_PREFIX'] ?? '');
|
||||
$this->table = '`' . $prefix . 'ext__form_submission_limits`';
|
||||
}
|
||||
|
||||
public function consume(int $formId, string $clientIp): bool
|
||||
{
|
||||
if (!is_object($this->db)) {
|
||||
throw new RuntimeException('The submission rate limit store is unavailable.');
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$ipHash = hash('sha256', $clientIp);
|
||||
if (!$this->db->query(
|
||||
"INSERT IGNORE INTO {$this->table} (formId, ipHash, startedAt, submissions) VALUES (?, ?, ?, 0)",
|
||||
[$formId, $ipHash, $now]
|
||||
)) {
|
||||
throw new RuntimeException('The submission rate limit could not be initialized.');
|
||||
}
|
||||
|
||||
$allowed = $this->db->transaction(function () use ($formId, $ipHash, $now): bool {
|
||||
$rows = $this->db->select(
|
||||
"SELECT startedAt, submissions FROM {$this->table} WHERE formId = ? AND ipHash = ? FOR UPDATE",
|
||||
[$formId, $ipHash]
|
||||
);
|
||||
if (empty($rows)) {
|
||||
throw new RuntimeException('The submission rate limit could not be loaded.');
|
||||
}
|
||||
|
||||
$startedAt = (int) $rows[0]['startedAt'];
|
||||
$submissions = (int) $rows[0]['submissions'];
|
||||
if ($now - $startedAt >= self::WINDOW_SECONDS) {
|
||||
$startedAt = $now;
|
||||
$submissions = 0;
|
||||
}
|
||||
if ($submissions >= self::MAX_SUBMISSIONS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$this->db->query(
|
||||
"UPDATE {$this->table} SET startedAt = ?, submissions = ? WHERE formId = ? AND ipHash = ?",
|
||||
[$startedAt, $submissions + 1, $formId, $ipHash]
|
||||
)) {
|
||||
throw new RuntimeException('The submission rate limit could not be updated.');
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
if ($allowed && random_int(1, 100) === 1) {
|
||||
try {
|
||||
$this->db->query(
|
||||
"DELETE FROM {$this->table} WHERE startedAt < ?",
|
||||
[$now - (self::WINDOW_SECONDS * 2)]
|
||||
);
|
||||
} catch (\Throwable $exception) {
|
||||
}
|
||||
}
|
||||
|
||||
return $allowed;
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,17 @@ return [
|
||||
],
|
||||
"uniqueKeys" => [],
|
||||
],
|
||||
"submission_limits" => [
|
||||
"columns" => [
|
||||
"formId" => "int NOT NULL",
|
||||
"ipHash" => "char(64) NOT NULL",
|
||||
"startedAt" => "int unsigned NOT NULL",
|
||||
"submissions" => "int unsigned NOT NULL",
|
||||
],
|
||||
"uniqueKeys" => [
|
||||
"form_ip" => ["formId", "ipHash"],
|
||||
],
|
||||
],
|
||||
"definitions" => [
|
||||
"columns" => [
|
||||
"name" => "varchar(255) NOT NULL",
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
<?php
|
||||
|
||||
$handler = new \Plugi\Extensions\Form\SubmissionHandler();
|
||||
$result = $handler->handle($_GET['id'] ?? null, file_get_contents('php://input') ?: '');
|
||||
$rawData = file_get_contents(
|
||||
'php://input',
|
||||
false,
|
||||
null,
|
||||
0,
|
||||
\Plugi\Extensions\Form\SubmissionHandler::MAX_REQUEST_BYTES + 1
|
||||
);
|
||||
$result = $handler->handle($_GET['id'] ?? null, is_string($rawData) ? $rawData : '');
|
||||
|
||||
http_response_code($result['status']);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace FormExtensionTests {
|
||||
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendConfirmationEmailToSubmitter.php';
|
||||
require_once dirname(__DIR__) . '/admin/Classes/Finishers/SendWebhook.php';
|
||||
require_once dirname(__DIR__) . '/admin/Classes/Finishers/FinishersRepository.php';
|
||||
require_once dirname(__DIR__) . '/admin/Classes/SubmissionRateLimiter.php';
|
||||
|
||||
class TestMailer
|
||||
{
|
||||
@@ -160,6 +161,40 @@ namespace FormExtensionTests {
|
||||
return ['class' => $this->finishers[$key]];
|
||||
}
|
||||
}
|
||||
|
||||
class RateLimitDatabase
|
||||
{
|
||||
public array $rows = [];
|
||||
|
||||
public function query(string $query, array $parameters = []): bool
|
||||
{
|
||||
if (str_starts_with($query, 'INSERT IGNORE')) {
|
||||
$key = $parameters[0] . ':' . $parameters[1];
|
||||
$this->rows[$key] ??= ['startedAt' => $parameters[2], 'submissions' => 0];
|
||||
return true;
|
||||
}
|
||||
if (str_starts_with($query, 'UPDATE')) {
|
||||
$key = $parameters[2] . ':' . $parameters[3];
|
||||
$this->rows[$key] = ['startedAt' => $parameters[0], 'submissions' => $parameters[1]];
|
||||
return true;
|
||||
}
|
||||
if (str_starts_with($query, 'DELETE')) {
|
||||
return true;
|
||||
}
|
||||
throw new \RuntimeException('Unexpected rate limiter query.');
|
||||
}
|
||||
|
||||
public function select(string $query, array $parameters): array
|
||||
{
|
||||
$key = $parameters[0] . ':' . $parameters[1];
|
||||
return isset($this->rows[$key]) ? [$this->rows[$key]] : [];
|
||||
}
|
||||
|
||||
public function transaction(callable $callback): mixed
|
||||
{
|
||||
return $callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace Plugi {
|
||||
@@ -177,6 +212,7 @@ namespace {
|
||||
|
||||
use FormExtensionTests\DefinitionsRepository as TestDefinitionsRepository;
|
||||
use FormExtensionTests\FinishersRepository as TestFinishersRepository;
|
||||
use FormExtensionTests\RateLimitDatabase as TestRateLimitDatabase;
|
||||
use Plugi\Extensions\Form\SubmissionHandler;
|
||||
|
||||
if (!function_exists('phpb_instance')) {
|
||||
@@ -193,11 +229,41 @@ namespace {
|
||||
}
|
||||
}
|
||||
|
||||
function makeHandler($form): SubmissionHandler
|
||||
function makeHandler($form, $rateLimiter = null): SubmissionHandler
|
||||
{
|
||||
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository());
|
||||
return new SubmissionHandler(new TestDefinitionsRepository($form), new TestFinishersRepository(), $rateLimiter ?? new AllowSubmissionRateLimiter());
|
||||
}
|
||||
|
||||
class AllowSubmissionRateLimiter
|
||||
{
|
||||
public function consume(int $formId, string $clientIp): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class RejectSubmissionRateLimiter
|
||||
{
|
||||
public function consume(int $formId, string $clientIp): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$rateLimitDatabase = new TestRateLimitDatabase();
|
||||
$rateLimiter = new \Plugi\Extensions\Form\SubmissionRateLimiter($rateLimitDatabase);
|
||||
for ($submission = 0; $submission < 5; $submission++) {
|
||||
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions within the limit must be allowed.');
|
||||
}
|
||||
assertSameValue(false, $rateLimiter->consume(7, '203.0.113.1'), 'Submissions over the limit must be rejected.');
|
||||
assertSameValue(true, $rateLimiter->consume(8, '203.0.113.1'), 'Rate limits must be scoped to each form.');
|
||||
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.2'), 'Rate limits must be scoped to each client IP.');
|
||||
$rateLimitKey = '7:' . hash('sha256', '203.0.113.1');
|
||||
$rateLimitDatabase->rows[$rateLimitKey]['startedAt'] = time() - 601;
|
||||
$rateLimitDatabase->rows[$rateLimitKey]['submissions'] = 5;
|
||||
assertSameValue(true, $rateLimiter->consume(7, '203.0.113.1'), 'Expired rate limit windows must reset.');
|
||||
assertSameValue(1, $rateLimitDatabase->rows[$rateLimitKey]['submissions'], 'The reset window must begin at one submission.');
|
||||
|
||||
function validForm(array $finishers = []): array
|
||||
{
|
||||
return [
|
||||
@@ -223,6 +289,31 @@ namespace {
|
||||
assertSameValue(true, $result['body']['success'], 'Successful actions must report success');
|
||||
assertSameValue(['first', 'second'], $GLOBALS['formFinisherCalls'], 'Actions must run in configured order');
|
||||
|
||||
$GLOBALS['formFinisherCalls'] = [];
|
||||
$result = makeHandler($form, new RejectSubmissionRateLimiter())->handle(7, $validPayload);
|
||||
assertSameValue(429, $result['status'], 'Rate-limited submissions must be rejected');
|
||||
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Rate-limited submissions must not run actions');
|
||||
|
||||
$GLOBALS['formFinisherCalls'] = [];
|
||||
$result = makeHandler($form)->handle(7, str_repeat('x', 65537));
|
||||
assertSameValue(413, $result['status'], 'Oversized request bodies must be rejected');
|
||||
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized requests must not run actions');
|
||||
|
||||
$GLOBALS['formFinisherCalls'] = [];
|
||||
$oversizedField = json_encode(['fields' => ['name' => str_repeat('A', 16385)]]);
|
||||
$result = makeHandler($form)->handle(7, $oversizedField);
|
||||
assertSameValue(422, $result['status'], 'Oversized field values must be rejected');
|
||||
assertSameValue([], $GLOBALS['formFinisherCalls'], 'Oversized fields must not run actions');
|
||||
|
||||
$tooManyFields = array_fill_keys(array_map('strval', range(1, 101)), 'value');
|
||||
$result = makeHandler($form)->handle(7, json_encode(['fields' => $tooManyFields]));
|
||||
assertSameValue(422, $result['status'], 'Submissions with too many fields must be rejected');
|
||||
|
||||
$submitRoute = file_get_contents(dirname(__DIR__) . '/routes/submit.php');
|
||||
if (strpos($submitRoute, 'MAX_REQUEST_BYTES + 1') === false) {
|
||||
throw new \RuntimeException('The submission route must read no more than the configured body limit plus one byte.');
|
||||
}
|
||||
|
||||
$GLOBALS['formFinisherCalls'] = [];
|
||||
$GLOBALS['formFinisherResults'] = ['first' => false, 'second' => true];
|
||||
$result = makeHandler($form)->handle(7, $validPayload);
|
||||
|
||||
Reference in New Issue
Block a user