Skip to content

Commit

Permalink
[HtmlSanitizer] Add HtmlSanitizerConfig::withMaxInputLength()
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-grekas committed Apr 15, 2022
1 parent 886c35d commit e1cfb2a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
8 changes: 3 additions & 5 deletions HtmlSanitizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,16 @@
final class HtmlSanitizer implements HtmlSanitizerInterface
{
private HtmlSanitizerConfig $config;
private int $maxInputLength;
private ParserInterface $parser;

/**
* @var array<string, DomVisitor>
*/
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();
}

Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions HtmlSanitizerConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ class HtmlSanitizerConfig
*/
private array $attributeSanitizers;

private int $maxInputLength = 20_000;

public function __construct()
{
$this->attributeSanitizers = [
Expand Down Expand Up @@ -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<string, array<string, true>>
*/
Expand Down

0 comments on commit e1cfb2a

Please sign in to comment.