Skip to content

Commit

Permalink
Restore CORS support to CORS proxy (#2023)
Browse files Browse the repository at this point in the history
## Motivation for the change, related issues

We want to move the CORS proxy to a separate host from
playground.wordpress.net. In order to continue using the proxy from
playground.wordpress.net, the CORS proxy needs to support cross-origin
requests to itself.

## Implementation details

This PR updates the CORS proxy to again respond with CORS-related
headers for supported origins. Currently, supported origins are
"https://playground.wordpress.net" and local origins based on
"127.0.0.1" and "localhost".

## Testing Instructions (or ideally a Blueprint)

- Once #2022 is merged, deploy this branch to the dedicated CORS proxy
host.
- Create a Blueprint that uses the dedicated CORS proxy host.
- Confirm the Blueprint works with playground.wordpress.net.
- Confirm the Blueprint works with the local dev server.
  • Loading branch information
brandonpayton authored Dec 4, 2024
1 parent b26717b commit f77ea88
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
27 changes: 27 additions & 0 deletions packages/playground/php-cors-proxy/cors-proxy-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -354,3 +354,30 @@ function rewrite_relative_redirect(
}
return $proxy_absolute_url . $redirect_location;
}

/**
* Answers whether CORS is allowed for the specified origin.
*/
function should_respond_with_cors_headers($host, $origin) {
if (empty($origin)) {
return false;
}

$is_request_from_playground_web_app = $origin === 'https://playground.wordpress.net';
$not_hosted_with_playground_web_app = $host !== 'playground.wordpress.net';
if (
$is_request_from_playground_web_app &&
$not_hosted_with_playground_web_app
) {
return true;
}

$origin_host = parse_url($origin, PHP_URL_HOST);
$is_local_origin = in_array(
$origin_host,
array('localhost', '127.0.0.1'),
true
);

return $is_local_origin;
}
10 changes: 10 additions & 0 deletions packages/playground/php-cors-proxy/cors-proxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@
require_once $config_file;
}

$server_host = $_SERVER['HTTP_HOST'] ?? '';
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (should_respond_with_cors_headers($server_host, $origin)) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
}

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header("Allow: GET, POST, OPTIONS");
exit;
Expand Down

0 comments on commit f77ea88

Please sign in to comment.