Issue
Enabling CORS in Drupal 8 (See D.O: Opt-in CORS Support) within Acquia Cloud may sometimes serve a request that lacks the proper headers, because of a bug in core triggered by the asm89/stack-cors component, which is not sending a Vary: Origin header on all responses.
This can result in some requests that include the Origin header receiving Varnish-cached responses that are missing some headers needed by browsers' security policies.
Some example headers are:
- Access-Control-Allow-Origin
- Access-Control-Max-Age
- Access-Control-Request-Method
- Access-Control-Expose-Headers
The above missing headers could then cause browsers to block that content. Some example messages (viewable in Javascript console) may look like these:
Access to [resource] at 'https://example.com/path/to/resource' from origin
'https://exampleorigin.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
http://example.com/path/to/resource' has been blocked by CORS policy: Response to preflight request doesn't pass.
Affected Applications/Limitations
This affects any Drupal 8 responses which are cacheable. Limited to Drupal 8 sites that have CORS support enabled (see below).
Resolution
First of all, ensure you have enabled the proper CORS support in Drupal; for this you can view the many examples at Drupal.org: Opt-in CORS support.
Consult the known Drupal.org issue at [#3001809] CORS breaks with cache proxies and same origin usage (Drupal 8) which is in progress at the time of writing, and includes a patch. For Drupal 9, there is another related issue [#3128982] Enabling CORS breaks cacheability which at the time of writing is also in progress.
An alternative to implementing the above patch is to use the HTTP Cache Control module and add the vary header on Origin (which works when the Origin header is passed as per a CORS request).