SecurityPolicyViolation events can cause errors when loading textures

The CSP error handler for the LoadImage in fileTools.ts is not specific enough, and unrelated CSP violation errors can cause image/texture loading to fail.

The SecurityPolicyViolationEvent.blockedURI field should be checked to see if it matches the url being loaded.

I don’t have a simplified demo case right now, since it requires setting up a custom CSP and the timing can be a bit finicky, but I have seen this be an issue when my CSP blocked https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png (used in the debugger) while a texture was also trying to load.

I am not sure to understand, it looks like all we do is hook into the CSPViolation event to surface it to the user without ending up in an infinite loop trying to load the fallback.

What would checking blockedURI provide ? we would still need to bubble the error up and prevent the fallback load ?

cc @carolhmj

The blockedURI indicates which URL violated the CSP. In my case, I am trying to load a texture (exact URL not relevant, but it’s being tested on a localhost URL), and the error that is given in the CSPV event has blockedURL="https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png", which does not correspond to the texture that was being loaded.

I can try to set up a test case for this later if you like, but in short, I believe that adding something along the lines of if (err.blockedURL !== img.src) { return; } in between lines 256 and 257 in the referenced code would (mostly) fix the issue of the SCPV event not being specific to the image being loaded (the event is attached to document).

Demo: Babylon.js Playground

This demo shows two textures which load images, one which violates CSP, one which doesn’t. Both images textures load due to a single CSP violation. If the second texture load is omitted, the first texture will load successfully.

In console, both error handlers show the same URL, which is incorrect:

error1 Error: CSP violation of policy connect-src https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png. Current policy is default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://playground.babylonjs.com
    at HTMLDocument.handler (fileTools.ts:225:30)
VM357:28 error2 Error: CSP violation of policy connect-src https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png. Current policy is default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://playground.babylonjs.com
    at HTMLDocument.handler (fileTools.ts:225:30)

Would you like to submit a PR for it? No worries if not :blush:

Sure: Add URL filter to the securitypolicyviolation event handler by kv-bh · Pull Request #13570 · BabylonJS/Babylon.js · GitHub

3 Likes

@kvbh thanks a lot for the explanation and the PR !!! it totally makes sense

1 Like