Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ export const escapeAttribution = (attribution?: string): string | undefined =>
.replace(/"/g, '"')
.replace(/'/g, ''');

/**
* The crossOrigin setting for tile images.
*
* Tiles usually come from an external server. Without a CORS request they
* taint the map canvas, and exporting a dashboard as PDF fails because the
* canvas can no longer be read.
*/
const TILE_CROSS_ORIGIN = 'anonymous';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: For external services that require cookie authentication, anonymous omits cross-origin credentials; configured WMS and XYZ layers then fail to load even when CORS is enabled.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Api mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset-frontend/plugins/plugin-chart-cartodiagram/src/util/layerUtil.tsx
**Line:** 64:64
**Comment:**
	*Api Mismatch: For external services that require cookie authentication, `anonymous` omits cross-origin credentials; configured WMS and XYZ layers then fail to load even when CORS is enabled.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎


/**
* Create a WMS layer.
*
Expand All @@ -71,6 +80,7 @@ export const createWmsLayer = (wmsLayerConf: WmsLayerConf) => {
VERSION: version,
},
attributions: escapeAttribution(attribution),
crossOrigin: TILE_CROSS_ORIGIN,
}),
});
};
Expand All @@ -88,6 +98,7 @@ export const createXyzLayer = (xyzLayerConf: XyzLayerConf) => {
source: new XyzSource({
url,
attributions: escapeAttribution(attribution),
crossOrigin: TILE_CROSS_ORIGIN,
}),
});
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
* under the License.
*/

import ImageTile from 'ol/ImageTile';
import { get as getProjection } from 'ol/proj';
import { WfsLayerConf, WmsLayerConf, XyzLayerConf } from '../../src/types';
import {
createLayer,
Expand Down Expand Up @@ -60,9 +62,37 @@ describe('layerUtil', () => {
'(c) OSM <img src=x onerror=alert(1)>',
]);
});

test('requests tiles with CORS so the map canvas stays exportable', () => {
const wmsLayerConf: WmsLayerConf = {
title: 'wms',
type: 'WMS',
url: 'https://ows-demo.terrestris.de/geoserver/osm/wms',
version: '1.3.0',
layersParam: 'osm:osm-fuel',
};
const layer = createWmsLayer(wmsLayerConf);
const tile = layer
.getSource()!
.getTile(0, 0, 0, 1, getProjection('EPSG:3857')!) as ImageTile;
expect(tile.getCrossOrigin()).toEqual('anonymous');
});
});

describe('createXyzLayer', () => {
test('requests tiles with CORS so the map canvas stays exportable', () => {
const xyzLayerConf: XyzLayerConf = {
title: 'osm',
type: 'XYZ',
url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
};
const layer = createXyzLayer(xyzLayerConf);
const tile = layer
.getSource()!
.getTile(0, 0, 0, 1, getProjection('EPSG:3857')!) as ImageTile;
expect(tile.getCrossOrigin()).toEqual('anonymous');
});

test('escapes HTML in the layer attribution', () => {
const xyzLayerConf: XyzLayerConf = {
title: 'osm',
Expand Down
54 changes: 54 additions & 0 deletions superset-frontend/src/utils/downloadAsPdf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,60 @@ test('warns the user via the bound toast callback when PDF generation fails', as
);
});

const createCanvases = () => {
const element = document.createElement('div');
const taintedCanvas = document.createElement('canvas');
const cleanCanvas = document.createElement('canvas');
jest.spyOn(taintedCanvas, 'toDataURL').mockImplementation(() => {
throw new DOMException('Tainted canvases may not be exported.');
});
jest.spyOn(cleanCanvas, 'toDataURL').mockReturnValue('data:,');
element.append(taintedCanvas, cleanCanvas);
return { element, taintedCanvas, cleanCanvas };
};

test('excludes tainted canvases from the PDF instead of failing the export', async () => {
const { element, taintedCanvas, cleanCanvas } = createCanvases();
jest.spyOn(document, 'querySelector').mockReturnValue(element);
const domToPdf = jest.requireMock('dom-to-pdf').default as jest.Mock;
let classesDuringExport: { tainted: string; clean: string } | undefined;
domToPdf.mockImplementation(() => {
classesDuringExport = {
tainted: taintedCanvas.className,
clean: cleanCanvas.className,
};
return Promise.resolve();
});

await downloadAsPdf(
'.some-selector',
'test-file',
true,
)({} as SyntheticEvent);

const { excludeClassNames } = domToPdf.mock.calls[0][1];
expect(excludeClassNames).toContain('header-controls');
expect(excludeClassNames).toContain(classesDuringExport?.tainted);
expect(classesDuringExport?.tainted).not.toBe('');
expect(classesDuringExport?.clean).toBe('');
});

test('removes the tainted canvas marker once the export settles', async () => {
const { element, taintedCanvas } = createCanvases();
jest.spyOn(document, 'querySelector').mockReturnValue(element);
const domToPdf = jest.requireMock('dom-to-pdf').default as jest.Mock;
domToPdf.mockRejectedValue(new Error('boom'));

await downloadAsPdf(
'.some-selector',
'test-file',
true,
)({} as SyntheticEvent);

expect(domToPdf).toHaveBeenCalled();
expect(taintedCanvas.className).toBe('');
});

test('forwards both bound toast callbacks to forceLoadAllCharts', async () => {
const element = document.createElement('div');
jest.spyOn(document, 'querySelector').mockReturnValue(element);
Expand Down
39 changes: 38 additions & 1 deletion superset-frontend/src/utils/downloadAsPdf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,38 @@ const PDF_DOWNLOAD_FAILED_MESSAGE = t(
'PDF download failed, please refresh and try again.',
);

const UNEXPORTABLE_CANVAS_CLASS = 'pdf-export-unexportable-canvas';

/**
* check whether a canvas can be read back, which fails with a SecurityError
* once cross-origin content (e.g. external map tiles) has been drawn into it
*
* @param canvas canvas element to check
*/
const isCanvasExportable = (canvas: HTMLCanvasElement) => {
try {
canvas.toDataURL();
return true;
} catch {
return false;
}
};

/**
* mark tainted canvases so dom-to-pdf leaves them out instead of failing the
* whole export when it reads them
*
* @param element element that is about to be printed
* @returns the canvases that were marked
*/
const markUnexportableCanvases = (element: Element) => {
const canvases = Array.from(element.querySelectorAll('canvas')).filter(
canvas => !isCanvasExportable(canvas),
);
canvases.forEach(canvas => canvas.classList.add(UNEXPORTABLE_CANVAS_CLASS));
return canvases;
};

/**
* generate a consistent file stem from a description and date
*
Expand Down Expand Up @@ -79,13 +111,15 @@ export default function downloadAsPdf(
addInfoToast,
);

const unexportableCanvases = markUnexportableCanvases(elementToPrint);

const options = {
margin: 10,
compression: pdfCompressionLevel,
filename: `${generateFileStem(description)}.pdf`,
image: { type: 'jpeg', quality: 1 },
html2canvas: { scale: 2 },
excludeClassNames: ['header-controls'],
excludeClassNames: ['header-controls', UNEXPORTABLE_CANVAS_CLASS],
};
return domToPdf(elementToPrint, options)
.then(() => {
Expand All @@ -96,6 +130,9 @@ export default function downloadAsPdf(
addWarningToast?.(PDF_DOWNLOAD_FAILED_MESSAGE);
})
.finally(() => {
unexportableCanvases.forEach(canvas =>
canvas.classList.remove(UNEXPORTABLE_CANVAS_CLASS),
);
if (didForceLoad) {
restoreVirtualization();
}
Expand Down
Loading