ldc-cocotte/app/Http/Middleware/HtmlSanitizer.php
Jérémy Munsch bf1c0d7d4e
test(HtmlSanitizer): add tests for HTML sanitization behavior
- Ensure password fields are preserved during sanitization.
- Validate rich HTML fields are purified correctly.
- Confirm HTTP scheme is stripped from oembed URLs after sanitization.
2026-11-15 16:45:05 +01:00

141 lines
3.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TransformsRequest;
use Illuminate\Support\Str;
use Mews\Purifier\Purifier;
/**
* Portable request sanitization middleware built on Laravel's `TransformsRequest`.
*
* Cleans query, form, and JSON bags while leaving uploaded files untouched:
* strips HTML tags by default, applies HTMLPurifier to listed rich-HTML fields,
* and skips fields matching `$except`.
*/
class HtmlSanitizer extends TransformsRequest
{
/**
* The attributes that should not be sanitized.
*
* @var list<string>
*/
protected array $except = [
'current_password',
'password',
'password_confirmation',
'password_old',
];
/** @var list<string> */
private array $richFields = [];
public function __construct(
private readonly Purifier $purifierService
) {
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request):(\Symfony\Component\HttpFoundation\Response) $next
* @param string ...$params List of input names that should be sanitized with rich sanitization (allowing some HTML)
*/
#[\Override]
public function handle($request, \Closure $next, string ...$params): mixed
{
$this->richFields = array_values($params);
try {
return parent::handle($request, $next);
} finally {
$this->richFields = [];
}
}
#[\Override]
protected function cleanValue($key, $value): mixed
{
if ($this->matchesPattern((string) $key, $this->except)) {
return $value;
}
return parent::cleanValue($key, $value);
}
#[\Override]
protected function transform($key, $value): mixed
{
if (! is_string($value)) {
return $value;
}
if ($this->matchesPattern((string) $key, $this->richFields)) {
return $this->sanitizeRichInput($value);
}
return strip_tags($value);
}
/**
* @param list<string> $patterns
*/
private function matchesPattern(string $key, array $patterns): bool
{
if ($patterns === []) {
return false;
}
$root = Str::before($key, '.');
$leaf = Str::afterLast($key, '.');
return Str::is($patterns, $key)
|| Str::is($patterns, $root)
|| Str::is($patterns, $leaf);
}
private function sanitizeRichInput(string $input): string
{
$decoded = \json_decode($input, true);
if ($decoded && is_array($decoded)) {
\array_walk_recursive($decoded, function (mixed &$item): void {
if (\is_string($item)) {
$item = $this->purifyString($item);
}
});
return json_encode($decoded, \JSON_THROW_ON_ERROR)
?: throw new \UnexpectedValueException('Failed to encode JSON after sanitization.');
}
return $this->purifyString($input);
}
private function purifyString(string $input): string
{
$cleaned = $this->purifierService->clean($input);
if (! is_string($cleaned)) {
throw new \UnexpectedValueException('Purifier should return a string when input is a string.');
}
return $this->stripCkEditorSchemesOnMediaInputs($cleaned);
}
/**
* Strip scheme (http) on oembed urls
* Only embed allowed are for MP4 self hosted videos right now
*
* https is force by ckeditor MediaElements which natively supports
* only cloud hosted medias (youtube, spotify etc..)
*/
private function stripCkEditorSchemesOnMediaInputs(string $input): string
{
return Str::of($input)
->replaceMatches('/(?<=<oembed url=")(http:\/\/)(?=.*?">)/m', '')
->toString();
}
}