Option to update CSP during runtime
link-point opened this issue · comments
Our web app is being embedded into other people's websites through iframes. For this reason we need to change the code (add frame ancestor exception to CSP) and deploy it every time we have a new client.
Is there a possibility to update CSP information in helmet during runtime? In this case we could have the additional list of CSP in the database and refresh it in the running application automatically.
Yes, this is possible. I think you have three options.
-
Conditionally use the middleware with different options. This is documented here.
-
Use functions for
contentSecurityPolicy
directive values, if that works for you.The
contentSecurityPolicy
middleware supports functions, not just strings, as directive values. For example:app.use(helmet({ contentSecurityPolicy: { directives: { // ... frameAncestors: [(req, res) => { return Math.random() > 0.5 ? "example.com" : "example.net"; }], }, }, }));
This only supports one directive value, though, so it might not work for you.
This is poorly-documented and I filed #404 to clean this up.
-
Don't use Helmet at all, and roll your own
Content-Security-Policy
middleware.app.use(helmet({ contentSecurityPolicy: false, })); app.use((req, res, next) => { res.setHeader( "Content-Security-Policy", `default-src 'self'; frame-ancestors ${sanitizedFrameAncestorsList.join(" ")}` ); next(); });
I'm going to close this issue because I think I've answered your question, but let me know if that's wrong and I'll reopen.