From 992083095bb5ae67b85a35ac13c1f7a24125197b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Pineau?= Date: Thu, 19 Oct 2023 15:23:47 +0200 Subject: [PATCH] [HtmlSanitizer] Add support for sanitizing unlimited length of HTML document --- CHANGELOG.md | 5 +++++ HtmlSanitizer.php | 2 +- HtmlSanitizerConfig.php | 8 ++++++++ Tests/HtmlSanitizerAllTest.php | 11 +++++++++++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 003f90d..c5d32f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +6.4 +--- + + * Add support for sanitizing unlimited length of HTML document + 6.1 --- diff --git a/HtmlSanitizer.php b/HtmlSanitizer.php index fb66892..ccc6f69 100644 --- a/HtmlSanitizer.php +++ b/HtmlSanitizer.php @@ -60,7 +60,7 @@ 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->config->getMaxInputLength()) { + if (-1 !== $this->config->getMaxInputLength() && \strlen($input) > $this->config->getMaxInputLength()) { $input = substr($input, 0, $this->config->getMaxInputLength()); } diff --git a/HtmlSanitizerConfig.php b/HtmlSanitizerConfig.php index aba3067..f46ffff 100644 --- a/HtmlSanitizerConfig.php +++ b/HtmlSanitizerConfig.php @@ -405,8 +405,16 @@ public function withoutAttributeSanitizer(AttributeSanitizerInterface $sanitizer return $clone; } + /** + * @param int $maxInputLength The maximum length of the input string in bytes + * -1 means no limit + */ public function withMaxInputLength(int $maxInputLength): static { + if ($maxInputLength < -1) { + throw new \InvalidArgumentException(sprintf('The maximum input length must be greater than -1, "%d" given.', $maxInputLength)); + } + $clone = clone $this; $clone->maxInputLength = $maxInputLength; diff --git a/Tests/HtmlSanitizerAllTest.php b/Tests/HtmlSanitizerAllTest.php index bdb47d7..dfc44e8 100644 --- a/Tests/HtmlSanitizerAllTest.php +++ b/Tests/HtmlSanitizerAllTest.php @@ -561,4 +561,15 @@ public static function provideSanitizeBody() yield $case[0] => $case; } } + + public function testUnlimitedLength() + { + $sanitizer = new HtmlSanitizer((new HtmlSanitizerConfig())->withMaxInputLength(-1)); + + $input = str_repeat('a', 10_000_000); + + $sanitized = $sanitizer->sanitize($input); + + $this->assertSame(\strlen($input), \strlen($sanitized)); + } }