Reputation: 11
My NextJS app is scanned by client’s pen test software and pointing that “unsafe-inline” should not be used. However I can’t get the nonce working and getting follow errors when MUI components is used on the page.
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' 'nonce-MDkzMjY2YmMtYTA2My00YzczLTljNTYtNjYyY2ZiODgyNjE0'". Either the 'unsafe-inline' keyword, a hash ('sha256-7uP4UMn0lzlm+J1RYqmY7+9oGVF+O/z16924/Q7zptE='), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.
Things that I tried:
Here on GitHub I uploaded a test project showing the problem. It is just a NextJS starter project using App Router. Added middleware for nonce generation and also the MUI CacheProvider. The only page is just the default start page all cleaned up and with just one CircularProgress UI from MUI.
What else I have to add or set so that MUI doesn’t produce those error anymore? I have been stuck on this problem for over a week now and I am pulling my hair out. Please help!
Upvotes: 1
Views: 1096
Reputation: 3475
First of all you need to decide if 'unsafe-inline' for style really is a problem. tl;dr: If the remainder of your CSP is strict, not much bad can happen through a CSS attack.
You say that you have experimented with nonces and mention them in relation to cookies and cache. Nonces have no function in cookies, and if the nonce value is available on the client, it can be used by an attacker. They need to be in style tags like this
<style nonce='<nonce value>'>... css code goes here ...</style>
If you try to use them in style attributes, these are not nonceable elements and it will not work. And remember that hashes will only work in this case if you also set 'unsafe-hashes'
If some code inserts a style element, it will also need to add the nonce. This will get complicated, especially if handled by 3rd party code.
You should identify all the offending code and see if any of it can be rewritten. Nonces are hard. Hashes are a bit easier, but will only work if the style being output is static and limited to a reasonable number of variations/hashes.
Upvotes: 0