vendor/shopware/core/Framework/Routing/CoreSubscriber.php line 45

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Framework\Routing;
  3. use Shopware\Core\Framework\Log\Package;
  4. use Shopware\Core\PlatformRequest;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. /**
  10.  * @internal
  11.  */
  12. #[Package('core')]
  13. class CoreSubscriber implements EventSubscriberInterface
  14. {
  15.     /**
  16.      * @internal
  17.      *
  18.      * @param array<string> $cspTemplates
  19.      */
  20.     public function __construct(private array $cspTemplates)
  21.     {
  22.         $this->cspTemplates $cspTemplates;
  23.     }
  24.     /**
  25.      * @return array<string, string|array{0: string, 1: int}|list<array{0: string, 1?: int}>>
  26.      */
  27.     public static function getSubscribedEvents(): array
  28.     {
  29.         return [
  30.             KernelEvents::REQUEST => 'initializeCspNonce',
  31.             KernelEvents::RESPONSE => 'setSecurityHeaders',
  32.         ];
  33.     }
  34.     public function initializeCspNonce(RequestEvent $event): void
  35.     {
  36.         $nonce base64_encode(random_bytes(8));
  37.         $event->getRequest()->attributes->set(PlatformRequest::ATTRIBUTE_CSP_NONCE$nonce);
  38.     }
  39.     public function setSecurityHeaders(ResponseEvent $event): void
  40.     {
  41.         if (!$event->getResponse()->isSuccessful()) {
  42.             return;
  43.         }
  44.         $response $event->getResponse();
  45.         if ($event->getRequest()->isSecure()) {
  46.             $response->headers->set('Strict-Transport-Security''max-age=31536000; includeSubDomains');
  47.         }
  48.         $response->headers->set('X-Frame-Options''deny');
  49.         $response->headers->set('X-Content-Type-Options''nosniff');
  50.         $response->headers->set('Referrer-Policy''strict-origin-when-cross-origin');
  51.         $cspTemplate $this->cspTemplates['default'] ?? '';
  52.         $scopes $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, []);
  53.         foreach ($scopes as $scope) {
  54.             $cspTemplate $this->cspTemplates[$scope] ?? $cspTemplate;
  55.         }
  56.         $cspTemplate trim($cspTemplate);
  57.         if ($cspTemplate !== '' && !$response->headers->has('Content-Security-Policy')) {
  58.             $nonce $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_CSP_NONCE);
  59.             if (\is_string($nonce)) {
  60.                 $csp str_replace('%nonce%'$nonce$cspTemplate);
  61.                 $csp str_replace(["\n""\r"], ' '$csp);
  62.                 $response->headers->set('Content-Security-Policy'$csp);
  63.             }
  64.         }
  65.     }
  66. }