sveltejs / svelte

web development for the rest of us
https://svelte.dev
MIT License
79.9k stars 4.25k forks source link

SvelteKit generates inline event handlers for `img` tag causing CSP inline execution issues #14014

Open duydang2311 opened 2 weeks ago

duydang2311 commented 2 weeks ago

Describe the bug

Wrapping an img as a Svelte component results in onload="this.__e=event" onerror="this.__e=event" generated in HTML output. It causes CSP issue related to inline execution.

Below is my csp configuration and the error message.

csp: {
    mode: 'auto',
    directives: {
        'script-src': ['self', 'unsafe-eval']
    }
}

Reproduction

https://github.com/duydang2311/kit-img-csp-reproduction

Logs

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval' 'nonce-94PQ75nivUUiZFr969Zztg=='". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.

System Info

System:
    OS: Windows 11 10.0.22631
    CPU: (8) x64 Intel(R) Core(TM) i3-10100F CPU @ 3.60GHz
    Memory: 2.90 GB / 15.94 GB
  Binaries:
    Node: 22.5.1 - C:\Program Files\nodejs\node.EXE
    npm: 10.8.2 - C:\Program Files\nodejs\npm.CMD
    bun: 1.1.30 - ~\scoop\shims\bun.EXE
  Browsers:
    Edge: Chromium (129.0.2792.89)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    @sveltejs/adapter-auto: ^3.0.0 => 3.3.1
    @sveltejs/kit: ^2.0.0 => 2.7.3
    @sveltejs/vite-plugin-svelte: ^4.0.0 => 4.0.0
    svelte: ^5.0.0 => 5.1.4
    vite: ^5.0.3 => 5.4.10

Severity

annoyance

Additional Information

No response

Rich-Harris commented 2 weeks ago

Possible remediations that spring to mind:

adiguba commented 2 weeks ago

Hello,

Another alternative would be to use unsafe-hashes, since all inserted codes have the same content : this.__e=event

=> This works :

    csp: {
      mode: "auto",
      directives: {
        "script-src": ["self", "unsafe-eval", "unsafe-hashes", "sha256-7dQwUgLau1NFCCGjfn9FsYptB6ZtWxJin6VohGIu20I="],
      },
    },