You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Reacted by Rich Harris, Albert Mañosa, Dan Kozlov, Patrick Hintermayer, kvn-shn, Seth Corker, Julian Tescher, Karl Erik Hofseth, Yusoof Moh, Caspian Baska and 8 more
I just want to highlight that it's really important that eval is not used in SvelteKit.
Can we ensure that there is no unsafe use, as @dominikg has suggested.
I've just been looking at an issue in Sapper here where the issue is that we have to allow unsafe-eval, which defeats the purpose of using CSP.
cc/ @Conduitry (as we were talking about this in the other ticket).
is there any way to move the inline script for SvelteKit to an external one? I’d like to enforce a stricter CSP, but currently need unsafe-inline to accommodate. Thanks!
For server-rendered pages we could just use a nonce, I think? For pre-rendered pages that's no good, we would need to generate a hashed file (say /boot/xyz123.js) for each unique script.
As far as I can see it's only the init script in the head, right? Nothing else is inline? Or does this depend on build configurations/adapters?
In any case meta policies are allowed alongside HTTP policies. However, any source must pass all specified policies, meaning if you wanted to load scripts from a CDN it must be specified both places and the HTTP header must still send unsafe-inline. Basically, generating CSP in more than one place is kind of a mess.
For pre-rendered pages that's no good, we would need to generate a hashed file (say /boot/xyz123.js) for each unique script.
I think one of the advantages of nonces is that with them and strict-dynamic you can load arbitrary scripts (say, Google Analytics, or a some other source) and since they're trusted, they can load anything they need, without needing to allowlist them. This is helpful for scripts distributed and loaded via CDN where the hashes might change frequently, and reduces maintenance cost.
I'm not an expert here, but I think if the page is guaranteed to be static, then a static nonce would also work and not pose a security risk. Alternatively, the pages could be build with a static, known nonce placeholder (ideally a build/deploy time secret) which could then be replaced on each request with a dynamic nonce. We've used this approach in our cloudflare workers app and it seems to be working pretty well so far.
@pzuraq Nonces must always be unique for each HTTP request. If you send the same one twice then an attacker can inject inline script with that nonce simply by checking the nonce themselves previously.
Nonces also don't work for static hosts where you don't have the ability to generate them.
Additionally, we have the problem described above that adding the nonce (or a hash) in a <meta> tag is hard to combine with a CSP set outside it (and is therefore hard to configure and use). If we set script-src nonce-randomString then any script-src policy defined in the HTTP header must include 'unsafe-inline'. If a resource fails either policy it will be blocked. I think this also means that any domains listed in the HTTP header must also be replicated.
It'd be nice if CSPs were just combined additively, but according to the spec they're not.
I think it would generally be a good idea to not rely on the adapters and/or runtime modification to avoid unsafe-inline. Moving the current inline script to a different file would work on all adapters without any extra work, and avoids adding any CSPs. If you need nonces to run Analytics you can still do that, but it doesn't seem like SvelteKit should need it honestly.
Hashing the script would work, as it's all build-time (and therefore works for static as well), but we'd still need 'unsafe-inline' in any HTTP headers if we're adding it in a <meta> tag.
Additionally, as discussed in #1776, using nonces and hashes don't work with manifest V3. It'd be a bit of a shame to not support writing browser extensions at all.
The only downside to moving the script to an external file is in implementation. I've started looking at it (I'm writing an app that really should have a strict CSP), but I'm having a hard time figuring how to do it. Speaking of, if @benmccann or someone has a tip to how one could modify the page render pipeline to emit a script file I'm all ears. I've found the script itself in server/page/render.js, but I'm not sure how I would create a separate file and have it be served and stuff?
But that's unfortunate because the script has to start executing in order to begin loading all of the resources. Maybe it'll execute quickly enough that it wouldn't make a difference?
Edit: I guess maybe you could MITM with a static nonce value?
Thanks for the valuable feedback everyone. I think we're close to squaring all the various circles.
Ideally I'd like to see a flag in config, based on which important (for performance) scripts and styles can be either inline or in external files. What do you think?
Yeah, it probably makes sense for this to live in Kit rather than adapters having to jump through lots of hoops themselves. Something like this perhaps:
Woah! This is very useful (I don't think I'd have been able to figure out how to get autocompletion for unsaf... while also supporting URLs etc).
Agree re string[] rather than string | string[]. I think ['self'] is preferable to ["'self'"], even if it would be more 'correct' to do the pedantic thing — I don't think there's any real potential for ambiguity, and the author of csp-typed-directives appears to agree.
Of course, by generating the hash at request time we are essentially bypassing that, making the function more or less identical with nonces, so really I think implementation concerns should decide here.
To clarify, I was only proposing hashing the scripts that SvelteKit generates — not injecting hashes (or nonces, for that matter) in cases like this:
<divclass="comment"><p>someone forgot to escape user input <script>alert('lol')</script></p></div>
That would mean people were responsible for their own dynamic scripts (google analytics, etc), either by putting them in static and allowing self, or using strict-dynamic and a) generating the hash themselves, as suggested above, or b) creating the script dynamically when the app loads (right now that would probably happen in the root __layout, but we'll probably add a client-side equivalent of src/hooks.js at some point soon, where this sort of thing could happen).
Then when we render dynamically we can use nonces instead.
Yeah, I think this hybrid approach makes sense. Nonces for dynamic, hashes for static. And we could expose the nonce — %svelte.nonce% — for things like analytics snippets and external scripts with strict-dynamic, but disallow its usage during prerendering, perhaps.
For posterity, I'm going to recap a discussion I had with @antony earlier since he raised a very reasonable question — rather than having Kit generate CSP headers based on config, what if it just gave you the tools you need to generate them yourself? For example this:
On the face of it this makes a lot of sense, since it allows Kit to get out of the way, and provides app authors with maximum flexibility. But after discussing it we concluded it probably wasn't the right direction:
headers are preferable to <meta http-equiv> in situations where you control them (i.e. not prerendering)
if using headers, we'd need to change the handle API and you'd need to implement a custom hook (and be careful to generate well-formed headers):
const{ response, hashes }=awaitresolve(request);if(hashes){// only true for pagesresponse.headers.set('content-security-policy': `script-src: ${hashes.script}`);}
prerendering would have to read the headers you'd generated in your custom hook, and inject them into the head using <meta http-equiv>. but this is tricky: normally the way to inject content into the head is to insert it right before </head, since otherwise you have to use brittle regexes, but with CSP the <meta> needs to go before your inline scripts and styles. So realistically we'd need to use cheerio or something to parse the HTML, which will slow prerendering down and make Kit heftier
So there'd be a lot more hoop-jumping, for both authors and the framework, and you'd lose the benefits of typechecked directives etc. The result would be that way fewer people would end up enabling CSP, unless someone made them do it. All in all it feels like this is one of those places where it makes sense for the framework to step in and say 'I got this'.
Reacted by Akumetsu, Kristen and Karl Erik Hofseth
Yeah, I think this hybrid approach makes sense. Nonces for dynamic, hashes for static. And we could expose the nonce — %svelte.nonce% — for things like analytics snippets and external scripts with strict-dynamic, but disallow its usage during prerendering, perhaps.
@Rich-Harris Would this be optional, to allow people to choose between using hashes or nonces based on what makes more sense to their setup? I think we would prefer hashes for the reasons I mentioned above, would help us cache our responses more aggressively and not need to rerender just to update the nonce.
To clarify, I was only proposing hashing the scripts that SvelteKit generates — not injecting hashes (or nonces, for that matter) in cases like this:
Absolutely! I was just saying the (admittedly minor) security differences between hashes and nonces kind of disappear for us. If you can compromise a nonced init script in Kit then you could do the same for a hashed script (though both would be difficult), when with only compile-time hashes you have a slight advantage.
On hashes for external scripts: This is a feature of CSP 3, and annoyingly not yet implemented in Firefox. That's a bit of a bummer. As far as I can tell other browsers support this. This is problematic for using hashes generated at compile time to allow our static scripts, which is otherwise an idea I really like. I'm not sure how much we should let this affect us though, since this is Firefox simply not being in line with spec and is likely to be fixed at some point.
And we could expose the nonce — %svelte.nonce% — for things like analytics snippets and external scripts with strict-dynamic, but disallow its usage during prerendering, perhaps.
We would need to be careful about this, no? As @pzuraq mentions this can be a target for attacking the SSR, and we don't want this to get through:
<divclass="comment"><p>someone forgot to escape user input <scriptnonce="%svelte.nonce%">alert('lol')</script></p></div>
I forget exactly how Kit's render pipeline works, but I imagine we can search for this string in, say, only the static app.html before any other content is added?
Suggestion so far (in auto mode):
Kit builds all the static files, hashes them, and stores the hashes somewhere (manifest?)
The adapter calls prerender. Kit renders the files, hashes the inline scripts, adds those to the manifest. All script links are given integrity attributes (required for hashes of external scripts to work)
Runtime. If Kit serves a response from the prerender cache, it sends with the hash headers relevant (that page and relevant assets). If instead it renders the page, it works mostly like in my PR (adapter gives a nonce, inserted into all script tags).
In nonce mode it would ignore hashes completely (basically my PR). In hash mode I guess it would dynamically hash the contents when rendering? Insert integrity attributes like during prerendering, hash the inline script, and send CSP headers with hashes.
Do we hash/nonce all scripts even if we're not in sctrict-dynamic? I don't think it can hurt, and it saves us from another toggle.
Wait, I left out kit.externaliseScriptsAndStyles from that. That would only have effect during prerendering I think (we've discussed at length here how that's almost impossible to combine with SSR), and would cause the prerender to return separate html and js file which can be placed somewhere. Some predictable url is needed, which Kit can insert into the html at render and then later serve the JS file from. Anything rendered at runtime basically ignore this.
We would need to be careful about this, no? As @pzuraq mentions this can be a target for attacking the SSR, and we don't want this to get through:
My understanding was that %svelte.nonce% would only be replaced in sections of the code that are known to be safe, e.g. before user content that has been SSR'd is inserted. That's a fine setup, because there's no user content added before the replacement.
The problem comes if we want to cache the entire response, so we don't need to enter into SSR in the first place. When caching the response, we lose context so there's no way to tell which parts of the response are "safe" to replace in and which are not. Responses could potentially be cached in parts to avoid this, maybe even the nonce placeholder could be cached as part of the response and generated uniquely for each response 🤔 but that could be platform specific. Cloudflare uses the Cache API to cache responses, and it expects a full Response object, so you'd have to like, store this info in a header or something like that.
My understanding was that %svelte.nonce% would only be replaced in sections of the code that are known to be safe, e.g. before user content that has been SSR'd is inserted. That's a fine setup, because there's no user content added before the replacement.
Yeah, that was my assumption too, just wanted to make it explicit.
%svelte.nonce% in rendered content wouldn't be replaced, because in production no string replacement happens. But I opened #3490 anyway because I'm a completionist
Thought I'd mention something that just popped up in the Discord that's a bit related. Currently, we have a few places where we need to use dynamic styles in our templates, as things like the background color of certain elements are theme-able. This currently does not work with our CSP, as we do not allow unsafe-inline for styles, so there's a brief pop-in flash as the page rerenders from JS taking over, at which point the styles are set via a trusted script and render properly.
Not sure what the best way to solve this would be, and it's definitely an edge case so it doesn't necessarily have to be in the first pass. I believe style attributes can also be hashed, so maybe there could be a way for a user to indicate that a certain style tag should be hashed and included?
@pzuraq That seems like it touches on both Kit and Svelte itself, no? Svelte is responsible for generating those inline styles (this is one annoyance of CSP, that it often requires passing a nonce or a hash all the way through an application stack from "the thing that generates CSS" to "the thing that sets HTTP headers").
Anyways, this is controlled by the style-src-attr directive, and allows hashing if you also specify unsafe-hashes. Noncing is not available for attribute styling. I'm not sure if I like adding unsafe-hashes (though I think it isn't as unsafe as the name implies).
Yeah, agreed re: unsafe-hashes. Another option would be to somehow allow SvelteKit to generate a stylesheet or style tag dynamically, and generate the hash for that. Will have to think about what would be the best way to do that.
Closed via #3499. Opened #3555, #3556, #3557 and #3558 to track follow-up tasks. I'm not going to be working on CSP stuff in the near term, so if anyone needs these and is up for a PR then please feel welcome!
Activity
acoyfellow commentedon Mar 31, 2021
Hi - it looks like this (mostly) can be solved with
hooksnow, in thehandlefunction.no
nonce's yet but i'm working on it, maybe someone can see that solutionhttps://gist.github.com/acoyfellow/d8e86979c66ebea25e1643594e38be73
furudean commentedon Mar 31, 2021
seanlail commentedon Apr 7, 2021
@acoyfellow Great work so far!
I just want to highlight that it's really important that eval is not used in SvelteKit.
Can we ensure that there is no unsafe use, as @dominikg has suggested.
I've just been looking at an issue in Sapper here where the issue is that we have to allow
unsafe-eval, which defeats the purpose of using CSP.cc/ @Conduitry (as we were talking about this in the other ticket).
Rich-Harris commentedon Aug 3, 2021
Noting this, from Twitter:
For server-rendered pages we could just use a
nonce, I think? For pre-rendered pages that's no good, we would need to generate a hashed file (say/boot/xyz123.js) for each unique script.Karlinator commentedon Aug 14, 2021
As far as I can see it's only the init script in the head, right? Nothing else is inline? Or does this depend on build configurations/adapters?
In any case meta policies are allowed alongside HTTP policies. However, any source must pass all specified policies, meaning if you wanted to load scripts from a CDN it must be specified both places and the HTTP header must still send
unsafe-inline. Basically, generating CSP in more than one place is kind of a mess.See: https://www.w3.org/TR/CSP3/#multiple-policies
Putting the init script in a separate file is a much better option imo.
pzuraq commentedon Aug 14, 2021
@Rich-Harris
I think one of the advantages of nonces is that with them and
strict-dynamicyou can load arbitrary scripts (say, Google Analytics, or a some other source) and since they're trusted, they can load anything they need, without needing to allowlist them. This is helpful for scripts distributed and loaded via CDN where the hashes might change frequently, and reduces maintenance cost.I'm not an expert here, but I think if the page is guaranteed to be static, then a static nonce would also work and not pose a security risk. Alternatively, the pages could be build with a static, known nonce placeholder (ideally a build/deploy time secret) which could then be replaced on each request with a dynamic nonce. We've used this approach in our cloudflare workers app and it seems to be working pretty well so far.
Karlinator commentedon Aug 14, 2021
@pzuraq Nonces must always be unique for each HTTP request. If you send the same one twice then an attacker can inject inline script with that nonce simply by checking the nonce themselves previously.
Nonces also don't work for static hosts where you don't have the ability to generate them.
Additionally, we have the problem described above that adding the nonce (or a hash) in a
<meta>tag is hard to combine with a CSP set outside it (and is therefore hard to configure and use). If we setscript-src nonce-randomStringthen anyscript-srcpolicy defined in the HTTP header must include'unsafe-inline'. If a resource fails either policy it will be blocked. I think this also means that any domains listed in the HTTP header must also be replicated.It'd be nice if CSPs were just combined additively, but according to the spec they're not.
I think it would generally be a good idea to not rely on the adapters and/or runtime modification to avoid
unsafe-inline. Moving the current inline script to a different file would work on all adapters without any extra work, and avoids adding any CSPs. If you need nonces to run Analytics you can still do that, but it doesn't seem like SvelteKit should need it honestly.Hashing the script would work, as it's all build-time (and therefore works for static as well), but we'd still need
'unsafe-inline'in any HTTP headers if we're adding it in a<meta>tag.Additionally, as discussed in #1776, using nonces and hashes don't work with manifest V3. It'd be a bit of a shame to not support writing browser extensions at all.
The only downside to moving the script to an external file is in implementation. I've started looking at it (I'm writing an app that really should have a strict CSP), but I'm having a hard time figuring how to do it. Speaking of, if @benmccann or someone has a tip to how one could modify the page render pipeline to emit a script file I'm all ears. I've found the script itself in
server/page/render.js, but I'm not sure how I would create a separate file and have it be served and stuff?pzuraq commentedon Aug 14, 2021
Right, but that only works if the contents of the page itself are dynamic. If they are not, there is no way to attack, unless I'm missing something. The alternative that allows you to still use
strict-dynamicand include external sources is to have a script dynamically add them inline and make that script safe with a hash: https://csp.withgoogle.com/docs/faq.html#static-contentBut that's unfortunate because the script has to start executing in order to begin loading all of the resources. Maybe it'll execute quickly enough that it wouldn't make a difference?
Edit: I guess maybe you could MITM with a static nonce value?
27 remaining items
Rich-Harris commentedon Jan 21, 2022
Thanks for the valuable feedback everyone. I think we're close to squaring all the various circles.
Yeah, it probably makes sense for this to live in Kit rather than adapters having to jump through lots of hoops themselves. Something like this perhaps:
That's something that could happen independently of the CSP work, even though it's motivated by it.
Totally doable — at build time we can hash all the assets, and use the hashes at render time if 'strict-dynamic' is enabled:
Woah! This is very useful (I don't think I'd have been able to figure out how to get autocompletion for
unsaf...while also supporting URLs etc).Agree re
string[]rather thanstring | string[]. I think['self']is preferable to["'self'"], even if it would be more 'correct' to do the pedantic thing — I don't think there's any real potential for ambiguity, and the author of csp-typed-directives appears to agree.To clarify, I was only proposing hashing the scripts that SvelteKit generates — not injecting hashes (or nonces, for that matter) in cases like this:
That would mean people were responsible for their own dynamic scripts (google analytics, etc), either by putting them in
staticand allowingself, or usingstrict-dynamicand a) generating the hash themselves, as suggested above, or b) creating the script dynamically when the app loads (right now that would probably happen in the root__layout, but we'll probably add a client-side equivalent ofsrc/hooks.jsat some point soon, where this sort of thing could happen).Yeah, I think this hybrid approach makes sense. Nonces for dynamic, hashes for static. And we could expose the nonce —
%svelte.nonce%— for things like analytics snippets and external scripts withstrict-dynamic, but disallow its usage during prerendering, perhaps.For posterity, I'm going to recap a discussion I had with @antony earlier since he raised a very reasonable question — rather than having Kit generate CSP headers based on config, what if it just gave you the tools you need to generate them yourself? For example this:
On the face of it this makes a lot of sense, since it allows Kit to get out of the way, and provides app authors with maximum flexibility. But after discussing it we concluded it probably wasn't the right direction:
<meta http-equiv>in situations where you control them (i.e. not prerendering)handleAPI and you'd need to implement a custom hook (and be careful to generate well-formed headers):<meta http-equiv>. but this is tricky: normally the way to inject content into the head is to insert it right before</head, since otherwise you have to use brittle regexes, but with CSP the<meta>needs to go before your inline scripts and styles. So realistically we'd need to usecheerioor something to parse the HTML, which will slow prerendering down and make Kit heftierSo there'd be a lot more hoop-jumping, for both authors and the framework, and you'd lose the benefits of typechecked directives etc. The result would be that way fewer people would end up enabling CSP, unless someone made them do it. All in all it feels like this is one of those places where it makes sense for the framework to step in and say 'I got this'.
pzuraq commentedon Jan 21, 2022
@Rich-Harris Would this be optional, to allow people to choose between using hashes or nonces based on what makes more sense to their setup? I think we would prefer hashes for the reasons I mentioned above, would help us cache our responses more aggressively and not need to rerender just to update the nonce.
Rich-Harris commentedon Jan 21, 2022
Yeah, perhaps we could have an option like this, where 'auto' is the default
Karlinator commentedon Jan 21, 2022
Absolutely! I was just saying the (admittedly minor) security differences between hashes and nonces kind of disappear for us. If you can compromise a nonced init script in Kit then you could do the same for a hashed script (though both would be difficult), when with only compile-time hashes you have a slight advantage.
On hashes for external scripts: This is a feature of CSP 3, and annoyingly not yet implemented in Firefox. That's a bit of a bummer. As far as I can tell other browsers support this. This is problematic for using hashes generated at compile time to allow our static scripts, which is otherwise an idea I really like. I'm not sure how much we should let this affect us though, since this is Firefox simply not being in line with spec and is likely to be fixed at some point.
We would need to be careful about this, no? As @pzuraq mentions this can be a target for attacking the SSR, and we don't want this to get through:
I forget exactly how Kit's render pipeline works, but I imagine we can search for this string in, say, only the static
app.htmlbefore any other content is added?Suggestion so far (in
automode):prerender. Kit renders the files, hashes the inline scripts, adds those to the manifest. All script links are givenintegrityattributes (required for hashes of external scripts to work)In
noncemode it would ignore hashes completely (basically my PR). Inhashmode I guess it would dynamically hash the contents when rendering? Insertintegrityattributes like during prerendering, hash the inline script, and send CSP headers with hashes.Do we hash/nonce all scripts even if we're not in
sctrict-dynamic? I don't think it can hurt, and it saves us from another toggle.Karlinator commentedon Jan 21, 2022
Wait, I left out
kit.externaliseScriptsAndStylesfrom that. That would only have effect during prerendering I think (we've discussed at length here how that's almost impossible to combine with SSR), and would cause the prerender to return separate html and js file which can be placed somewhere. Some predictable url is needed, which Kit can insert into the html at render and then later serve the JS file from. Anything rendered at runtime basically ignore this.pzuraq commentedon Jan 21, 2022
My understanding was that
%svelte.nonce%would only be replaced in sections of the code that are known to be safe, e.g. before user content that has been SSR'd is inserted. That's a fine setup, because there's no user content added before the replacement.The problem comes if we want to cache the entire response, so we don't need to enter into SSR in the first place. When caching the response, we lose context so there's no way to tell which parts of the response are "safe" to replace in and which are not. Responses could potentially be cached in parts to avoid this, maybe even the nonce placeholder could be cached as part of the response and generated uniquely for each response 🤔 but that could be platform specific. Cloudflare uses the Cache API to cache responses, and it expects a full Response object, so you'd have to like, store this info in a header or something like that.
Karlinator commentedon Jan 21, 2022
Yeah, that was my assumption too, just wanted to make it explicit.
Rich-Harris commentedon Jan 21, 2022
%svelte.nonce%in rendered content wouldn't be replaced, because in production no string replacement happens. But I opened #3490 anyway because I'm a completionistpzuraq commentedon Jan 22, 2022
Thought I'd mention something that just popped up in the Discord that's a bit related. Currently, we have a few places where we need to use dynamic styles in our templates, as things like the background color of certain elements are theme-able. This currently does not work with our CSP, as we do not allow
unsafe-inlinefor styles, so there's a brief pop-in flash as the page rerenders from JS taking over, at which point the styles are set via a trusted script and render properly.Not sure what the best way to solve this would be, and it's definitely an edge case so it doesn't necessarily have to be in the first pass. I believe
styleattributes can also be hashed, so maybe there could be a way for a user to indicate that a certain style tag should be hashed and included?Karlinator commentedon Jan 22, 2022
@pzuraq That seems like it touches on both Kit and Svelte itself, no? Svelte is responsible for generating those inline styles (this is one annoyance of CSP, that it often requires passing a nonce or a hash all the way through an application stack from "the thing that generates CSS" to "the thing that sets HTTP headers").
Anyways, this is controlled by the
style-src-attrdirective, and allows hashing if you also specifyunsafe-hashes. Noncing is not available for attribute styling. I'm not sure if I like addingunsafe-hashes(though I think it isn't as unsafe as the name implies).pzuraq commentedon Jan 22, 2022
Yeah, agreed re:
unsafe-hashes. Another option would be to somehow allow SvelteKit to generate a stylesheet orstyletag dynamically, and generate the hash for that. Will have to think about what would be the best way to do that.Rich-Harris commentedon Jan 26, 2022
Closed via #3499. Opened #3555, #3556, #3557 and #3558 to track follow-up tasks. I'm not going to be working on CSP stuff in the near term, so if anyone needs these and is up for a PR then please feel welcome!
benmccann commentedon Feb 26, 2022
CSP docs are here: https://kit.svelte.dev/docs/configuration#csp
backend: Manually add a nonce to the svelte script