NetEscapades.AspNetCore.SecurityHeaders icon indicating copy to clipboard operation
NetEscapades.AspNetCore.SecurityHeaders copied to clipboard

Add support for `unsafe-hashes` on `style` attributes, and inline event handlers (fixes #155)

Open tiesmaster opened this issue 7 months ago • 4 comments

As discussed in #155, this adds an additonal tag helper which allows you to hash style attributes, and inline event handlers. A couple notes:

  • I noticed a couple typos, so I fixed those, I hope that's ok (otherwise, I can remove them from the PR)
  • the example in the test site actually didn't didn't leverage the HashTagHelper, as that just contained .UnsafeInline().UnsafeEval(), which allows all the unsafe examples in the test page
    • in order to get this to work, I added .WithHashTagHelper(), and .WithNonce(), as also documented in the README.md
    • what's important to mention here, is that, if you add that, you'd get CSP violations in Dev Tools of Firefox (even though they work), in Chrome, no warnings pop up!
  • you're not able to hash multiple attributes with the current implementation (see below)

Hashing multiple attributes on the same element?

With the current implementation, only 1 occurence of the asp-add-attribute-to-csp is supported, after the first run, all attributes for this tag helper will be removed (as does the HashTagHelper). Although, you might not run into this often, but still I think it would be good to support this scenario. For example, if you have multiple inline event handlers, then you'd need to specify multiple attributes. I don't know if you can add the same attributes more than once, but it didn't seemed like it does, as Visual Studio warned about that. Next, we have a separate attribute for the hash type, so that's an attribute you share with other invocation of the same tag helper, so you wouldn't be able to remove that attribute anymore, which is sloppy.

What I'm thinking now is to still go with the approach of adding the name of the target attribute in the asp-add-...-to-csp attribute, and then also do that for the hash type attribute, like this:

<button style="background: red"
    onclick="..."
    asp-add-style-attribute-to-csp
    csp-style-attribute-hash-type="SHA512"
    asp-add-onclick-attribute-to-csp
    csp-style-onclick-hash-type="SHA512">
    Click me!
</button>

Or maybe just allow for setting the hash type on that attribute itself?

<button style="background: red"
    onclick="..."
    asp-add-style-attribute-to-csp
    asp-add-onclick-attribute-to-csp="SHA512">
    Click me!
</button>

tiesmaster avatar Jul 03 '24 21:07 tiesmaster