Google Cloud Storage and CORS (1/2)
Don’t be scared, it’s just an Error!
Jump scares can be exciting, but the ones we get from CORS errors can be genuinely frightening. Have you heard this scary story before? Perhaps you looked up the error on Google and found a great Stack Overflow answer, skimmed it quickly, and added the header you needed. You might have put the whole incident out of your mind until the next time this happened, and then you found the same SO response. Is there an end in sight? In short, yes. But let’s break it down.
Understanding same-origin resource sharing
To understand CORS, short for cross-origin resource sharing, it helps to first understand same-origin resource sharing. The same-origin policy is a security policy enforced on web browsers to prevent interactions between resources from different origins, ie domains. I like to think of it as preventing a bait and switch. If I go to a website, say cat.pics, I expect to interact with the resources of cat.pics.
But what if cat.pics, instead of showing photos of adorable cats, downloaded malicious software from some other website? The same-origin policy looks at the calls that are coming from a website and ensures they come from, you guessed it, the same origin. So the same-origin policy is a good thing! It protects users. However, it also prevents legitimate interactions between known origins.
For example, a script on a page hosted on App Engine at example.appspot.com might need to use resources stored in a Cloud Storage bucket at example.storage.googleapis.com. These are two different origins from the perspective of the browser. Thanks to that trusty same-origin policy, the browser won’t allow a script from example.appspot.com to fetch resources from example.storage.googleapis.com. This will manifest as a CORS error.
The dreaded CORS error
I’m going to go out on a limb and say that if you’re still reading this, you’ve probably experienced the above example before. Great. What does this mean, and how do we fix it?
The Cross Origin Resource Sharing spec, AKA CORS, was developed by the World Wide Web Consortium to get around the limitations of same-origin policy. Cloud Storage supports CORS by allowing you to configure your buckets to support it.
So in the above example case, you can configure the example.storage.googleapis.com bucket so that a browser can share its resources with scripts from example.appspot.com. Yay! No more CORS error!
But wait, there’s more!
There’s more to talk about with CORS, and much connecting to Google Cloud Storage. But that’s all for this installment, so stay tuned for part 2!