Reputation: 47
I'm trying to secure my website (built with node.js/express/npm) with correct CSP. I'm using npm helmet package and trying to configure CSP using nonce. I have tried to pass nonce in any possible way but I can't figure why Chrome is refusing to execute inline styles or scripts. A code example below:
// my app.js
// I generate a new random nonce value for every response.
const nonce = crypto.randomBytes(16).toString("base64");
//configure CSP under helmet
app.use(
helmet.contentSecurityPolicy({
useDefaults: false,
directives: {
defaultSrc: ["'self'"],
connectSrc: ["'self'", ...connectSrcUrls],
scriptSrc: ["'self'", "unsafe-inline", `nonce-${nonce}`, ...scriptSrcUrls],
styleSrc: ["'self'", ...styleSrcUrls],
workerSrc: ["'self'", "blob:"],
objectSrc: [],
imgSrc: [
"'self'",
"blob:",
"data:",
"https://res.cloudinary.com/dqcadja0y/",
"https://images.unsplash.com/"
],
fontSrc: ["'self'", ...fontSrcUrls],
},
})
);
//I pass nonce
app.get('/', (req, res) => {
res.render('home', { style: 'app', nonce: nonce });
});
//example of use in script e.g. mapbox
<script nonce="${nonce}" src='https://api.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.js'></script>
error return from the console:
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https://fonts.googleapis.com/ https://api.mapbox.com/ https://api.tiles.mapbox.com/ https://fonts.googleapis.com/ https://fonts.gstatic.com https://use.fontawesome.com/ https://cdn.jsdelivr.net". Either the 'unsafe-inline' keyword 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.
I tried to look into documentation of express, helmet but I cant figure this out. What am I doing wrong?
Upvotes: 1
Views: 1828
Reputation: 3455
You have an inline style, and as the error message says you have to either add 'unsafe-inline' or a nonce. When it is a tag you could also use a hash. If it is a style attribute (style="...">) the hash won't work, and likely not nonce either in most cases. Note that you have set 'unsafe-inline' for script-src, but you also have to be more permissive in style-src. An alternative is of course to move styles from inline to a separate file located in one of the style location you have allowed.
Upvotes: 1