# CORS’ing the complexity: idempotent and caching meets Vary: Origin for CORS

- Link: https://www.agilicus.com/cors-idempotent-vary-origin-header/
- Published: 2020-06-12T01:11:07+00:00
- Author: Don Bowman

So I spent a bit of time debugging something this am, and I thought I would share.
Its super detailed, so feel free to gloss over.

There is a class of browser-security issues addressed by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).
They are meant to prevent inadvertent (or malicious) cross-origin resource sharing.
E.g. some javascript in your current web page posts a password.

I am using Istio. It magically takes the CORS origin and rewrites it. So if you 
do a:

    ```wp-block-preformatted
    GET /
    Origin: foo
    ```

then it will respond:

    ```wp-block-preformatted
    200 OK
    Access-Control-Allow-Origin: *
    ```

*if* its configured for ‘*’ policy.

Now, the problem is, I have two clients that are using OpenID Connect. They are 
fetching the keys for jwks validation. They run in the same browser. One of them
does:

    ```wp-block-preformatted
    GET /keys
    Origin: app-1
    ```

the other does

    ```wp-block-preformatted
    GET /keys
    Origin: app-2
    ```

Unfortunately, the browser *caches* the 2nd response, returning the response app-
1 got (with the wrong Access-Control-Allow-Origin) in it.

Why? Well, let’s dive into some specs. [Here](https://fetch.spec.whatwg.org/#cors-protocol-and-http-caches)
we find the answer.

> If [CORS protocol](https://fetch.spec.whatwg.org/#cors-protocol) requirements 
> are more complicated than setting `[`Access-Control-Allow-Origin`](https://fetch.spec.whatwg.org/#http-access-control-allow-origin)`
> to `*` or a static [origin](https://html.spec.whatwg.org/multipage/origin.html#concept-origin),``
> Vary`` is to be used. [[HTML]](https://fetch.spec.whatwg.org/#biblio-html) [[HTTP]](https://fetch.spec.whatwg.org/#biblio-http)
> [[HTTP-SEMANTICS]](https://fetch.spec.whatwg.org/#biblio-http-semantics) [[HTTP-COND]](https://fetch.spec.whatwg.org/#biblio-http-cond)
> [[HTTP-CACHING]](https://fetch.spec.whatwg.org/#biblio-http-caching) [[HTTP-AUTH]](https://fetch.spec.whatwg.org/#biblio-http-auth)

Huh. I’m supposed to add a ‘Vary’ header to these. But, sadly, I am not in control
of these applications. What is one to do? RTFC for [envoy](https://github.com/envoyproxy/envoy/blob/0418a855d9f9e37ec70b4c6d1942688fc8bb5751/source/extensions/filters/http/cors/cors_filter.cc#L70)?
