lordbyron lordbyron - 2 years ago 57
HTML Question

What does it mean to set a Content Security Policy on response to a non-HTML request?

I understand that I might set a CSP header for the main page of my site, say

, to restrict from where I can load scripts and other resources. But, if there is no CSP on the main page, how will the browser treat a policy on a subsequent request?

This is two examples in one:

  1. I browse to
    and get back some HTML (no CSP header)

  2. The HTML includes a script from

  3. This script requests some data from the API by issuing a GET to

  4. The same script then opens a websocket to the same domain,

  5. The same script then makes another request, POSTing externally to

[*] In steps 2 and 3, what would happen if the script.js or the JSON response came back with a restrictve CSP, like
Content-Security-Policy: default-src 'none'
? Would any downstream requests be changed? Does the browser do anything to prevent any of the script's requests? Or are the allowed because the original page load did not include any CSP?


Answer Source

The current CSP spec (version 2) says (emphasis mine):

3.6. Policy applicability

Policies are associated with an protected resource, and enforced or monitored for that resource. If a resource does not create a new execution context (for example, when including a script, image, or stylesheet into a document), then any policies delivered with that resource are discarded without effect. Its execution is subject to the policy or policies of the including context.

CSPs only apply to resources that create a new execution context (i.e., a Web page), which includes only top-level documents, embedded objects like <iframe>s, and scripts loaded as Web Workers. If a resource is served over HTTP and that reource is not used in a way that creates a new execution context, the CSP has no effect.

Therefore, your scripts will behave identically whether or not they are served with a Content-Security-Policy header.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download