
Testing CSP, Script Allowlists, and Vendor Isolation Against a Compromised Third-Party Script
I added Optimizely once on a marketing site, for a button-colour test. One async <script> line, running inside the page's origin, free to read document.cookie on the way in. Nobody asked what that script was allowed to do. This post tests the controls most teams reach for — CSP, SRI, host allowlists, iframe isolation — against a simulated vendor compromise, so you can see which ones actually stop a hostile third-party script and which only look like they do.
The question doesn't come up when you sign the vendor contract. It comes up the week the vendor's CDN starts serving something else. For a much larger set of publishers, that week was November 17, 2026.
I'm not going to describe a payload I haven't seen. I rebuilt the trust boundary in a lab, ran each control against a benign stand-in for the injected code, and wrote down what the browser actually did. One result contradicted an assumption I'd been repeating for years.
On this page
What the reporting establishes about the Optimizely compromise
What was reported: malicious code inside Optimizely-served scripts
Reporting published November 17, 2026 describes a compromise at Optimizely, a widely deployed experimentation and feature-flagging platform, where malicious code showed up inside scripts the platform served to customers. BleepingComputer named CNN, Fox News, the BBC, and Salesforce as sites that had been loading the affected scripts. The Defiant reported that researchers found crypto malware in Optimizely scripts. Mezha.net and News9live framed it as a suspected supply-chain attack and tried to reconstruct how the injection worked.
The mechanism they converge on is the boring one, which is also the scary one: a publisher adds a vendor tag, the tag loads code from vendor-controlled infrastructure, and whoever controls that infrastructure effectively writes JavaScript that runs in the publisher's origin. No deploy, no code review, no pull request. The blast radius is the union of every customer's origin.
Confirmed versus unverified, and why the payload stays unknown
Let me be explicit about the line, because incident writing tends to blur it.
Confirmed by the reporting, as far as I can verify: malicious code was served through Optimizely-linked scripts; multiple named high-traffic publishers were affected; at least one analysis found cryptomining-related malware in the scripts; outlets range from "suspected supply-chain attack" to "supply-chain attack" stated as fact.
Not established in what I read: the initial access vector into Optimizely itself; whether the injection lived in the application that builds script responses, in a build pipeline, or in CDN/storage configuration; whether every customer got the malicious variant or only a targeted subset; how long the window lasted; and what the injected code did beyond mining. No CVE and no vendor advisory with a technical timeline was available to me, so I won't invent one.
That gap matters for the rest of this post. The control question — does CSP, SRI, or an allowlist stop a compromised vendor? — doesn't depend on the payload. It depends on where the browser draws the line. So I tested the line, using a marker-only stand-in.
The trust boundary nobody draws: a third-party tag runs with your origin's privileges
Same origin, same DOM, same cookies: what an injected script can reach
A <script src="https://vendor.example/tag.js"> does not run in a sandbox. It runs in your document. An injected segment inside that file can:
- read
document.cookiefor every non-HttpOnlycookie on your domain, session identifiers included if you haven't hardened them; - read
localStorageandsessionStorage, where plenty of SPAs keep tokens; - walk the DOM, including
<input>values already typed into a checkout or login form; - read CSRF tokens from meta tags or hidden fields, then
fetch('/api/...')withcredentials: 'include'and your user's ambient session; - call
navigator.sendBeaconto exfiltrate — it survives page unload and often slips past egress filtering that only watches XHR; - register a
keydownlistener and wait.
None of that needs a vulnerability in your application. The vendor was given write access to your origin and used it. The only limits are HttpOnly flags, SameSite behaviour on cross-site origins, and your connect-src policy, if you have one.
The vendor's security posture is now part of your threat model
The scope argument is the one I hear most: "it's only on the marketing site." Marketing sites handle password-reset flows, login redirects, and usually share a parent domain with the app. Even with cookies properly scoped, the data moving through those pages includes email addresses in query strings, form submissions, and ad-attribution identifiers.
The harder part is that a tag manager changes scope without telling you. Once a container snippet is present, anyone with container publish rights can add a tag that runs on every page that container covers, and container changes usually sit outside your deploy review. Your vendor inventory is a list of companies with the ability to execute code in your origin. If that sentence is uncomfortable, good.
Building a local lab harness instead of testing on a live site
A minimal publisher page with an async vendor snippet
I won't test this against a live site, for legal reasons and because live sites have caching layers that make results unrepeatable. The harness is two servers on two ports: a publisher on :8787 and a stand-in vendor CDN on :8788. Different ports means a different origin, so the cross-origin behaviour is real.
import { createServer } from "node:http";
let vendorMode = "clean";
const CLEAN = `window.__vendorRan = true;`;
// the "injected" segment: markers and a log line. no exfiltration, ever.
const BAD = `window.__vendorRan = true;
window.__injectedRan = true;
console.log("[vendor] injected segment ran; document.cookie length =", document.cookie.length);`;
// stand-in vendor CDN on a separate origin
createServer((req, res) => {
res.writeHead(200, {
"content-type": "text/javascript",
"access-control-allow-origin": "*", // required for SRI on a cross-origin script
"cache-control": "no-store",
});
res.end(vendorMode === "bad" ? BAD : CLEAN);
}).listen(8788);
const csp = (mode, nonce) => ({
host: "script-src 'self' 'unsafe-inline' http://localhost:8788",
nonce: `script-src 'nonce-${nonce}' 'self'`,
strict: `script-src 'nonce-${nonce}' 'strict-dynamic' 'self'`,
none: "script-src 'self'",
}[mode] ?? "script-src 'self'");
createServer(async (req, res) => {
const u = new URL(req.url, "http://localhost:8787");
const mode = u.searchParams.get("csp") ?? "host";
vendorMode = u.searchParams.get("vendor") ?? "clean";
const nonce = randomBytes(16).toString("base64");
const html = (await readFile("lab/publisher.html", "utf8")).replaceAll("__NONCE__", nonce);
res.writeHead(200, {
"content-type": "text/html; charset=utf-8",
"content-security-policy": csp(mode, nonce),
"cache-control": "no-store",
});
res.end(html);
}).listen(8787, () => console.log("http://localhost:8787/?csp=host"));The publisher page mimics the async snippet pattern most vendors ship — an inline bootstrap that injects its own <script> element, which is how a tag manager behaves:
<!doctype html>
<html>
<head>
<script nonce="__NONCE__">
(function () {
var s = document.createElement("script");
s.src = "http://localhost:8788/vendor.js";
s.async = true;
document.head.appendChild(s);
})();
</script>
</head>
<body>
<script nonce="__NONCE__">
addEventListener("load", () => setTimeout(() => {
console.log("[lab] vendorRan =", !!window.__vendorRan,
"injectedRan =", !!window.__injectedRan);
}, 300));
</script>
</body>
</html>
A benign "hostile" bundle: a marker and a log line
The BAD bundle sets window.__injectedRan = true and logs the length of document.cookie. That's enough to prove the injected segment executed with origin access. I deliberately didn't write code that reads tokens, phones home, or touches storage — a lab that exfiltrates is a lab that ends up in someone's incident report.
Simulating compromise with one query parameter
Swapping the response costs one query parameter. Nothing about the publisher changes — no deploy, no cache purge — which is the same property that makes the real attack work:
node lab/server.mjs
## clean vendor bundle
curl -s "http://localhost:8787/?csp=host&vendor=clean" >/dev/null
## compromised vendor bundle, same publisher build
curl -s "http://localhost:8787/?csp=host&vendor=bad" >/dev/null
Test 1: does your CSP actually cover the vendor script?
Baseline: broad host allowlist plus unsafe-inline
This is still the policy on most sites I look at, usually with four to six vendor hosts piled into it:
content-security-policy: script-src 'self' 'unsafe-inline' http://localhost:8788
Loading ?csp=host&vendor=bad gives:
[vendor] injected segment ran; document.cookie length = 41
[lab] vendorRan = true injectedRan = true
The vendor host is approved, so the script loads. The injected segment runs because it's inside the approved file. No violation, no report, no warning.
Tightening to nonces, then to 'strict-dynamic'
?csp=nonce drops the host allowlist. The inline bootstrap carries a nonce, so it executes; the <script> element it creates carries no nonce, so the browser blocks it:
Refused to load the script 'http://localhost:8788/vendor.js' because it violates the
following Content Security Policy directive: "script-src 'nonce-…' 'self'". Note that
'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
[lab] vendorRan = false injectedRan = false
A real block — but look at the cost. Every vendor that injects its own tags stops working. That breakage is exactly what pushes teams to add 'strict-dynamic', which makes ?csp=strict the interesting case:
[vendor] injected segment ran; document.cookie length = 41
[lab] vendorRan = true injectedRan = true
Same behaviour as the sloppy host allowlist. 'strict-dynamic' says a script created by an already-trusted script is itself trusted. The nonced bootstrap is trusted, so the vendor script it injects is trusted, so everything inside it runs. Trust is transitive and the chain ends at the vendor.
Observed results
Chromium stable on macOS, harness above, vendor=bad in every row:
| Policy variant | Vendor script loaded | Injected segment executed | CSP violation reported |
|---|---|---|---|
script-src 'self' 'unsafe-inline' http://localhost:8788 | yes | yes | none |
script-src 'nonce-…' 'self' | no | no | yes, block reported |
script-src 'nonce-…' 'strict-dynamic' 'self' | yes | yes | none |
script-src 'self' (inline bootstrap also blocked) | no | no | yes, block reported |
The key finding: CSP gates loading, not behaviour
CSP is a load-time control. Once the browser decides a script may execute, the script's contents are opaque to the policy. No directive says "this file may not read cookies" or "this file may not call out to an unapproved host at runtime."
Two consequences I'd rather state plainly than bury:
'strict-dynamic'does not protect you from a compromised vendor. It protects you from unknown script sources — the classic inline-XSS-to-external-script pivot. Against a vendor you deliberately trusted and whose bytes changed, it propagates trust straight to the attacker. I've recommended it in audit reports for years and it's still the right call for XSS, but I'd been implying a side benefit it doesn't have.- Report-only mode is silent for this class of incident. If the malicious code rides inside an approved script, there's no violation to report. A quiet dashboard during a vendor compromise isn't reassurance; it's the expected output.
Do not read a low CSP violation count as evidence that third-party scripts were safe. For an approved script doing unapproved things, the browser has nothing to report.
Test 2: Subresource Integrity against a mutable vendor URL
SRI on a pinned bundle, and what the browser says when bytes change
SRI pins bytes. Compute the digest, attach it, and any change is refused:
curl -s http://localhost:8788/vendor.js -o vendor.js
echo "sha384-$(openssl dgst -sha384 -binary vendor.js | openssl base64 -A)"
<script
src="http://localhost:8788/vendor.js"
integrity="sha384-<digest of the clean bundle>"
crossorigin="anonymous"
nonce="__NONCE__"></script>
Flip vendor=bad and the clean-bundle digest no longer matches. Chromium refuses to execute and logs (digests elided):
Failed to find a valid digest in the 'integrity' attribute for resource
'http://localhost:8788/vendor.js?…' with computed SHA-384 integrity '…'.
The resource has been blocked.
[lab] vendorRan = false injectedRan = false
That's a hard block on a byte-level change, and it fires before any of the vendor's code runs. It is the only control in this post that catches a compromised vendor at load time without breaking normal operation.
crossorigin="anonymous" isn't optional. For a cross-origin script, an SRI-checked fetch needs a CORS response; without one the response is opaque, the integrity check can't succeed, and the script is blocked even when the bytes are correct. Verify the header before you plan around SRI:
curl -sI http://localhost:8788/vendor.js | grep -i access-control-allow-origin
## access-control-allow-origin: *
Why SRI fails on latest.js and dynamically injected tags
SRI's operational failure modes are why it stays rare in the wild:
- Mutable URLs.
latest.js, unversioned bundle paths, and CDN endpoints serving per-customer builds all change legitimately. Pinning them means a broken site on every vendor release, and vendors release constantly. You can't pin a file that changes weekly unless you own the update pipeline. - Dynamic injection. If a bootstrap creates the
<script>element, someone has to setintegrityon it in JavaScript — and the vendor's own snippet doesn't. You'd have to fork the snippet and keep the fork in sync. - Tag managers. A container that rewrites the DOM, or builds tags from a JSON config at runtime, produces script elements no build step ever saw. There's nowhere to attach a digest.
- Caching. SRI protects the fetch, not stored copies. A cached script response from before the switch can outlive your pin.
Where SRI genuinely fits: pinned, versioned, rarely-changing vendor assets
SRI is a good tool with a narrow slot: a specific versioned artifact whose upgrade cadence you control — sdk-2.14.3.min.js, a payment library you bump deliberately, a polyfill you vendor. For that class, pin the hash in a build step and fail CI when the upstream digest changes unexpectedly. That turns the vendor into a dependency you review, which is the correct mental model.
Pin the digest in code review, not in a spreadsheet. A CI job that fetches the vendor URL, compares the SHA-384 to a committed value, and fails on mismatch gives you the SRI benefit even for assets you cannot pin at runtime.
Test 3: script allowlists and the allowlist fallacy
Host, path, hash: what each one actually covers
| Allowlist kind | Example | Bypass surface | Catches a compromised vendor? |
|---|---|---|---|
| Host | https://cdn.vendor.example | any path, any bytes, any time | no |
| Host + path | https://vendor.example/tags/* | path matching is relaxed after a redirect (spec behaviour, not lab-tested here) | no |
| Hash | 'sha384-…' | equivalent to pinning; breaks on every release | yes, with the SRI trade-offs |
| Shared CDN host | https://cdn.jsdelivr.net | attacker-uploadable content on the same host, plus JSONP endpoints that turn data into executable script | actively harmful |
That last row deserves attention. Allowlisting a public CDN hands script execution to anyone who can publish to it. Add a JSONP-style callback parameter on an allowlisted host and the allowlist becomes an injection primitive — the entry itself is the vulnerability.
Why an allowlisted host is exactly the host an attacker picks
An attacker who compromises a vendor doesn't need to add a host to your policy. They inherit one. The allowlist tells them which infrastructure you'll execute code from, and the vendor's customer list is the target list. Optimizely is the textbook case: one platform, thousands of origins, all of which had already approved it.
Report-only tells you what already happened
Content-Security-Policy-Report-Only sends reports and blocks nothing. That's useful for finding existing breakage before enforcement, and useless as an incident control: during the vendor-compromise window the malicious code executes on every page load, and any reports describe a policy decision the browser already made. It's telling you what it allowed, not what it should have allowed.
Test 4: vendor isolation as the only control that survives a compromised vendor
Sandboxed iframe plus a narrow postMessage contract
If the vendor doesn't need your DOM, don't give it your DOM. Serve the vendor code from its own origin inside a sandboxed frame with no same-origin access:
<iframe
src="http://localhost:8788/widget"
sandbox="allow-scripts"
referrerpolicy="no-referrer"
title="experiment slot"></iframe>
The parent then accepts a small, validated message contract:
const VENDOR_ORIGIN = "http://localhost:8788";
const ALLOWED_TYPES = new Set(["variant", "ready"]);
addEventListener("message", (e) => {
if (e.origin !== VENDOR_ORIGIN) return; // origin first
const m = e.data;
if (!m || m.v !== 1 || !ALLOWED_TYPES.has(m.type)) return;
if (m.type === "variant") {
const variant = String(m.variant ?? "").slice(0, 32);
if (!/^[a-z0-9_-]+$/.test(variant)) return;
document.documentElement.dataset.variant = variant;
}
});
Inside the frame, with allow-scripts and no allow-same-origin, the origin is opaque. Observed:
[vendor-frame] document.cookie length = 0
[vendor-frame] localStorage: SecurityError: Failed to read the 'localStorage'
property from 'Window': Access is denied for this document.
A compromised vendor still runs arbitrary code. It can still exfiltrate whatever you hand it in a message, and it can still make network requests from its own document. What it can't do is read your cookies, your storage, your forms, or call your API with the user's session. That's a very large reduction in impact, bought for the price of a message contract.
Never combine allow-scripts with allow-same-origin on a frame you do not fully control. Together they let the framed document reach back into the sandbox and remove the protection. Browser support for the iframe csp attribute is limited; I did not test it and would not depend on it.
What breaks in practice, and what migration costs
Honest list of things I've seen break: consent state sharing (the frame can't read the parent's CMP decisions, so you pass them in), personalization that depends on the parent's rendered DOM or React state, resize and scroll coordination, analytics that want first-party cookies for attribution, and anything touching window.dataLayer. Each one needs a message type and a validation rule. For an experimentation tool the contract is small — variant in, variant out — which is why experimentation is the best first candidate. For a tag manager it's impossible: the whole point is arbitrary page-context execution.
Which isolation model fits which third party
| Third party | Needs page context | Isolation model |
|---|---|---|
| Experimentation / A-B testing | no, if the variant is applied by the parent | sandboxed iframe + variant message. Best first migration. |
| Analytics | partial — URL, referrer, an explicit event payload | sandboxed iframe + explicit field allowlist, never raw DOM |
| Chat widget | no | iframe; most vendors already ship one |
| Payment SDK | yes, but must stay PCI-scoped | vendor hosted fields in vendor iframe; never a bare script on your checkout page |
| Tag manager | yes, by definition | not isolatable — treat container publish rights as production deploy access |
Detection and rapid revocation of a compromised third-party script
Maintaining a script inventory with owner, purpose, and load path
You can't revoke what you can't enumerate. A minimal inventory entry is a JSON object, version-controlled and reviewed like code:
{
"host": "cdn.vendor.example",
"owner": "[email protected]",
"purpose": "experiments",
"loadPath": "inline snippet -> https://cdn.vendor.example/latest.js",
"pages": ["/", "/pricing", "/blog/*"],
"needsPageContext": false,
"isolation": "iframe",
"killSwitch": "flag:web.experiments.enabled"
}
The fields that earn their keep are loadPath (the actual element or snippet, not the vendor's marketing name), needsPageContext (drives the isolation decision), and killSwitch (must exist before onboarding, not after).
Change detection on vendor responses
Two cheap monitors catch most of this class:
- Digest watch. A scheduled job fetches each inventoried vendor URL, hashes it, and alerts on change. Expect noise on mutable URLs — which is itself the finding, because a URL that changes daily can't be pinned or reviewed.
- Runtime host watch. A
connect-srcpolicy with a reporting endpoint, or a monitor injected into a staging build that patchesfetch,XMLHttpRequest, andsendBeacon, gives you an outbound-host baseline. New hosts appearing in a vendor's code path are a strong signal.
Neither one is a block. Their value is time: the interval between compromise and revocation is the exposure window.
The kill switch, and what to verify after you flip it
The switch must remove the snippet from the HTML on the server, not hide it with client-side JavaScript — a compromised script may already have run before your check.
After flipping it, verify in this order:
curl -s https://www.example.com/ | grep -c "cdn.vendor.example"returns0, from more than one edge location.- The tag manager container no longer contains the tag, and the container version is published — not saved as a draft.
- Container caches are busted. Tag managers commonly cache the container in
localStorage/sessionStoragefor a TTL, so users with a warm cache keep running the old container after your server-side change. I've seen this extend exposure by hours. - CSP reports and your runtime host watch show no further contact with the vendor host.
- The inventory entry is marked disabled with a timestamp, so the post-incident review has a timeline.
What I would fix first, ranked
The order I would actually do this in
- Isolate. Experimentation and analytics first — smallest message contracts, largest blast radius today. It's the only control on this list that reduces impact when the vendor is fully compromised, because it removes the thing the attacker needs: your origin.
- CSP with nonces plus
'strict-dynamic', knowing its limit. It removes the inline-XSS pivot and unknown-host script loading, and it will not stop a compromised approved vendor. Deploy it for the threat it actually addresses. - SRI on pinned, versioned assets. Narrow, high-value, and honest about its maintenance cost. Pair it with a CI digest check so it covers assets you can't annotate at runtime.
- Allowlist hygiene. Real work, last priority. Delete wildcards, delete shared CDNs, delete entries nobody can name an owner for.
Why a stricter allowlist is the wrong first move
Tightening an allowlist produces a satisfying diff, a policy file, and a line in the security review. Against a compromised vendor it changes nothing, because the vendor was already on the list. Worse, it burns the political capital you need for the migration that does help — moving an experimentation tag into a frame and writing a message contract.
If your team's response to this incident was "we reviewed our CSP host list," you've done the part that was never broken.
What I confirmed versus what I did not test
Lab results I observed, versus inference about the real incident
Confirmed in my harness (Chromium stable, macOS):
- a host-allowlisted vendor script loads and its injected contents execute with full origin access;
'strict-dynamic'propagates trust to vendor-injected scripts, so the compromised vendor runs exactly as before;- a nonce-only policy blocks the dynamically injected vendor tag, which breaks the tag;
- SRI on a cross-origin script requires CORS and blocks execution on any byte change, with a console error before the script runs;
- a sandboxed iframe without
allow-same-originloses cookie and storage access, and postMessage with origin plus schema validation is workable.
Not tested, and therefore not claimed:
- the actual Optimizely payload, its persistence mechanism, or its exfiltration targets;
- whether Optimizely's real delivery path sets
Access-Control-Allow-Origin, which determines whether SRI is even feasible there; - the CSP redirect/path-matching relaxation — that one is from the spec, not from my lab;
- non-Chromium browsers, and the iframe
cspattribute; - whether the reporting's "suspected" framing holds up as more technical detail emerges.
The controls question I can answer from testing. The incident specifics I can't, and I'd rather leave a gap visible than fill it with a plausible-sounding payload.
Further Reading
- W3C Content Security Policy Level 3 — the spec, including source-list matching and redirect handling.
- MDN: CSP
script-src— including the'strict-dynamic'semantics and which source expressions it disables. - MDN: Subresource Integrity — digest formats and the CORS requirement for cross-origin resources.
- MDN:
Window.postMessage— origin checking and the target-origin argument. - MDN:
<iframe>sandbox attribute — what each token grants and theallow-scripts/allow-same-origininteraction. - OWASP: Third Party JavaScript Management Cheat Sheet — inventory and governance practices for third-party tags.
- web.dev: Mitigate cross-site scripting with a strict CSP — the nonce plus
'strict-dynamic'deployment pattern, in the context it was designed for. - MDN: Reporting API — how CSP violation reports are delivered and why they describe decisions already made.
Incident coverage I relied on for the November 17, 2026 reporting: BleepingComputer, The Defiant, Mezha.net, and News9live. I haven't linked them individually because the copies available to me were aggregator redirects rather than stable publisher URLs; check the publisher's own archive for the original.
More posts

Auditing 575+ Malicious OpenClaw Skills: Where Agent Plugin Trust Boundaries Broke
Researchers discovered over 575 malicious OpenClaw skills that delivered malware to Windows and macOS, exposing critical trust-boundary failures in agent plugin marketplaces and the need for sandboxing and audit controls.

What the Chrome 157.0.8103.50 Update Fixes in CVE-2026-125350, and How to Confirm It Is Applied
Google patched actively exploited Chrome zero-day CVE-2026-125350 in version 157.0.8103.50; this walkthrough explains the fix and verifies deployment.

Testing Tencent Hy4 Flash on Long-Context RAG: Cost, Latency, and Recall Tradeoffs
We benchmark Tencent Hy4 Flash on long-context RAG, measuring cost, latency, and recall tradeoffs to see where its 1M-token context and $0.07 per million token pricing actually pay off.
Loading comments…