Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: set headers for CORS #9437

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 25 additions & 13 deletions system/Filters/Cors.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,32 @@ public function before(RequestInterface $request, $arguments = null)

$this->createCorsService($arguments);

if (! $this->cors->isPreflightRequest($request)) {
return null;
}

/** @var ResponseInterface $response */
$response = service('response');

$response = $this->cors->handlePreflightRequest($request, $response);
if ($this->cors->isPreflightRequest($request)) {
$response = $this->cors->handlePreflightRequest($request, $response);

// Always adds `Vary: Access-Control-Request-Method` header for cacheability.
// If there is an intermediate cache server such as a CDN, if a plain
// OPTIONS request is sent, it may be cached. But valid preflight requests
// have this header, so it will be cached separately.
$response->appendHeader('Vary', 'Access-Control-Request-Method');
// Always adds `Vary: Access-Control-Request-Method` header for cacheability.
// If there is an intermediate cache server such as a CDN, if a plain
// OPTIONS request is sent, it may be cached. But valid preflight requests
// have this header, so it will be cached separately.
$response->appendHeader('Vary', 'Access-Control-Request-Method');

return $response;
}

return $response;
if ($request->is('OPTIONS')) {
// Always adds `Vary: Access-Control-Request-Method` header for cacheability.
// If there is an intermediate cache server such as a CDN, if a plain
// OPTIONS request is sent, it may be cached. But valid preflight requests
// have this header, so it will be cached separately.
$response->appendHeader('Vary', 'Access-Control-Request-Method');
}

$this->cors->addResponseHeaders($request, $response);

return null;
}

/**
Expand All @@ -87,8 +97,6 @@ private function createCorsService(?array $arguments): void

/**
* @param list<string>|null $arguments
*
* @return ResponseInterface|null
*/
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
Expand All @@ -98,6 +106,10 @@ public function after(RequestInterface $request, ResponseInterface $response, $a

$this->createCorsService($arguments);

if ($this->cors->hasResponseHeaders($request, $response)) {
return null;
}

// Always adds `Vary: Access-Control-Request-Method` header for cacheability.
// If there is an intermediate cache server such as a CDN, if a plain
// OPTIONS request is sent, it may be cached. But valid preflight requests
Expand Down
20 changes: 20 additions & 0 deletions system/HTTP/Cors.php
Original file line number Diff line number Diff line change
Expand Up @@ -227,4 +227,24 @@ private function setExposeHeaders(ResponseInterface $response): void
);
}
}

/**
* Check if response headers were set
*/
public function hasResponseHeaders(RequestInterface $request, ResponseInterface $response): bool
{
if (! $response->hasHeader('Access-Control-Allow-Origin')) {
return false;
}

if ($this->config['supportsCredentials']
&& ! $response->hasHeader('Access-Control-Allow-Credentials')) {
return false;
}

return ! ($this->config['exposedHeaders'] !== [] && (! $response->hasHeader('Access-Control-Expose-Headers') || ! str_contains(
$response->getHeaderLine('Access-Control-Expose-Headers'),
implode(', ', $this->config['exposedHeaders']),
)));
}
}
45 changes: 45 additions & 0 deletions tests/system/Filters/CorsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use CodeIgniter\Exceptions\ConfigException;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\SiteURI;
Expand Down Expand Up @@ -154,6 +155,25 @@ private function handle(RequestInterface $request): ResponseInterface
return $response;
}

private function handleRedirect(RequestInterface $request): ResponseInterface
{
$response = $this->cors->before($request);
if ($response instanceof ResponseInterface) {
$this->response = $response;

return $response;
}

$response = service('redirectresponse');

$response = $this->cors->after($request, $response);
$response ??= service('redirectresponse');

$this->response = $response;

return $response;
}

public function testItDoesModifyOnARequestWithSameOrigin(): void
{
$this->cors = $this->createCors(['allowedOrigins' => ['*']]);
Expand Down Expand Up @@ -461,4 +481,29 @@ public function testItAddsVaryAccessControlRequestMethodHeaderEvenIfItIsNormalOp
// Always adds `Vary: Access-Control-Request-Method` header.
$this->assertHeader('Vary', 'Access-Control-Request-Method');
}

public function testItReturnsAllowOriginHeaderOnValidActualRequestWithRedirect(): void
{
$this->cors = $this->createCors();
$request = $this->createValidActualRequest();

$response = $this->handleRedirect($request);

$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertTrue($response->hasHeader('Access-Control-Allow-Origin'));
$this->assertHeader('Access-Control-Allow-Origin', 'http://localhost');
}

public function testItReturnsAllowOriginHeaderOnAllowAllOriginRequestWithRedirect(): void
{
$this->cors = $this->createCors(['allowedOrigins' => ['*']]);
$request = $this->createRequest();
$request->setHeader('Origin', 'http://localhost');

$response = $this->handleRedirect($request);

$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertTrue($response->hasHeader('Access-Control-Allow-Origin'));
$this->assertHeader('Access-Control-Allow-Origin', '*');
}
}
37 changes: 37 additions & 0 deletions tests/system/HTTP/CorsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -521,4 +521,41 @@ public function testAddResponseHeadersMultipleAllowedOriginsNotAllowed(): void
$response->hasHeader('Access-Control-Allow-Methods'),
);
}

public function testHasResponseHeadersFalse(): void
{
$config = $this->getDefaultConfig();
$config['allowedOrigins'] = ['http://localhost:8080'];
$config['allowedMethods'] = ['GET', 'POST', 'PUT'];
$cors = $this->createCors($config);

$request = $this->createRequest()
->withMethod('GET')
->setHeader('Origin', 'http://localhost:8080');

$response = service('redirectresponse', null, false);

$this->assertFalse(
$cors->hasResponseHeaders($request, $response),
);
}

public function testHasResponseHeadersTrue(): void
{
$config = $this->getDefaultConfig();
$config['allowedOrigins'] = ['http://localhost:8080'];
$config['allowedMethods'] = ['GET', 'POST'];
$cors = $this->createCors($config);

$request = $this->createRequest()
->withMethod('GET')
->setHeader('Origin', 'http://localhost:8080');

$response = service('redirectresponse', null, false);
$response = $cors->addResponseHeaders($request, $response);

$this->assertTrue(
$cors->hasResponseHeaders($request, $response),
);
}
}
1 change: 1 addition & 0 deletions user_guide_src/source/changelogs/v4.6.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Bugs Fixed
**********

- **CURLRequest:** Fixed an issue where multiple header sections appeared in the CURL response body during multiple redirects from the target server.
- **Cors:** Fixed a bug in the Cors filter that caused the appropriate headers to not be added when another filter returned a response object in the ``before`` filter.

See the repo's
`CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
Expand Down
Loading