Subresource Integrity (SRI)

Learn how Subresource Integrity can be used to add security to the Content Delivery Network layer.

Content Delivery Networks (CDNs)

A content delivery network (CDN) is a group of edge servers spread out across many different locations around the world. An edge server is just a traditional server that is as geographically near to the respective end-user as possible. When a user fetches a resource (like a JavaScript file) from a CDN for the first time, if the resource is not available at the edge server, the edge server will check the origin server, cache the resource, and then return it. Subsequent requests won’t have to travel to the origin server since the resource will be cached at the CDN layer. Duplicate copies of data are stored across the edge servers so that the server closest to the user can fulfill the request.

A CDN server is often not one that is directly managed by the application developers themselves. When using a third-party service for important tasks like resource delivery, we have to do everything we can to ensure that it is secure. Subresource Integrity (SRI) is a modern browser security feature that ensures static resources, requested from a CDN for example, are an exact match with our predefined expectations.

For each resource requested, we provide a cryptographic hash that is equal to the base64-encoded cryptographic hash of the contents of the expected resource or file. If the hash of the contents of the fetched resource doesn't match the known, expected hash, we know that the contents of the file are different from what we were expecting and the browser prevents it from loading.

Note: Using HTTPS may seem like it already solves the problem that SRI attempts to solve. The key difference is that HTTPS protects data in-transit from being tampered with, while SRI ensures that the resources received from the host server itself are expected.

The integrity attribute

Let’s take a look at how we can use SRI when requesting a JavaScript file from a CDN:

  • The minified, production bundle of react@16.8.5 can be found at https://unpkg.com/react@16.8.5/umd/react.production.min.js.

  • We can use an online SRI hash generator to produce the following SHA-384 hash for it: sha384-dOCiLz3nZfHiJj//EWxjwSKSC6Z1IJtyIEK/b/xlHVNdVLXDYSesoxiZb94bbuGE.

Note: SRI hashes are usually not manually computed like this unless the file almost never changes. For files with more dynamic content, we can automate hash generation using module bundlers like webpack.

  • Next, we can add this hash to our script tag via an integrity attribute.

Get hands-on with 1200+ tech skills courses.