• caglararli@hotmail.com
  • 05386281520

Is it practically possible to use SVGs to their full potential while still enjoying all protections offered by Content Security Policy (CSP)?

Çağlar Arlı      -    5 Views

Is it practically possible to use SVGs to their full potential while still enjoying all protections offered by Content Security Policy (CSP)?

My understanding is that:

  • SVGs offer far greater functionality if they are directly embedded in a site's HTML code via the <svg> tag than if they are linked to via the <img> tag
    • For example, if the <svg> tag is used, it is possible to dynamically change colors of certain parts of an SVG or even move parts around from JavaScript. Consider this SVG as a possible use case: https://freesvg.org/old-round-clock A site's JS code could rotate the clock's hands to make them show the current time, but only if the clock is embedded with the <svg> tag
  • However, SVGs very frequently have inlined styles. For example, the above clock includes this piece of code:
      <rect
         transform="matrix(0.87719078,0.480142,-0.480142,0.87719078,0,0)"
         ry="1.75"
         y="269.82101"
         x="564.13495"
         height="9.75"
         width="9.75"
         id="rect3049"
         style="fill:url(#radialGradient3051);fill-opacity:1;stroke:none" />

This is precisely what CSP strives to forbid. Therefore, including the above SVG on a CSP protected site breaks this SVG, at least if the SVG is included via the <svg> tag.

There are at least two ways to remedy the problem, unfortunately both are unsatisfactory:

  • Inline styles in SVGs can be exempted from protection in the CSP policy. However, this seems to defeat the point of using CSP. Note that exempting hashes cannot be employed in this case.
    • This would be even more the case if JavaScript in SVGs would have to be exempted as well. And if the above approach was pushed to its logical end then it would make perfect sense to include JS in the clock SVG, for example to let the user manually set time by dragging hands with the mouse pointer.
  • Inline styles can be removed from the SVG and placed in an external stylesheet. Then a the full range of protections offered by CSP could remain enabled.
    • This would be very tedious and would arguably result in code that would be difficult to maintain and follow, since an image would have to be split into multiple files included separately in the website.

Is there any possibility I'm missing? Is it possible to, in a practical way, include SVGs on a webpage with the <svg> tag while still having CSP fully enabled?