From e1cfb2a89da8f5fe4bb5b0515b9f92c3673ddb8a Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 15 Apr 2022 17:00:35 +0200 Subject: [PATCH] [HtmlSanitizer] Add HtmlSanitizerConfig::withMaxInputLength() --- HtmlSanitizer.php | 8 +++----- HtmlSanitizerConfig.php | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/HtmlSanitizer.php b/HtmlSanitizer.php index 78687d6..2f49472 100644 --- a/HtmlSanitizer.php +++ b/HtmlSanitizer.php @@ -25,7 +25,6 @@ final class HtmlSanitizer implements HtmlSanitizerInterface { private HtmlSanitizerConfig $config; - private int $maxInputLength; private ParserInterface $parser; /** @@ -33,10 +32,9 @@ final class HtmlSanitizer implements HtmlSanitizerInterface */ private array $domVisitors = []; - public function __construct(HtmlSanitizerConfig $config, int $maxInputLength = 20000, ParserInterface $parser = null) + public function __construct(HtmlSanitizerConfig $config, ParserInterface $parser = null) { $this->config = $config; - $this->maxInputLength = $maxInputLength; $this->parser = $parser ?? new MastermindsParser(); } @@ -64,8 +62,8 @@ private function sanitizeWithContext(string $context, string $input): string $this->domVisitors[$context] ??= $this->createDomVisitorForContext($context); // Prevent DOS attack induced by extremely long HTML strings - if (\strlen($input) > $this->maxInputLength) { - $input = substr($input, 0, $this->maxInputLength); + if (\strlen($input) > $this->config->getMaxInputLength()) { + $input = substr($input, 0, $this->config->getMaxInputLength()); } // Only operate on valid UTF-8 strings. This is necessary to prevent cross diff --git a/HtmlSanitizerConfig.php b/HtmlSanitizerConfig.php index 81a2812..34576ca 100644 --- a/HtmlSanitizerConfig.php +++ b/HtmlSanitizerConfig.php @@ -92,6 +92,8 @@ class HtmlSanitizerConfig */ private array $attributeSanitizers; + private int $maxInputLength = 20_000; + public function __construct() { $this->attributeSanitizers = [ @@ -405,6 +407,19 @@ public function withoutAttributeSanitizer(AttributeSanitizerInterface $sanitizer return $clone; } + public function withMaxInputLength(int $maxInputLength): static + { + $clone = clone $this; + $clone->maxInputLength = $maxInputLength; + + return $clone; + } + + public function getMaxInputLength(): int + { + return $this->maxInputLength; + } + /** * @return array> */