From 02456263e02f82727d93ed85c712dcc4b3dbc4b0 Mon Sep 17 00:00:00 2001 From: Shane Date: Thu, 19 Nov 2026 12:31:02 -0800 Subject: [PATCH] Merge commit from fork --- src/components.d.ts | 4 +- src/components/icon/icon.tsx | 17 +- src/components/icon/readme.md | 26 +- src/components/icon/request.ts | 47 ++- .../icon/test/sanitization/icon.e2e.ts | 271 ++++++++++++++++++ src/components/icon/test/validate.spec.ts | 127 +++++--- src/components/icon/validate.ts | 80 ++++-- src/utils/test/playwright/page/utils/index.ts | 1 + .../test/playwright/page/utils/set-content.ts | 73 +++++ .../playwright/playwright-declarations.ts | 6 + src/utils/test/playwright/playwright-page.ts | 3 +- 11 files changed, 570 insertions(+), 85 deletions(-) create mode 100644 src/utils/test/playwright/page/utils/set-content.ts diff --git a/src/components.d.ts b/src/components.d.ts index c818a522..86456cec 100644 --- a/src/components.d.ts +++ b/src/components.d.ts @@ -42,7 +42,7 @@ export namespace Components { */ "name"?: string; /** - * When set to `false`, SVG content that is HTTP fetched will not be checked if the response SVG content has any ``); + }); + + test('should not run handlers from a utf8 svg data url', async ({ page }) => { + await addIcon(page, 'attack', utf8DataUrl(imageOnErrorSvg('attack'))); + await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false); + await waitForControl(page); + + expect(await getFired(page)).not.toContain('attack'); + await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0); + }); + + test('should render a clean utf8 svg data url', async ({ page }) => { + const clean = ``; + await addIcon(page, 'clean', utf8DataUrl(clean)); + + await expect(page.locator('#clean .icon-inner svg path')).toHaveCount(1); + }); + + test('should warn when an svg is rejected', async ({ page }) => { + const warnings: string[] = []; + page.on('console', (msg) => { + if (msg.type() === 'warning') { + warnings.push(msg.text()); + } + }); + + await addIcon(page, 'attack', utf8DataUrl(imageOnErrorSvg('attack'))); + + await expect.poll(() => warnings.some((warning) => warning.includes('[Ionicons Warning]'))).toBe(true); + }); + + test('should not warn about sanitizing when the response is not an svg', async ({ page }) => { + const warnings: string[] = []; + page.on('console', (msg) => { + if (msg.type() === 'warning') { + warnings.push(msg.text()); + } + }); + await page.route('**/missing.svg', (route) => + route.fulfill({ status: 404, contentType: 'text/html', body: 'Not found' }), + ); + await page.route('**/rejected.svg', (route) => + route.fulfill({ contentType: 'image/svg+xml', body: imageOnErrorSvg('attack') }), + ); + + const missingLoaded = page.waitForResponse('**/missing.svg'); + await addIcon(page, 'missing', '/missing.svg'); + await missingLoaded; + // This takes the same fetch and sanitize steps, so once it warns the 404 has been handled + await addIcon(page, 'rejected', '/rejected.svg'); + await expect.poll(() => warnings.some((warning) => warning.includes('rejected.svg'))).toBe(true); + + expect(warnings.filter((warning) => warning.includes('missing.svg'))).toHaveLength(0); + }); + + test('should not run handlers from a fetched svg while sanitizing it', async ({ page }) => { + await page.route('**/xss/*.svg', (route) => { + const label = route.request().url().includes('control') ? 'control' : 'attack'; + route.fulfill({ + contentType: 'image/svg+xml', + body: `${imageOnErrorSvg(label)}`, + }); + }); + + // Fetches resolve independently, so let the attack load before the control starts + const attackLoaded = page.waitForResponse('**/xss/attack.svg'); + await addIcon(page, 'attack', '/xss/attack.svg'); + await attackLoaded; + await addIcon(page, 'control', '/xss/control.svg', false); + await waitForControl(page); + + expect(await getFired(page)).not.toContain('attack'); + await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0); + }); + + test('should reject a fetched svg with more than one root svg', async ({ page }) => { + await page.route('**/xss/*.svg', (route) => { + const label = route.request().url().includes('control') ? 'control' : 'attack'; + route.fulfill({ + contentType: 'image/svg+xml', + body: `${imageOnErrorSvg(label)}`, + }); + }); + + const attackLoaded = page.waitForResponse('**/xss/attack.svg'); + await addIcon(page, 'attack', '/xss/attack.svg'); + await attackLoaded; + await addIcon(page, 'control', '/xss/control.svg', false); + await waitForControl(page); + + expect(await getFired(page)).not.toContain('attack'); + await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0); + }); + + const htmlInSvgPayloads = [ + { + name: 'noscript', + inner: ``, + }, + { + name: 'template', + inner: ``, + }, + ]; + + htmlInSvgPayloads.forEach(({ name, inner }) => { + test(`should reject an svg containing an html ${name} element`, async ({ page }) => { + const svg = `${inner}`; + await addIcon(page, 'attack', utf8DataUrl(svg)); + await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false); + await waitForControl(page); + + expect(await getFired(page)).not.toContain('attack'); + await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0); + }); + }); + + const foreignObjectPayloads = [ + { + name: 'iframe srcdoc', + inner: ``, + }, + { + name: 'iframe javascript: src', + inner: ``, + }, + ]; + + foreignObjectPayloads.forEach(({ name, inner }) => { + test(`should remove a foreignObject containing an ${name}`, async ({ page }) => { + const svg = `${inner}`; + await addIcon(page, 'attack', utf8DataUrl(svg)); + await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false); + await waitForControl(page); + + expect(await getFired(page)).not.toContain('attack'); + await expect(page.locator('#attack .icon-inner svg path')).toHaveCount(1); + await expect(page.locator('#attack .icon-inner svg > :not(path)')).toHaveCount(0); + }); + }); + + test('should render an illustrator export that uses a switch with a foreignObject', async ({ page }) => { + const svg = ``; + await addIcon(page, 'illustrator', utf8DataUrl(svg)); + + await expect(page.locator('#illustrator .icon-inner svg path')).toHaveCount(1); + }); + + const javascriptUrlPayloads = [ + { name: 'an anchor href', inner: `` }, + { + name: 'an obfuscated xlink:href', + inner: ``, + }, + { + name: 'an animate element', + inner: ``, + }, + { + name: 'a set element', + inner: ``, + }, + ]; + + javascriptUrlPayloads.forEach(({ name, inner }) => { + test(`should reject an svg with a javascript: url in ${name}`, async ({ page }) => { + const svg = `${inner}`; + await addIcon(page, 'attack', utf8DataUrl(svg)); + await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false); + await waitForControl(page); + + await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0); + }); + }); + + test('should not reuse unsanitized content cached for the same data url', async ({ page }) => { + const shared = utf8DataUrl(imageOnErrorSvg('shared')); + + await addIcon(page, 'unsanitized', shared, false); + await page.waitForFunction(() => (window as any).xssFired.includes('shared')); + + await addIcon(page, 'sanitized', shared); + await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false); + await waitForControl(page); + + await expect(page.locator('#sanitized .icon-inner svg')).toHaveCount(0); + expect((await getFired(page)).filter((label) => label === 'shared')).toHaveLength(1); + }); + + test('should not reuse sanitized content cached for the same data url', async ({ page }) => { + const shared = utf8DataUrl(imageOnErrorSvg('shared')); + + await addIcon(page, 'sanitized', shared); + await addIcon(page, 'unsanitized', shared, false); + + await expect(page.locator('#unsanitized .icon-inner svg')).toHaveCount(1); + }); + + test('should not let a src forge the unsanitized cache key', async ({ page }) => { + const shared = utf8DataUrl(imageOnErrorSvg('shared')); + + await addIcon(page, 'unsanitized', shared, false); + await page.waitForFunction(() => (window as any).xssFired.includes('shared')); + + await addIcon(page, 'sanitized', `unsanitized:${shared}`); + await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false); + await waitForControl(page); + + await expect(page.locator('#sanitized .icon-inner svg')).toHaveCount(0); + expect((await getFired(page)).filter((label) => label === 'shared')).toHaveLength(1); + }); + + test('should not reuse an unsanitized in-flight fetch for the same url', async ({ page }) => { + await page.route('**/xss/*.svg', (route) => { + const label = route.request().url().includes('control') ? 'control' : 'shared'; + // Sanitizing drops the sibling and keeps the clean + route.fulfill({ + contentType: 'image/svg+xml', + body: ``, + }); + }); + + await addIcon(page, 'unsanitized', '/xss/shared.svg', false); + await addIcon(page, 'sanitized', '/xss/shared.svg'); + await addIcon(page, 'control', '/xss/control.svg', false); + await waitForControl(page); + await page.waitForFunction(() => (window as any).xssFired.includes('shared')); + + await expect(page.locator('#sanitized .icon-inner svg path')).toHaveCount(1); + await expect(page.locator('#sanitized .icon-inner img')).toHaveCount(0); + expect((await getFired(page)).filter((label) => label === 'shared')).toHaveLength(1); + }); +}); diff --git a/src/components/icon/test/validate.spec.ts b/src/components/icon/test/validate.spec.ts index b71c7f14..0297de7b 100644 --- a/src/components/icon/test/validate.spec.ts +++ b/src/components/icon/test/validate.spec.ts @@ -1,54 +1,65 @@ -import { isEncodedDataUrl, isSvgDataUrl, isValid } from '../validate'; +import { readFileSync, readdirSync } from 'fs'; +import { join } from 'path'; + +import { isEncodedDataUrl, isSvgDataUrl, isValid, validateContent } from '../validate'; + +const SVG_NS = 'http://www.w3.org/2000/svg'; + +const elm = (nodeName: string, attributes: { name: string; value?: string }[] = [], childNodes: any[] = []) => + ({ nodeType: 1, namespaceURI: SVG_NS, nodeName, attributes, childNodes }) as any; describe('isValid', () => { it('invalid onload attr', () => { - const el = { - nodeType: 1, - nodeName: 'svg', - attributes: [{ name: 'onload' }], - childNodes: [], - } as any; - expect(isValid(el)).toBe(false); + expect(isValid(elm('svg', [{ name: 'onload' }]))).toBe(false); }); it('invalid onclick attr', () => { - const el = { - nodeType: 1, - nodeName: 'svg', - attributes: [{ name: 'OnClIcK' }], - childNodes: [], - } as any; - expect(isValid(el)).toBe(false); + expect(isValid(elm('svg', [{ name: 'OnClIcK' }]))).toBe(false); }); it('invalid child SCRIPT elm', () => { - const el = { - nodeType: 1, - nodeName: 'svg', - attributes: [], - childNodes: [{ nodeType: 1, nodeName: 'SCRIPT', attributes: [], childNodes: [] }], - } as any; - expect(isValid(el)).toBe(false); + expect(isValid(elm('svg', [], [elm('SCRIPT')]))).toBe(false); }); it('invalid script elm', () => { - const el = { nodeType: 1, nodeName: 'script', attributes: [], childNodes: [] } as any; - expect(isValid(el)).toBe(false); + expect(isValid(elm('script'))).toBe(false); + }); + + it('invalid foreignObject elm', () => { + expect(isValid(elm('svg', [], [elm('foreignObject')]))).toBe(false); + }); + + it.each(['iframe', 'embed', 'object'])('invalid %s elm', (name) => { + expect(isValid(elm('svg', [], [elm(name)]))).toBe(false); + }); + + it('invalid html namespace elm', () => { + const noscript = { ...elm('noscript'), namespaceURI: 'http://www.w3.org/1999/xhtml' }; + expect(isValid(elm('svg', [], [elm('desc', [], [noscript])]))).toBe(false); + }); + + it('invalid javascript: url', () => { + expect(isValid(elm('a', [{ name: 'href', value: 'javascript:alert(1)' }]))).toBe(false); + }); + + it('invalid obfuscated javascript: url', () => { + expect(isValid(elm('a', [{ name: 'xlink:href', value: ' JaVa\tScRiPt:alert(1)' }]))).toBe(false); + }); + + it('invalid javascript: url in a value list', () => { + expect(isValid(elm('animate', [{ name: 'values', value: 'https://ionic.io;javascript:alert(1)' }]))).toBe(false); }); it('is valid circle elm', () => { - const el = { nodeType: 1, nodeName: 'circle', attributes: [], childNodes: [] } as any; - expect(isValid(el)).toBe(true); + expect(isValid(elm('circle'))).toBe(true); }); it('is valid SVG elm', () => { - const el = { - nodeType: 1, - nodeName: 'SVG', - attributes: [], - childNodes: [{ nodeType: 1, nodeName: 'line', attributes: [], childNodes: [] }], - } as any; - expect(isValid(el)).toBe(true); + expect(isValid(elm('SVG', [], [elm('line')]))).toBe(true); + }); + + it('is valid href', () => { + expect(isValid(elm('a', [{ name: 'href', value: 'https://ionic.io' }]))).toBe(true); }); it('is valid text node', () => { @@ -57,6 +68,56 @@ describe('isValid', () => { }); }); +describe('validateContent', () => { + it('removes foreignObject and keeps the artwork', () => { + const onRejected = jest.fn(); + const result = validateContent( + ``, + onRejected, + ); + expect(result).toContain(' { + const result = validateContent( + ``, + ); + expect(result).toContain(' { + const onRejected = jest.fn(); + expect(validateContent(``, onRejected)).toBe( + '', + ); + expect(onRejected).toHaveBeenCalledTimes(1); + }); + + it('rejects more than one root svg', () => { + const onRejected = jest.fn(); + const svg = ``; + expect(validateContent(svg + svg, onRejected)).toBe(''); + expect(onRejected).toHaveBeenCalledTimes(1); + }); + + it('accepts every shipped icon', () => { + const svgDir = join(__dirname, '../../../svg'); + const rejected = readdirSync(svgDir) + .filter((file) => file.endsWith('.svg')) + .filter((file) => !validateContent(readFileSync(join(svgDir, file), 'utf8'))); + expect(rejected).toEqual([]); + }); + + it('does not call onRejected when there is no svg', () => { + const onRejected = jest.fn(); + expect(validateContent('Not found', onRejected)).toBe(''); + expect(onRejected).not.toHaveBeenCalled(); + }); +}); + it('isSvgDataUrl', () => { expect(isSvgDataUrl('data:image/svg+xml;base64,xxx')).toBe(true); expect(isSvgDataUrl('data:image/svg+xml;utf8,')).toBe(true); diff --git a/src/components/icon/validate.ts b/src/components/icon/validate.ts index 3c73b876..ae851b4b 100644 --- a/src/components/icon/validate.ts +++ b/src/components/icon/validate.ts @@ -1,43 +1,91 @@ import { isStr } from './utils'; -export const validateContent = (svgContent: string) => { - const div = document.createElement('div'); - div.innerHTML = svgContent; +/** + * Calls `onRejected` only when an `` was found and failed validation, + * not when there's no `` at all (like an HTML 404 page). + */ +export const validateContent = (svgContent: string, onRejected?: () => void) => { + /** + * Parse into a template so nothing loads or runs yet. Parsing into a live + * element would fire handlers like `` before validation. + */ + const template = document.createElement('template'); + template.innerHTML = svgContent; + const content = template.content; - // setup this way to ensure it works on our buddy IE - for (let i = div.childNodes.length - 1; i >= 0; i--) { - if (div.childNodes[i].nodeName.toLowerCase() !== 'svg') { - div.removeChild(div.childNodes[i]); + for (let i = content.childNodes.length - 1; i >= 0; i--) { + if (content.childNodes[i].nodeName.toLowerCase() !== 'svg') { + content.removeChild(content.childNodes[i]); } } - // must only have 1 root element - const svgElm = div.firstElementChild; + const svgElm = content.firstElementChild; if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') { const svgClass = svgElm.getAttribute('class') || ''; svgElm.setAttribute('class', (svgClass + ' s-ion-icon').trim()); - // root element must be an svg - // lets double check we've got valid elements - // do not allow scripts - if (isValid(svgElm as any)) { - return div.innerHTML; + /** + * Illustrator exports keep editor data in a `` next to the + * artwork, so remove it instead of rejecting the icon. + */ + removeForeignObjects(svgElm); + + // every root is serialized, so a second would skip validation + if (content.children.length === 1 && isValid(svgElm as any)) { + return template.innerHTML; } + onRejected?.(); } return ''; }; +const removeForeignObjects = (elm: Element) => { + for (let i = elm.children.length - 1; i >= 0; i--) { + const child = elm.children[i]; + if (child.nodeName.toLowerCase() === 'foreignobject') { + child.remove(); + } else { + removeForeignObjects(child); + } + } +}; + +/** + * Elements that can run script or load a document without an `on*` attribute. + */ +const disallowedElements = new Set(['script', 'foreignobject', 'iframe', 'embed', 'object']); + +/** + * Browsers ignore whitespace and control characters in a URL scheme, so strip + * them first. Checking the whole value also catches lists like + * ``. + */ +const hasJavascriptUrl = (value: string) => + value + .replace(/[\u0000-\u0020]/g, '') + .toLowerCase() + .includes('javascript:'); + +const SVG_NS = 'http://www.w3.org/2000/svg'; + export const isValid = (elm: HTMLElement) => { if (elm.nodeType === 1) { - if (elm.nodeName.toLowerCase() === 'script') { + /** + * HTML inside `` or `` (like `<noscript>`) can parse + * differently when it renders than it did here, so only allow SVG elements. + */ + if (elm.namespaceURI !== SVG_NS || disallowedElements.has(elm.nodeName.toLowerCase())) { return false; } for (let i = 0; i < elm.attributes.length; i++) { - const name = elm.attributes[i].name; + const { name, value } = elm.attributes[i]; if (isStr(name) && name.toLowerCase().indexOf('on') === 0) { return false; } + if (isStr(value) && hasJavascriptUrl(value)) { + return false; + } } for (let i = 0; i < elm.childNodes.length; i++) { diff --git a/src/utils/test/playwright/page/utils/index.ts b/src/utils/test/playwright/page/utils/index.ts index 8e7bfcaf..a2ff94be 100644 --- a/src/utils/test/playwright/page/utils/index.ts +++ b/src/utils/test/playwright/page/utils/index.ts @@ -1 +1,2 @@ export * from './goto'; +export * from './set-content'; diff --git a/src/utils/test/playwright/page/utils/set-content.ts b/src/utils/test/playwright/page/utils/set-content.ts new file mode 100644 index 00000000..ee6c731a --- /dev/null +++ b/src/utils/test/playwright/page/utils/set-content.ts @@ -0,0 +1,73 @@ +import type { Page, TestInfo } from '@playwright/test'; +import type { E2EPage } from '@utils/test/playwright'; + +/** + * Overwrites the default Playwright page.setContent method. + * + * Navigates to a blank page, sets the content, and waits for the + * Stencil components to be hydrated before proceeding with the test. + * + * Ported from Ionic Framework's fixture. Ionicons has no mode, direction, + * or palette config, so only the ionicons build is injected. + * + * @param page The Playwright page object. + * @param html The HTML content to set on the page body. + * @param testInfo The TestInfo associated with the current test run. + * @param options Navigation options passed to page.goto. + */ +export const setContent = async ( + page: Page, + html: string, + testInfo: TestInfo, + options?: Parameters<E2EPage['goto']>[1], +) => { + if (page.isClosed()) { + throw new Error('setContent unavailable: page is already closed'); + } + + const baseUrl = testInfo.project.use.baseURL; + if (!baseUrl) { + throw new Error('setContent requires a baseURL in the Playwright config'); + } + + const output = ` + <!DOCTYPE html> + <html dir="ltr" lang="en"> + <head> + <title>Ionicons Playwright Test + + + + + + ${html} + + + `; + + await page.route(baseUrl, (route) => { + if (route.request().url() === `${baseUrl}/`) { + /** + * Intercepts the empty page request and returns the + * HTML content that was passed in. + */ + route.fulfill({ + status: 200, + contentType: 'text/html', + body: output, + }); + } else { + // Allow all other requests to pass through + route.continue(); + } + }); + + /** + * URL query parameters cause the custom Playwright `page.route` + * interceptor to fail, which is necessary to inject the test HTML. + * + * To avoid this, the final navigation URL is kept simple by using + * hash params to ensure the route interceptor always works. + */ + await page.goto(`${baseUrl}#`, options); +}; diff --git a/src/utils/test/playwright/playwright-declarations.ts b/src/utils/test/playwright/playwright-declarations.ts index e7f6e5fb..15395089 100644 --- a/src/utils/test/playwright/playwright-declarations.ts +++ b/src/utils/test/playwright/playwright-declarations.ts @@ -54,4 +54,10 @@ export interface E2EPage extends Page { waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' | 'commit'; }, ) => Promise; + + /** + * Replaces the page content with the given HTML, loads the ionicons build, + * and waits for the Stencil components to be hydrated. + */ + setContent: (html: string, options?: Parameters[1]) => Promise; } diff --git a/src/utils/test/playwright/playwright-page.ts b/src/utils/test/playwright/playwright-page.ts index 68c81d35..d9693253 100644 --- a/src/utils/test/playwright/playwright-page.ts +++ b/src/utils/test/playwright/playwright-page.ts @@ -7,7 +7,7 @@ import type { } from '@playwright/test'; import { test as base } from '@playwright/test'; -import { goto as goToPage } from './page/utils'; +import { goto as goToPage, setContent } from './page/utils'; import type { E2EPage } from './playwright-declarations'; type CustomTestArgs = PlaywrightTestArgs & @@ -43,6 +43,7 @@ export async function extendPageFixture(page: E2EPage, testInfo: TestInfo) { })();`); // Overridden Playwright methods page.goto = (url: string, options) => goToPage(page, url, options, testInfo, originalGoto); + page.setContent = (html: string, options) => setContent(page, html, testInfo, options); return page; }