nibtime / next-safe-middleware

Strict CSP (Content-Security-Policy) for Next.js hybrid apps https://web.dev/strict-csp/
https://next-safe-middleware.vercel.app
MIT License
78 stars 20 forks source link

Issue with styles when running application in development mode #49

Closed benhodgson87 closed 2 years ago

benhodgson87 commented 2 years ago

Hi,

Love this project, amazed this still isn't a part of the core Next functionality.

Unfortunately we're running into an issue with loading styles in development (default Next CSS modules setup). It seems that because the nonce is provided to the CSP in development, it overrides the 'unsafe-inline' that is needed to allow style-loader to inject the styles in development without the nonce.

Content Security Policy: Ignoring "'unsafe-inline'" within script-src or style-src: nonce-source or hash-source specified 

As a result our styles don't load in development, but do load in production, where the nonce is correctly applied.

Is it possible to disable including the nonce in the CSP when in development mode as a workaround for this?

Basic repro of setup: https://gist.github.com/benhodgson87/8507b754aa5015181341d5565493cce2

"@next-safe/middleware": "^0.8.0",
"next": "12.1.6",
benhodgson87 commented 2 years ago

Closing this; discovered that applying reportOnly: process.env.NODE_ENV === 'development' to the CSP config resolves this 🙏

nibtime commented 2 years ago

Hi @benhodgson87

thank you very much for reporting this. That is actually a bug of this lib, strict CSP is incompatible wit Next dev server, so I fixed this in #47, nonce won't get applied in upcoming 0.9.0 anymore in dev build. Should you host your app on Vercel I especially recommend the update because of (#45) so you don't receive annoying notifications from Vercel beacuse of CPU usage :D

Your workaround resolves the problem but it also leads to a misuse of report-only mode. The report only mode is intended for a gradual rollout of enforce mode into production. When running a dev server you actually want enforce mode for things like images and stylesheets so you can instantly spot missing sources in your CSP base config visually.

What I always do in projects is the following: I set the env var CSP_REPORT_ONLY, but only for the production environment (not NODE_ENV, e.g. on Vercel it will be VERCEL_ENV from .env.local, that depends on the hosting/CI provider). So the CSP will be always in enforce mode and possibly break things in development and preview builds (there also with strict CSP applied), but not in production builds for the live website. Once I got some reporting data from production and see that everything seems OK, I delete the CSP_REPORT_ONLY env var, redeploy the production build and thereby activate CSP enforce mode for the live website.

nibtime commented 2 years ago

@all-contributors add @benhodgson87 for bug

allcontributors[bot] commented 2 years ago

@nibtime

I've put up a pull request to add @benhodgson87! :tada: