Skip to content

Commit 4f5ac21

Browse files
committed
Opt-in CORS GET request cache
1 parent 122edbb commit 4f5ac21

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

dropins/advanced-cache.php

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ class wondercache {
5757
public $cancel = false; // Change this to cancel the output buffer. Use wondercache_cancel();
5858

5959
public $noskip_cookies = array( 'wordpress_test_cookie' ); // Names of cookies - if they exist and the cache would normally be bypassed, don't bypass it
60+
public $cacheable_origin_hostnames = array(); // A whitelist of HTTP origin `<host>:<port>` (or just `<host>`) names that are allowed as cache variations.
6061

6162
public $query = '';
6263
public $genlock = false;
@@ -70,6 +71,23 @@ function __construct( $settings ) {
7071
}
7172
}
7273

74+
function is_cacheable_origin( $origin ) {
75+
$parsed_origin = parse_url( $origin );
76+
77+
if ( false === $parsed_origin ) {
78+
return false;
79+
}
80+
81+
$origin_host = ! empty( $parsed_origin['host'] ) ? strtolower( $parsed_origin['host'] ) : null;
82+
$origin_scheme = ! empty( $parsed_origin['scheme'] ) ? strtolower( $parsed_origin['scheme'] ) : null;
83+
$origin_port = ! empty( $parsed_origin['port'] ) ? $parsed_origin['port'] : null;
84+
85+
return $origin
86+
&& $origin_host
87+
&& ( 'http' === $origin_scheme || 'https' === $origin_scheme )
88+
&& ( null === $origin_port || 80 === $origin_port || 443 === $origin_port )
89+
&& in_array( $origin_host, $this->cacheable_origin_hostnames, true );
90+
}
7391

7492
function status_header( $status_header, $status_code ) {
7593
$this->status_header = $status_header;
@@ -342,6 +360,17 @@ function add_debug_html_to_output( $debug_html ) {
342360
return;
343361
}
344362

363+
// Never wondercache a response for a request with an Origin request header.
364+
// *Unless* that Origin header is in the configured whitelist of allowed origins with restricted schemes and ports.
365+
if ( isset( $_SERVER['HTTP_ORIGIN'] ) ) {
366+
if ( ! $wondercache->is_cacheable_origin( $_SERVER['HTTP_ORIGIN'] ) ) {
367+
return;
368+
}
369+
370+
$wondercache->origin = $_SERVER['HTTP_ORIGIN'];
371+
}
372+
373+
345374
// Never cache when cookies indicate a cache-exempt visitor.
346375
if ( is_array( $_COOKIE ) && ! empty( $_COOKIE ) ) {
347376
foreach ( array_keys( $_COOKIE ) as $wondercache->cookie ) {
@@ -415,7 +444,7 @@ function add_debug_html_to_output( $debug_html ) {
415444
$is_cached && // We have cache
416445
! $wondercache->genlock && // We have not obtained cache regeneration lock
417446
(
418-
! $has_expired || // Batcached page that hasn't expired
447+
! $has_expired || // Wondercache page that hasn't expired
419448
( $wondercache->do && $wondercache->use_stale ) // Regenerating it in another request and can use stale cache
420449
)
421450
) {

0 commit comments

Comments
 (0)