The canvas has been tainted by cross-origin data: fixing getImageData
Our avatar cropper threw SecurityError on getImageData for images from our CDN. The img had no crossOrigin attribute, and once we added it the browser reused a cached response without CORS headers. Setting crossOrigin, CORS and Vary: Origin fixed it.
Our profile editor lets users crop and recolour their avatar in the browser before saving. The image is loaded from our CDN on a separate domain, drawn on a canvas, and read back with getImageData for filters and toBlob for upload. After we moved user images from the app domain to cdn.example.com, the editor broke for every user:
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D':
The canvas has been tainted by cross-origin data.
The export step failed with its sibling message:
SecurityError: Failed to execute 'toBlob' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Firefox reported SecurityError: The operation is insecure. for the same calls.
Reproducing it
const img = new Image();
img.src = 'https://cdn.example.com/avatars/u123.jpg';
await img.decode();
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0); // allowed
ctx.getImageData(0, 0, 10, 10); // SecurityError
What we ruled out
Content Security Policy. A CSP block would stop the image loading at all; the image drew fine, which meant it loaded.
Mixed content. Both origins were HTTPS.
Image format. JPEG, PNG and WebP all failed equally.
After we added img.crossOrigin = 'anonymous' and a CORS rule on the bucket, most users were fixed, but some still got the error, and it went away for them after a hard refresh. That part took longest to explain.
Root cause
Two problems stacked up. First, the image was loaded without CORS, so the canvas became tainted the moment we drew it; that is how browsers stop scripts from reading pixels of images from other origins. Second, after we fixed that, browsers and the CDN still held cached copies of the images fetched without CORS headers (from <img> tags elsewhere on the site). The cached response had no Access-Control-Allow-Origin, the CDN did not vary its cache on Origin, and the CORS request was served that cached response, so it failed.
What is happening under the hood
A canvas tracks an origin-clean flag. Drawing an image whose pixels the page is not allowed to read sets the flag to false. After that, every API that reads pixels out of the canvas throws a SecurityError: getImageData, toDataURL, toBlob, captureStream, and WebGL's readPixels or texture uploads.
An image is readable if it is same-origin, or if it was fetched in CORS mode and the response allowed the page's origin. CORS mode is what the crossorigin attribute (or img.crossOrigin in script) turns on:
anonymous: CORS request without cookies. The server must sendAccess-Control-Allow-Originwith*or the page origin.use-credentials: CORS request with cookies. The server must name the exact origin and sendAccess-Control-Allow-Credentials: true.
The attribute must be set before src, or the browser may already have started a non-CORS request.
The cache problem is about shared caches. If a CDN caches a response that has no CORS headers, then serves it to a CORS request, the browser rejects it. The same applies to the browser's own HTTP cache. The standard fix is Vary: Origin on responses whose headers depend on the request origin, or sending the same CORS header on every response so the cached copy is always valid.
Environment
Component | Version / value |
|---|---|
Browsers | Chrome 142, Firefox 145, Safari 26.1 |
CDN | Amazon CloudFront in front of an S3 bucket |
Page origin |
|
Image origin |
|
Editor | Custom canvas cropper, React 19 |
Minimal reproduction
<img src="https://cdn.example.com/avatars/u123.jpg" alt=""> <!-- elsewhere on the page, no CORS -->
<canvas id="c" width="256" height="256"></canvas>
<script type="module">
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = 'https://cdn.example.com/avatars/u123.jpg'; // may be served from the non-CORS cache entry
await img.decode();
const ctx = document.getElementById('c').getContext('2d');
ctx.drawImage(img, 0, 0, 256, 256);
ctx.getImageData(0, 0, 1, 1);
</script>
Who is affected
Image editors, croppers, colour pickers, OCR and face-blur tools, WebGL texture loaders.
Sites serving images from a CDN domain or third-party storage.
Mixed usage: the same image URL used both by plain
<img>tags and by canvas code.
The fix
1. Request the image in CORS mode, attribute first:
const img = new Image();
+img.crossOrigin = 'anonymous';
img.src = url;
await img.decode();
2. Allow the origin on the bucket. S3 CORS configuration:
[
{
"AllowedOrigins": ["https://app.example.com"],
"AllowedMethods": ["GET", "HEAD"],
"AllowedHeaders": ["*"],
"MaxAgeSeconds": 3600
}
]
3. Fix caching at the CDN. S3 only returns CORS headers when the request carries an Origin header, so CloudFront must forward Origin to S3 and include it in the cache key. We attached CloudFront's managed origin request policy that forwards CORS headers and a cache policy that keys on Origin. Then responses for requests with and without Origin are cached separately, and S3 adds Vary: Origin.
For public images there is a simpler variant we now use: a CloudFront response headers policy that always adds Access-Control-Allow-Origin: * to image responses. Every cached copy is then valid for CORS, with or without Origin.
4. Invalidate the old cache. We ran a CloudFront invalidation for /avatars/* so nobody kept receiving the old header-less objects. For browsers' own caches, a one-time version query (?v=2) on the editor's image URL avoided waiting for expiry.
Alternatives and trade-offs
Proxy through the app origin. Serve images from
app.example.com/img/...so they are same-origin. No CORS needed, but you pay for the bandwidth through your app tier.Fetch as a blob.
fetch(url, { mode: 'cors' }), thencreateImageBitmap(await res.blob()). Still needs CORS headers, but makes the request mode explicit and avoids the<img>cache sharing in some setups.Server-side editing. Crop and filter on the server. Removes the browser rule entirely, at the cost of a round trip per change.
How to test the fix
# Without Origin: no CORS header is fine only if Vary or a fixed ACAO is in place
curl -sI https://cdn.example.com/avatars/u123.jpg | grep -iE 'access-control|vary|x-cache'
# With Origin: must allow our app
curl -sI -H 'Origin: https://app.example.com' https://cdn.example.com/avatars/u123.jpg \
| grep -iE 'access-control-allow-origin|vary'
# access-control-allow-origin: https://app.example.com
# vary: Origin
test('editor can read pixels of CDN avatar', async ({ page }) => {
await page.goto('/profile/edit');
await page.getByRole('button', { name: 'Edit photo' }).click();
const ok = await page.evaluate(() => (window as any).cropper.canExport());
expect(ok).toBe(true);
});
Confirming in production
avatar_editor_security_error before: 100% of sessions after invalidation: 0.03%
The remainder came from browser extensions that rewrite image URLs. We now catch the SecurityError and show a "reload the photo" option that re-requests with a cache-busting parameter.
Regression guard
A synthetic check every 15 minutes requests a sample avatar with an
Originheader and fails ifAccess-Control-Allow-Originis missing.Our image helper
loadEditableImage(url)is the only way the editor loads images, and it always setscrossOriginbeforesrc.The infrastructure code for the CDN has a test asserting the response headers policy is attached to the avatar behaviour.
Security implications
The tainted-canvas rule is a real protection: without it, any page could draw your bank's logo or a private image from another site and read its pixels. Do not work around it by proxying arbitrary URLs, which turns your server into an open image fetcher. Allow only your own origins in CORS unless images are truly public. Avoid use-credentials with *, which browsers reject anyway, and never reflect the request Origin back without checking it against an allowlist.
Prevention checklist
Set
crossOriginbeforesrcon any image you will read from a canvas.Configure CORS on the storage bucket and forward
Originthrough the CDN.Make cached responses CORS-safe with
Vary: Originor a fixed allow header.Invalidate CDN caches after changing CORS rules.
Catch
SecurityErrorand offer a recovery path.
References
MDN, Allowing cross-origin use of images and canvas: https://developer.mozilla.org/en-US/docs/Web/HTML/How_to/CORS_enabled_image
MDN, crossorigin attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin
MDN, Cross-Origin Resource Sharing: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
AWS, Using cross-origin resource sharing in Amazon S3: https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html
AWS, Configuring CloudFront to respect CORS settings: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html
Add a label
Embed this post
<iframe src="https://hibug.me/canvas-tainted-getimagedata-securityerror-cors" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I lead a small team responsible for observability and quality tooling, and I spend a fair share of my time on application security reviews. That mix means I see many incidents twice: once when they happen and again when we ask why nothing warned us. The posts here come from that second look. An alert that never fired because the metric disappeared, sampling that dropped exactly the traces we needed, a catch-all that reported success for weeks, a secret recoverable from an image layer, tests that passed against mocks while production failed. Each one covers how the gap was found, what we changed in code or configuration, and how we verified the fix with a test or a drill. Security topics stay defensive and practical: controls you can add to your own code and a way to test each one.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.