platform/src/Core/Framework/Routing/CoreSubscriber.php line 31

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