View source
<?php
namespace Drupal\csp\EventSubscriber;
use Drupal\Core\Asset\LibraryDependencyResolverInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Render\AttachmentsInterface;
use Drupal\csp\Csp;
use Drupal\csp\CspEvents;
use Drupal\csp\Event\PolicyAlterEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CoreCspSubscriber implements EventSubscriberInterface {
private $libraryDependencyResolver;
private $moduleHandler;
public static function getSubscribedEvents() {
$events[CspEvents::POLICY_ALTER] = [
'onCspPolicyAlter',
];
return $events;
}
public function __construct(LibraryDependencyResolverInterface $libraryDependencyResolver, ModuleHandlerInterface $moduleHandler) {
$this->libraryDependencyResolver = $libraryDependencyResolver;
$this->moduleHandler = $moduleHandler;
}
public function onCspPolicyAlter(PolicyAlterEvent $alterEvent) {
$policy = $alterEvent
->getPolicy();
$response = $alterEvent
->getResponse();
if ($response instanceof AttachmentsInterface) {
$attachments = $response
->getAttachments();
$libraries = isset($attachments['library']) ? $this->libraryDependencyResolver
->getLibrariesWithDependencies($attachments['library']) : [];
if (in_array('core/drupal.ajax', $libraries) && !$this->moduleHandler
->moduleExists('csp_extras')) {
$policy
->fallbackAwareAppendIfEnabled('script-src-attr', []);
$policy
->fallbackAwareAppendIfEnabled('script-src', [
Csp::POLICY_UNSAFE_INLINE,
]);
$policy
->fallbackAwareAppendIfEnabled('script-src-elem', [
Csp::POLICY_UNSAFE_INLINE,
]);
$policy
->fallbackAwareAppendIfEnabled('style-src-attr', []);
$policy
->fallbackAwareAppendIfEnabled('style-src', [
Csp::POLICY_UNSAFE_INLINE,
]);
$policy
->fallbackAwareAppendIfEnabled('style-src-elem', [
Csp::POLICY_UNSAFE_INLINE,
]);
}
$quickedit = in_array('quickedit/quickedit', $libraries) && $this->moduleHandler
->moduleExists('ckeditor');
if (in_array('core/ckeditor', $libraries) || $quickedit) {
$policy
->fallbackAwareAppendIfEnabled('script-src-elem', []);
$policy
->fallbackAwareAppendIfEnabled('script-src', [
Csp::POLICY_UNSAFE_INLINE,
]);
$policy
->fallbackAwareAppendIfEnabled('script-src-attr', [
Csp::POLICY_UNSAFE_INLINE,
]);
}
if (in_array('ckeditor/drupal.ckeditor', $libraries) || $quickedit) {
$policy
->fallbackAwareAppendIfEnabled('style-src', [
Csp::POLICY_UNSAFE_INLINE,
]);
$policy
->fallbackAwareAppendIfEnabled('style-src-attr', [
Csp::POLICY_UNSAFE_INLINE,
]);
$policy
->fallbackAwareAppendIfEnabled('style-src-elem', [
Csp::POLICY_UNSAFE_INLINE,
]);
}
$umamiFontLibraries = [
'umami/webfonts',
'umami/webfonts-open-sans',
'umami/webfonts-scope-one',
];
if (!empty(array_intersect($libraries, $umamiFontLibraries))) {
$policy
->fallbackAwareAppendIfEnabled('font-src', [
'https://fonts.gstatic.com',
]);
}
}
}
}