So I know that using innerHTML with user input is not safe but I'm wondering if it's okay if you're using radio buttons, where the only user input is checked vs unchecked.
My JS looks like this: const topsButton = document.getElementById("tops"); topsButton.addEventListener("click", () => { chart.innerHTML = "<div>somehtml</div>"});
this JS is embedded in a script tag in my HTML.
Can this be exploited?
I know that using innerHTML with user input is not safe
The issue that arises when using innerHTML with user input is that the document could be corrupted by a "bad" input. In a benign case, the user might accidentally paste something that messes up the page formatting; in the worst cases, an attacker may manipulate the user into inputting code that steals their credentials or performs privileged actions etc.
The risk comes from unconstrained user input rather than user input itself. If I have a text input whose contents get copied verbatim into the innerHTML of an element, that would generally be considered risky, or at least highly questionable. If the contents are run through a high quality HTML sanitizer before being added to the page, that would be significantly less risky.
In this case, you're just adding a known HTML payload depending on user input. This is not a risky behavior. For what it's worth, that particular snippet looks quite safe to me but I am not accredited as an HTML sanitizing library!
As an aside, innerHTML manipulation can be considered a bit of a "code smell" – partly because of the HTML injection security aspects, partly because it tends to make it harder to make sure that the document is "well formed", potential performance implications .... You might instead having that <div>
within the document and hiding/revealing it with CSS and appropriate ARIA markup.