diff --git a/.travis.yml b/.travis.yml index 63d5320..905f786 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,6 +34,16 @@ matrix: - php: 7 env: - DEPS=latest + - php: 7.1 + env: + - DEPS=lowest + - php: 7.1 + env: + - DEPS=locked + - CS_CHECK=true + - php: 7.1 + env: + - DEPS=latest - php: hhvm env: - DEPS=lowest diff --git a/CHANGELOG.md b/CHANGELOG.md index 28f128e..2dc289d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ - ZfrCors now properly disallows `Access-Control-Allow-Origin: *` when the credentials flag is true. [#35] +- The `CorsRequestListener` now no longer raises an exception when triggered + during `EVENT_FINISH` if the `Origin` header is invalid, and instead just + returns early. That condition is already found during pre-flight, which allows + ignoring it when returning the response. [#47] # 1.4.0 diff --git a/src/ZfrCors/Mvc/CorsRequestListener.php b/src/ZfrCors/Mvc/CorsRequestListener.php index 6c29baa..0834b86 100644 --- a/src/ZfrCors/Mvc/CorsRequestListener.php +++ b/src/ZfrCors/Mvc/CorsRequestListener.php @@ -128,10 +128,17 @@ public function onCorsRequest(MvcEvent $event) return; } + try { + $isCorsRequest = $this->corsService->isCorsRequest($request); + } catch (InvalidOriginException $exception) { + // InvalidOriginException should already be handled by `CorsRequestListener::onCorsPreflight` + return; + } + // Also ensure that the vary header is set when no origin is set // to prevent reverse proxy caching a wrong request; causing all of the following // requests to fail due to missing CORS headers. - if (! $this->corsService->isCorsRequest($request)) { + if (! $isCorsRequest) { if (! $request->getHeader('Origin')) { $this->corsService->ensureVaryHeader($response); } diff --git a/tests/ZfrCorsTest/Mvc/CorsRequestListenerTest.php b/tests/ZfrCorsTest/Mvc/CorsRequestListenerTest.php index d79ef8c..33976d1 100644 --- a/tests/ZfrCorsTest/Mvc/CorsRequestListenerTest.php +++ b/tests/ZfrCorsTest/Mvc/CorsRequestListenerTest.php @@ -156,4 +156,25 @@ public function testImmediatelyReturnBadRequestResponseForInvalidOriginHeaderVal $this->assertEquals(400, $response->getStatusCode()); $this->assertEquals('', $response->getContent()); } + + /** + * Application always triggers `MvcEvent::EVENT_FINISH` and since the `CorsRequestListener` is listening on it, we + * should handle the exception aswell. + * + * + * @return void + */ + public function testOnCorsRequestCanHandleInvalidOriginHeaderValue() + { + $mvcEvent = new MvcEvent(); + $request = new HttpRequest(); + $response = new HttpResponse(); + + $request->getHeaders()->addHeaderLine('Origin', 'file:'); + + $mvcEvent->setRequest($request) + ->setResponse($response); + + $this->corsListener->onCorsRequest($mvcEvent); + } }