Catalog My learning Blog
Browser Security Headers: CORS, CSP and Cookies Explained · Phase 5 · Lesson 25 · 6 min read

Subresource Integrity (SRI) for Third-Party Scripts

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: SRI Plus the Layers That Cover Its Gaps
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Apply Subresource Integrity to third-party scripts and stylesheets, explain exactly which threats it addresses and which it cannot, and combine it with CSP and connect-src to constrain the damage a compromised vendor script can do.

Concept Explanation

Every third-party script a page loads executes with the full privileges of the page's own origin. It can read the DOM, read same-origin storage, read any form field including a credit card number as it is typed, issue authenticated requests, and send anything it finds anywhere the policy permits. A site that embeds a tag manager, an analytics library, a chat widget, and a payment helper has, in security terms, four additional organizations with code execution in its origin, and each of those may in turn load further scripts the site never reviewed.

Subresource Integrity addresses one specific part of that risk: the possibility that the file served at a URL is not the file you reviewed. An integrity attribute on a script or link element carries a base64 cryptographic hash, and the browser computes the hash of the fetched resource and refuses to execute or apply it if the values differ. Multiple hashes may be listed as alternatives for rotation, and stronger algorithms take precedence. Because a cross-origin resource's bytes must be readable to be hashed, SRI requires the crossorigin attribute and therefore CORS headers on the resource.

It is crucial to be precise about the threat model. SRI protects against a CDN being compromised, a DNS hijack, a man-in-the-middle substitution, and an account takeover at the hosting provider, because in every one of those cases the delivered bytes differ from the reviewed bytes. It does not protect against a vendor deliberately or accidentally shipping malicious code in a new version, because you will pin that version's hash yourself once you adopt it. It also cannot protect a resource that is intentionally dynamic, which is why tag managers and personalized script endpoints, precisely the highest-risk category, are the ones SRI cannot cover.

That gap is why SRI belongs in a layered configuration rather than standing alone. CSP with strict-dynamic constrains what a trusted script may load onward. connect-src constrains where any script may send data, which is the single most valuable limit on a compromised vendor script, since exfiltration requires a destination. A strict Permissions-Policy denies APIs no third party should reach. And for payment pages specifically, the strongest architecture is to keep the third party out of the origin entirely by putting card entry in a cross-origin iframe, so the embedding page cannot read those fields even if it is fully compromised.

Operationally, generate the hash from the exact file you reviewed, pin exact versions rather than floating tags, and treat a dependency's subresource list as part of your inventory. Where a vendor requires a dynamic endpoint that cannot be hashed, that is a risk decision to make explicitly: document it, restrict it with connect-src, monitor CSP violation reports for unexpected destinations, and periodically review whether the integration is still needed at all.

ThreatSRI helps?What else is needed
CDN compromised and serving altered bytesYesNothing further; this is the core case
DNS hijack or man-in-the-middle substitutionYesHSTS to prevent the plaintext path in the first place
Vendor ships a malicious new versionNoVersion pinning, review on upgrade, and connect-src limits
Dynamic tag manager or personalized scriptNot possible to hashconnect-src, CSP reporting, and vendor review
Compromised script exfiltrating form dataNoconnect-src, and a cross-origin iframe for card entry

Worked Example: SRI Plus the Layers That Cover Its Gaps

The markup and headers below show the complete shape: an integrity-pinned vendor script, and the policy that limits what any script can do with what it collects even if SRI does not apply.

Code
<!-- Generate the hash from the exact reviewed file:
     openssl dgst -sha384 -binary lib.js | openssl base64 -A  -->
<script src="https://cdn.example.com/lib-4.2.1.js"
        integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
        crossorigin="anonymous"></script>
<!-- crossorigin is REQUIRED: the bytes must be readable to be hashed,
     so the CDN must send Access-Control-Allow-Origin. -->

<!-- Multiple hashes allow rotation across a version bump -->
<script src="https://cdn.example.com/lib.js"
        integrity="sha384-oqVuAfXRKap7... sha384-Rk3Fa0tTv9uV..."
        crossorigin="anonymous"></script>

# The layer SRI cannot provide: limiting where data can go.
# A compromised or dynamic script must have a destination to exfiltrate to.
Content-Security-Policy:
  script-src 'nonce-{PER_RESPONSE}' 'strict-dynamic';
  connect-src 'self' https://api.example.com;
  form-action 'self';
  object-src 'none'; base-uri 'none'; frame-ancestors 'none';
  require-trusted-types-for 'script';
  report-to csp-endpoint

Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()

<!-- Strongest for card entry: the third party never enters your origin. -->
<iframe src="https://payments.vendor.example/card-field" allow="payment"></iframe>
A third-party script reaching a page through a CDN, with SRI rejecting altered bytes at load time and connect-src blocking the exfiltration destination for the case SRI cannot cover.
A third-party script reaching a page through a CDN, with SRI rejecting altered bytes at load time and connect-src blocking the exfiltration destination for the case SRI cannot cover.

Real-World Examples

  • In February 2018, the Browsealoud accessibility script from Texthelp was compromised and altered to include a Coinhive cryptocurrency miner, which then executed on more than four thousand websites that embedded it, including the UK Information Commissioner's Office and multiple government sites; commentary at the time noted that Subresource Integrity on the script tag would have caused browsers to refuse the altered file outright, and the incident became the standard argument for pinning third-party script hashes.
  • The Magecart attack against British Airways in 2018 injected a skimmer into a script on the airline's payment flow, capturing card details from roughly 380,000 transactions and resulting in a 20 million pound fine from the UK Information Commissioner's Office; the exfiltration required the script to send captured data to an attacker-controlled domain, which is precisely the step a strict connect-src directive is designed to block.
Key TakeawaysSRI guarantees the bytes are the ones you reviewed; it does not guarantee the code is safe. Pair it with a strict connect-src, since a compromised or dynamic third-party script must have somewhere to send what it captures, and keep payment card entry in a cross-origin iframe so the third party never has access to those fields at all.

Review Questions & Answers

Because the browser must read the resource's bytes to compute their hash, and a normal no-cors cross-origin load produces an opaque response whose contents are inaccessible. Adding crossorigin makes it a CORS request, so the CDN must send an Access-Control-Allow-Origin header permitting the page, after which the browser can read the bytes, hash them, and compare against the integrity attribute.

It does not address a vendor shipping malicious or vulnerable code in a version you deliberately adopt, since you will compute and pin that version's hash yourself. It also cannot cover intentionally dynamic resources such as tag managers and personalized script endpoints, because their content changes by design and has no stable hash. The gap is significant precisely because those dynamic integrations are usually the highest-risk third parties on the page.

Because capturing data is useless to an attacker without a way to send it out. A skimmer can read every form field on the page, but if connect-src permits only your own API origins, the fetch, XHR, WebSocket, or sendBeacon call carrying the stolen data is blocked and generates a violation report. It converts a silent, successful exfiltration into a failed request that also alerts you, which is exactly the outcome the British Airways case lacked.

Because it moves the sensitive fields outside your origin entirely. Script running in your page, including every third-party tag you embed, can read any form field in your own document, so a first-party card form is only as safe as the least trustworthy script on the page. With the fields inside a cross-origin iframe served by the payment provider, the Same-Origin Policy prevents your page, and therefore any compromised script in it, from reading them at all.