Handling load error within subresource integrity check
Asked Answered
F

3

8

I'm implementing subresource integrity checks. I'd like to implement a fallback such that 1) the browsers loads from my CDN, performs the integrity check and carries on or 2) in the event of failing the integrity check, an embedded script launches and retrieves the needed script from my application server (resource under my control).

I have a simple javascript which catches window.onerror events, but the script is actually detecting an uncaught ReferenceError (my page references a script within the external resource), and not the browser error "Failed to find a valid digest...".

Has anyone found a way to detect the integrity check has failed, and then use javascript to pull the third-party hosted resource from a more trusted location?

Floe answered 3/11, 2016 at 18:18 Comment(0)
K
4

Take a look at this implementation of SRI-fallback:

https://github.com/cyph/sri-fallback

Kudos answered 21/11, 2016 at 20:4 Comment(0)
A
2

You can check if the loaded resource is present and load a fallback local copy:

<script src="https://code.jquery.com/jquery-1.12.0.min.js" integrity="sha256-Xxq2X+KtazgaGuA2cWR1v3jJsuMJUozyIXDB3e793L8=" crossorigin="anonymous"></script>
<script>
if (!window.jQuery) {
                var script = document.createElement('script');
                script.src = '/local-resources/js/jquery-1.12.0.min.js';
                script.async = false;
                document.head.appendChild(script);
            }
</script>
Africa answered 6/12, 2016 at 16:5 Comment(0)
R
2

you have to catch the error and do whatever is necessary.

  • Create and attach a MutationObserver
  • add a callback
  • catch the error and act accordingly

Look in both examples below. Borrow whatever is useful. Send a big thank you to the authors ;-)

Here you could find an example https://github.com/cyph/sri-fallback/blob/master/sri-fallback.js

Another very good reading is available here https://aldaris.github.io/dev/security/2018/03/05/subresource-integrity.html

PS: window.onerror is not probably the best approach for you might end up with more errors than expected and to tungle up into many conditions...

Remanence answered 11/1, 2019 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.