Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow inline scripts to have a nonce added #644

Merged
merged 1 commit into from
Jan 14, 2022
Merged

Conversation

traherom
Copy link
Contributor

@traherom traherom commented Nov 4, 2021

The script insertion method introduced in 1.6.0 is very clean and avoids using eval(), which is great. However, it breaks when using CSPs that require a nonce for inline scripts. While evalScript does try to copy all the incoming script's attributes, this doesn't work for nonce because a) it appears to be filtered from the attributes and b) wouldn't actually match the nonce for the original page anyway, since each request's nonce is different in most setups.

The CSP script-src 'self' 'nonce-9190f323fb54b166d23a0ad59387dabf' 'unsafe-eval' used to work with HTMX, but no longer does if you were relying on inline scripts. Changing it to add 'unsafe-inline' would work, but at that point there feels like almost no point to having the CSP.

This PR adds an inlineScriptNonce configuration setting to allow nonce-based CSPs to still work with the new script insertion method. It's not flawless from a security standpoint--it essentially just allows all inline scripts in HTMX requests to work, but at least then you can still have a stronger CSP for non-HTMX pages/requests. This also still isn't ideal since now an attacker could grab the nonce from the HTML.

Usage-wise, it's working for me using this in my base HTML:

  <meta name="htmx-config" content='{"inlineScriptNonce":"{% csp_nonce %}"}'>

Which renders to include the original page's nonce:

  <meta name="htmx-config" content='{"inlineScriptNonce":"9190f323fb54b166d23a0ad59387dabf"}'>

Again, not flawless but at least you put a slight barrier up! Truly security conscious people should probably just put the dang script in a file and not inline.

…ed CSPs to still work with the new script insertion method.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants