diff --git a/helfi_proxy.services.yml b/helfi_proxy.services.yml index 3aece98..afb96a4 100644 --- a/helfi_proxy.services.yml +++ b/helfi_proxy.services.yml @@ -3,6 +3,9 @@ parameters: - www.hel.fi - www-test.hel.fi - helfi-proxy.docker.so + helfi_proxy.valid_origin_domains: + - hel.fi + - docker.so services: helfi_proxy.http_middleware: class: Drupal\helfi_proxy\HttpMiddleware\AssetHttpMiddleware @@ -52,6 +55,13 @@ services: tags: - { name: event_subscriber } + helfi_proxy.cors_subscriber: + class: Drupal\helfi_proxy\EventSubscriber\CorsResponseSubscriber + arguments: + - '%helfi_proxy.valid_origin_domains%' + tags: + - { name: event_subscriber } + helfi_proxy.asset.css.optimizer: public: false class: Drupal\helfi_proxy\Asset\CssOptimizer diff --git a/src/EventSubscriber/CorsResponseSubscriber.php b/src/EventSubscriber/CorsResponseSubscriber.php new file mode 100644 index 0000000..c6ddcac --- /dev/null +++ b/src/EventSubscriber/CorsResponseSubscriber.php @@ -0,0 +1,68 @@ +getRequest()->headers->get('Origin'); + + if (!$requestDomain) { + return; + } + $validHost = FALSE; + + foreach ($this->validOriginDomains as $domain) { + if ($requestDomain === $domain) { + $validHost = TRUE; + } + + // Allow subdomains as well. + if (str_ends_with($requestDomain, '.' . $domain)) { + $validHost = TRUE; + } + } + if (!$validHost) { + return; + } + + $event->getResponse()->headers->add([ + 'Access-Control-Allow-Origin' => $requestDomain, + ]); + } + + /** + * {@inheritdoc} + */ + public static function getSubscribedEvents() : array { + $events[KernelEvents::RESPONSE][] = ['onResponse', -100]; + return $events; + } + +} diff --git a/tests/src/Kernel/CorsResponseSubscriberTest.php b/tests/src/Kernel/CorsResponseSubscriberTest.php new file mode 100644 index 0000000..02de20a --- /dev/null +++ b/tests/src/Kernel/CorsResponseSubscriberTest.php @@ -0,0 +1,59 @@ + 'localhost:8888', + ]); + $request->headers->set('Origin', $domain); + $http_kernel = $this->container->get('http_kernel'); + /** @var \Symfony\Component\HttpFoundation\Response $response */ + $response = $http_kernel->handle($request); + $this->assertEquals($expected, $response->headers->has('Access-Control-Allow-Origin')); + } + + /** + * Data provider for testCors(). + * + * @return array[] + * The data. + */ + public function corsTestData() : array { + return [ + ['www.hel.fi', TRUE], + ['hel.fi', TRUE], + ['docker.so', TRUE], + ['helfi-kymp.docker.so', TRUE], + ['testdocker.so', FALSE], + [NULL, FALSE], + ]; + } + +}