🌐 Chapter 67: CORS & Cross-Origin Embedding

Tainted Canvas & Media with CORS Security Boundaries

**Part 14: Security & Best Practices** — Chapter 67: Cross-Origin Resource Sharing (CORS) & Embedding

LEARNING OBJECTIVES
  • Understand why loading cross-origin images without CORS marks an HTML <canvas> as "Tainted".
  • Resolve DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
  • Configure img.crossOrigin = 'anonymous' and server-side Access-Control-Allow-Origin: * headers.
  • Read pixel data safely via ctx.getImageData() from external CDNs.
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

📖 The Tainted Canvas Defense

If an attacker could draw an image from your private intranet (or banking dashboard) onto a <canvas> and read back the raw RGB pixel data with ctx.getImageData() or canvas.toDataURL(), they could exfiltrate private user charts and financial statements.

To prevent this, browsers lock down any canvas that draws an image loaded without CORS:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();

// Fix: Request image with CORS mode enabled
img.crossOrigin = 'anonymous';
img.src = 'https://cdn.example.com/chart.png';

img.onload = () => {
  ctx.drawImage(img, 0, 0);
  // Now safe to export pixel data!
  const base64 = canvas.toDataURL('image/png');
};

📌 Key Takeaways

  • Drawing a non-CORS cross-origin image taints the canvas, permanently disabling toDataURL(), toBlob(), and getImageData().
  • Set crossOrigin = "anonymous" on image elements and ensure the CDN responds with Access-Control-Allow-Origin: *.
  • --

❓ Knowledge Check

1. Which of the following is correct?

2. Which of the following is correct?