Defining a dynamic Content Security Policy in a Single Page Application
Asked Answered
B

1

9

I want to define a content security policy that allows loading images from any origin by default but restricts this to allow only a specific set of origins in some sections of the website.

In a traditional website that makes a new HTTP request for every navigation, this could be easily done by sending a different Content-Security-Policy HTTP header for the pages that require the stricter policy. But in a single page application, this is of course not possible because navigating to a more restrictive section of the app does not cause a new HTTP request (also I would like to define policies on more dynamic conditions than a URL navigation).

I know that—besides in an HTTP header—CSP policies can also be defined in a meta tag and when multiple CSP policies are defined a request must pass all of them to be permitted. So my first approach to solving the problem was setting a default CSP in a Content-Security-Policy header for the entire page and then dynamically set more restrictive policies by adding a <meta http-equiv="Content-Security-Policy" content="…"> tag to the document's head when required.

And this works just fine for dynamically adding more restrictive policies. The big problem is that removing that meta tag or modifying it does not remove or modify the associated content security policy (tested in Chrome in Firefox). This behavior is defined in the W3C Content Security Policy spec:

Note: Modifications to the content attribute of a meta element after the element has been parsed will be ignored.

So is there any way to dynamically add (and more importantly also remove) a content security policy that does not rely on a HTTP navigation? I would like to avoid setting a restrictive image policy by default and then excepting individual images through hashes or nonces as this would be quite elaborate to implement.

Binocular answered 12/4, 2021 at 3:12 Comment(1)
no there isn't. even if there is some kind of a "hack" it will likely be patch when new version of browsers are released.Troposphere
M
1

In SPA you can each time to create a new fullscreen iframe and fill it by script. <iframe>, as nested browsing context, can have own CSP meta tag regardless of the parent page.
The parent page will contains only script to manage iframe's content, may be it's possible to use Worker() for this purpose.

Mischievous answered 15/4, 2021 at 4:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.