How Subresource Integrity Verifies External JavaScript
Subresource Integrity (SRI) is a web security standard that enables browsers to verify that external files, such as JavaScript libraries delivered via Content Delivery Networks (CDNs), are delivered without unexpected manipulation. By comparing a cryptographic hash defined in your HTML with the hash of the fetched file, SRI ensures that your web application only executes trusted, unmodified code, mitigating the risks of supply-chain attacks and compromised third-party servers.
The Core Mechanism of Subresource Integrity
SRI relies on cryptographic hashing algorithms (typically SHA-256, SHA-384, or SHA-512) to validate the authenticity and integrity of fetched files. The verification process follows a strict step-by-step workflow between your web page, the external host, and the client’s browser:
1. Generating the Cryptographic Hash
Before deploying the code, the developer computes a cryptographic
hash of the exact JavaScript file to be hosted externally. This hash is
encoded in base64 format and prefixed with the algorithm used (for
example, sha384-).
2. Declaring the Integrity Attribute
The generated hash string is placed inside the integrity
attribute of the <script> tag in the HTML document.
Alongside it, the crossorigin="anonymous" (or
use-credentials) attribute is required to enforce
Cross-Origin Resource Sharing (CORS) validation.
<script
src="https://cdn.example.com/library.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous">
</script>3. Fetching and Comparing on the Client Side
When a user loads the page: * Download: The browser
fetches the external JavaScript file from the specified URL. *
Calculation: Before executing the script, the browser
calculates its own cryptographic hash of the downloaded content using
the algorithm specified in the integrity attribute. *
Validation: The browser compares its generated hash to
the hash provided in the HTML.
4. Execution or Blocking
- Match: If the calculated hash exactly matches the
hash in the
integrityattribute, the resource is verified, and the browser executes the JavaScript. - Mismatch: If the hashes do not match—indicating the file was modified, corrupted, or tampered with—the browser refuses to execute the script and logs a network error in the developer console.
Why SRI Verification is Critical
- CDN Compromise Defense: If a third-party CDN is hacked and malicious code is injected into a hosted script, SRI blocks the script because its hash changes.
- Protection Against Man-in-the-Middle (MitM) Attacks: Even if transport security is bypassed or a proxy alters the script payload in transit, the browser detects the discrepancy and halts execution.
- Supply Chain Security: SRI guarantees that your application runs the exact version of the library you tested and approved during development, preventing silent updates or unauthorized changes.