20

I understand that I might set a CSP header for the main page of my site, say https://example.com, 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 https://example.com and get back some HTML (no CSP header)
  2. The HTML includes a script from https://example.com/script.js [*]
  3. This script requests some data from the API by issuing a GET to https://api.example.com [*]
  4. The same script then opens a websocket to the same domain, https://api.example.com
  5. The same script then makes another request, POSTing externally to https://api.analytics.com

[*] 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?

Thanks!

lordbyron
  • 588
  • 1
  • 5
  • 11

1 Answers1

36

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.

Community
  • 1
  • 1
apsillers
  • 112,806
  • 17
  • 235
  • 239
  • 1
    Yes but in general json response can be presented as a top level document. Currently I simply add CSP to each response but is it an overkill? Should it somehow be based on the content-type? text/html, application/pdf only e.t.c. ? – norekhov May 01 '22 at 07:49
  • Thanks for your answer. Do you know if there's any info about execution context in a browser context (I assume they are not speaking about a javascript context)? – Xen_mar Oct 12 '22 at 07:59