From 117cdc7b130b7254a55d40146f925f3c610237a6 Mon Sep 17 00:00:00 2001 From: Antoine THEBAUD Date: Tue, 20 Oct 2026 11:33:03 +0200 Subject: [PATCH 1/4] [FEATURE] Support Markdown in panel description Signed-off-by: Antoine THEBAUD --- dashboards/package.json | 2 + .../src/components/Panel/Panel.test.tsx | 28 +++- .../src/components/Panel/PanelActions.tsx | 5 +- .../Panel/PanelDescriptionTooltip.test.tsx | 45 ++++++ .../Panel/PanelDescriptionTooltip.tsx | 137 ++++++++++++++++++ .../PanelDrawer/PanelEditorForm.tsx | 4 +- package-lock.json | 30 ++++ 7 files changed, 245 insertions(+), 6 deletions(-) create mode 100644 dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx create mode 100644 dashboards/src/components/Panel/PanelDescriptionTooltip.tsx diff --git a/dashboards/package.json b/dashboards/package.json index 36d87d068..15bd86c42 100644 --- a/dashboards/package.json +++ b/dashboards/package.json @@ -38,7 +38,9 @@ "@snapgridjs/react": "^0.10.0", "@tanstack/hotkeys": "^0.8.0", "@tanstack/react-hotkeys": "^0.9.1", + "dompurify": "^3.4.17", "immer": "^10.1.1", + "marked": "^15.0.12", "mdi-material-ui": "^7.9.2", "react-hook-form": "^7.87.0", "react-intersection-observer": "^9.4.0", diff --git a/dashboards/src/components/Panel/Panel.test.tsx b/dashboards/src/components/Panel/Panel.test.tsx index fb26a4b6d..555d04f6b 100644 --- a/dashboards/src/components/Panel/Panel.test.tsx +++ b/dashboards/src/components/Panel/Panel.test.tsx @@ -17,7 +17,7 @@ import { DataQueriesProvider, TimeRangeProviderBasic, useDataQueriesContext } fr import type * as PluginSystemModule from '@perses-dev/plugin-system'; import type { PanelDefinition, QueryDefinition, VariableDefinition, VariableValue } from '@perses-dev/spec'; import { DEFAULT_ALL_VALUE } from '@perses-dev/spec'; -import { fireEvent, screen, waitFor } from '@testing-library/react'; +import { fireEvent, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { VariableProvider } from '../../context'; @@ -290,12 +290,34 @@ describe('Panel', () => { // Can hover to see panel description in tooltip userEvent.hover(descriptionButton); - const tooltip = await screen.findByRole('tooltip', { name: 'This is a fake panel - bar' }); - expect(tooltip).toBeDefined(); + const tooltip = await screen.findByTestId('panel-description-content'); expect(tooltip).toHaveTextContent('This is a fake panel - bar'); expect(descriptionButton.querySelector('svg')).toHaveAttribute('aria-describedby', 'info-tooltip'); }); + it('renders panel description as markdown', async () => { + const panel = createTestPanel(); + panel.spec.display = { + name: 'Fake Panel Title', + description: + '# Heading\n\nSome **bold** text for $foo\n\n- first item\n- second item\n\n[docs](https://example.com)', + }; + await renderPanel(panel); + + userEvent.hover(screen.getByRole('button', { name: /description/i })); + + const content = await screen.findByTestId('panel-description-content'); + expect(within(content).getByRole('heading', { name: 'Heading' })).toBeInTheDocument(); + expect(content.querySelector('strong')).toHaveTextContent('bold'); + expect(content).toHaveTextContent('Some bold text for bar'); + expect( + within(content) + .getAllByRole('listitem') + .map((item) => item.textContent), + ).toEqual(['first item', 'second item']); + expect(within(content).getByRole('link', { name: 'docs' })).toHaveAttribute('target', '_blank'); + }); + it('shows panel link', async () => { await renderPanel(); diff --git a/dashboards/src/components/Panel/PanelActions.tsx b/dashboards/src/components/Panel/PanelActions.tsx index 0fb9033d9..a683474c7 100644 --- a/dashboards/src/components/Panel/PanelActions.tsx +++ b/dashboards/src/components/Panel/PanelActions.tsx @@ -40,6 +40,7 @@ import { import { LinksDisplay } from '../LinksDisplay'; import { HeaderIconButton } from './HeaderIconButton'; import type { PanelOptions } from './Panel'; +import { PanelDescriptionTooltip } from './PanelDescriptionTooltip'; const noticeTypeToIcon: Record = { error: , @@ -98,7 +99,7 @@ export const PanelActions: React.FC = ({ const descriptionAction = useMemo((): ReactNode | undefined => { if (description && description.trim().length > 0) { return ( - + = ({ sx={{ color: (theme) => theme.palette.text.secondary }} /> - + ); } return undefined; diff --git a/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx b/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx new file mode 100644 index 000000000..5fc48387e --- /dev/null +++ b/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx @@ -0,0 +1,45 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import { panelDescriptionToHTML } from './PanelDescriptionTooltip'; + +describe('panelDescriptionToHTML', () => { + it('keeps plain text descriptions unchanged', () => { + expect(panelDescriptionToHTML('Simple description')).toBe('

Simple description

\n'); + }); + + it('preserves single line breaks', () => { + expect(panelDescriptionToHTML('first line\nsecond line')).toBe('

first line
second line

\n'); + }); + + it('renders markdown', () => { + const html = panelDescriptionToHTML('Some **bold** text\n\n- item 1\n- item 2'); + expect(html).toContain('bold'); + expect(html).toContain('
    \n
  • item 1
  • \n
  • item 2
  • \n
'); + }); + + it('opens links in a new tab', () => { + expect(panelDescriptionToHTML('[docs](https://example.com)')).toContain( + 'docs', + ); + }); + + it('sanitizes dangerous HTML', () => { + const html = panelDescriptionToHTML( + 'click', + ); + expect(html).not.toContain(' { + if (!(node instanceof Element) || node.tagName !== 'A') { + return; + } + // Links are always opened in a new tab, so that the dashboard being viewed is not left. + node.setAttribute('target', '_blank'); + node.setAttribute('rel', 'noopener noreferrer'); +}); + +/** + * Converts a (GitHub Flavored) Markdown panel description into sanitized HTML. + */ +export function panelDescriptionToHTML(description: string): string { + const html = marked.parse(description, { gfm: true, breaks: true, async: false }); + return descriptionPurifier.sanitize(html, { ADD_ATTR: ['target', 'rel'] }); +} + +export interface PanelDescriptionTooltipProps { + id?: string; + /** + * Panel description, written in Markdown. + */ + description: string; + children: ReactNode; + enterDelay?: number; +} + +/** + * Tooltip displaying a panel description rendered as Markdown. + * The tooltip is interactive, so that links can be clicked and long descriptions can be scrolled. + */ +export function PanelDescriptionTooltip({ + id, + description, + children, + enterDelay, +}: PanelDescriptionTooltipProps): ReactElement { + const title = useMemo(() => , [description]); + return ( + + {/* Wrap in a span so that the tooltip always has a child that can hold a ref. */} + {children} + + ); +} + +// Tooltip content is only mounted when the tooltip is open, so the Markdown is only parsed on demand. +function PanelDescriptionContent({ description }: { description: string }): ReactElement { + const innerHTML = useMemo(() => ({ __html: panelDescriptionToHTML(description) }), [description]); + return ; +} + +const MarkdownContent = styled(Box)(({ theme }) => ({ + ...theme.typography.caption, + color: theme.palette.text.primary, + maxHeight: '50vh', + overflowY: 'auto', + overflowWrap: 'anywhere', + '& > :first-child': { marginTop: 0 }, + '& > :last-child': { marginBottom: 0 }, + '& p, & ul, & ol, & pre, & table, & blockquote': { + margin: theme.spacing(0, 0, 1), + }, + '& ul, & ol': { paddingLeft: theme.spacing(2.5) }, + '& h1, & h2, & h3, & h4, & h5, & h6': { + margin: theme.spacing(1, 0, 0.5), + fontSize: theme.typography.body2.fontSize, + fontWeight: theme.typography.fontWeightMedium, + }, + '& a': { color: theme.palette.primary.main }, + '& code': { + fontFamily: 'monospace', + fontSize: '0.95em', + padding: '0.1em 0.3em', + borderRadius: '3px', + backgroundColor: theme.palette.action.hover, + }, + '& pre': { + padding: theme.spacing(1), + overflowX: 'auto', + borderRadius: '4px', + backgroundColor: theme.palette.action.hover, + }, + '& pre code': { padding: 0, backgroundColor: 'transparent' }, + '& blockquote': { + paddingLeft: theme.spacing(1), + borderLeft: `3px solid ${theme.palette.divider}`, + color: theme.palette.text.secondary, + }, + '& table, & th, & td': { + padding: theme.spacing(0.5), + border: `1px solid ${theme.palette.divider}`, + borderCollapse: 'collapse', + }, + '& img': { maxWidth: '100%' }, +})); + +function PopperClassTooltip({ className, ...props }: TooltipProps): ReactElement { + const classes = useMemo(() => ({ popper: className }), [className]); + return ; +} + +const StyledTooltip = styled(PopperClassTooltip)(({ theme }) => ({ + [`& .${tooltipClasses.tooltip}`]: { + backgroundColor: theme.palette.background.tooltip, + color: theme.palette.text.primary, + maxWidth: '500px', + padding: theme.spacing(1), + boxShadow: theme.shadows[1], + }, + [`& .${tooltipClasses.arrow}`]: { + color: theme.palette.background.tooltip, + }, +})); diff --git a/dashboards/src/components/PanelDrawer/PanelEditorForm.tsx b/dashboards/src/components/PanelDrawer/PanelEditorForm.tsx index f1d54fff9..a62dc8a02 100644 --- a/dashboards/src/components/PanelDrawer/PanelEditorForm.tsx +++ b/dashboards/src/components/PanelDrawer/PanelEditorForm.tsx @@ -206,9 +206,11 @@ export function PanelEditorForm(props: PanelEditorFormProps): ReactElement { { field.onChange(event); diff --git a/package-lock.json b/package-lock.json index 8a0876d1a..35c3bf9e3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -113,7 +113,9 @@ "@snapgridjs/react": "^0.10.0", "@tanstack/hotkeys": "^0.8.0", "@tanstack/react-hotkeys": "^0.9.1", + "dompurify": "^3.4.17", "immer": "^10.1.1", + "marked": "^15.0.12", "mdi-material-ui": "^7.9.2", "react-hook-form": "^7.87.0", "react-intersection-observer": "^9.4.0", @@ -5670,6 +5672,13 @@ "@types/jest": "*" } }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, "node_modules/@types/yargs": { "version": "17.0.35", "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", @@ -7333,6 +7342,15 @@ "csstype": "^3.0.2" } }, + "node_modules/dompurify": { + "version": "3.4.17", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz", + "integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -9014,6 +9032,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/marked": { + "version": "15.0.12", + "resolved": "https://registry.npmjs.org/marked/-/marked-15.0.12.tgz", + "integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", From 13f1e5033a263baca697e0972562b25940feac00 Mon Sep 17 00:00:00 2001 From: Antoine THEBAUD Date: Tue, 20 Oct 2026 13:45:36 +0200 Subject: [PATCH 2/4] Address review comment (support for non-browser builds) Signed-off-by: Antoine THEBAUD --- .../Panel/PanelDescriptionTooltip.test.tsx | 13 +++++ .../Panel/PanelDescriptionTooltip.tsx | 49 +++++++++++++++---- 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx b/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx index 5fc48387e..0cfaa3790 100644 --- a/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx +++ b/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx @@ -42,4 +42,17 @@ describe('panelDescriptionToHTML', () => { expect(html).not.toContain('onerror'); expect(html).not.toContain('javascript:'); }); + + it('can be imported and falls back to escaped plain text when no DOM is available', async () => { + vi.resetModules(); + vi.stubGlobal('window', undefined); + try { + const module = await import('./PanelDescriptionTooltip'); + expect(module.panelDescriptionToHTML('**bold** ')).toBe( + '**bold** <img src=x onerror="alert(1)">', + ); + } finally { + vi.unstubAllGlobals(); + } + }); }); diff --git a/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx b/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx index df781697e..5d187bd4a 100644 --- a/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx +++ b/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx @@ -13,29 +13,58 @@ import type { TooltipProps } from '@mui/material'; import { Box, styled, Tooltip, tooltipClasses } from '@mui/material'; +import type { DOMPurify as DOMPurifyInstance } from 'dompurify'; import DOMPurify from 'dompurify'; import { marked } from 'marked'; import type { ReactElement, ReactNode } from 'react'; import { useMemo } from 'react'; -// Isolated DOMPurify instance so the hook below does not affect other consumers of the default singleton. -const descriptionPurifier = typeof window !== 'undefined' ? DOMPurify(window) : DOMPurify; +let descriptionPurifier: DOMPurifyInstance | undefined; -descriptionPurifier.addHook('afterSanitizeAttributes', (node) => { - if (!(node instanceof Element) || node.tagName !== 'A') { - return; +// Lazily create an isolated DOMPurify instance, so that: +// - the hook below does not affect other consumers of the default singleton, +// - importing this module does not fail in environments without a DOM (e.g. SSR), where DOMPurify is not supported. +function getDescriptionPurifier(): DOMPurifyInstance { + if (descriptionPurifier === undefined) { + descriptionPurifier = DOMPurify(); + if (descriptionPurifier.isSupported) { + descriptionPurifier.addHook('afterSanitizeAttributes', (node) => { + if (!(node instanceof Element) || node.tagName !== 'A') { + return; + } + // Links are always opened in a new tab, so that the dashboard being viewed is not left. + node.setAttribute('target', '_blank'); + node.setAttribute('rel', 'noopener noreferrer'); + }); + } } - // Links are always opened in a new tab, so that the dashboard being viewed is not left. - node.setAttribute('target', '_blank'); - node.setAttribute('rel', 'noopener noreferrer'); -}); + return descriptionPurifier; +} + +/** + * Escapes the HTML special characters of a text, so that it is displayed as-is instead of being interpreted as HTML. + * Used as a safe fallback when DOMPurify is not supported and the rendered Markdown therefore cannot be sanitized. + */ +function escapeHTML(text: string): string { + return text + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} /** * Converts a (GitHub Flavored) Markdown panel description into sanitized HTML. + * When HTML cannot be sanitized (no DOM available), the description is returned as escaped plain text. */ export function panelDescriptionToHTML(description: string): string { + const purifier = getDescriptionPurifier(); + if (!purifier.isSupported) { + return escapeHTML(description); + } const html = marked.parse(description, { gfm: true, breaks: true, async: false }); - return descriptionPurifier.sanitize(html, { ADD_ATTR: ['target', 'rel'] }); + return purifier.sanitize(html, { ADD_ATTR: ['target', 'rel'] }); } export interface PanelDescriptionTooltipProps { From bf7139af078eb636bd7aecb7bbb303676b3c4f06 Mon Sep 17 00:00:00 2001 From: Antoine THEBAUD Date: Fri, 30 Oct 2026 12:25:14 +0100 Subject: [PATCH 3/4] address review comments Signed-off-by: Antoine THEBAUD --- .../Panel/PanelDescriptionTooltip.test.tsx | 30 +++++++++++++++++++ .../Panel/PanelDescriptionTooltip.tsx | 26 ++++++++++++++-- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx b/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx index 0cfaa3790..1852ba46c 100644 --- a/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx +++ b/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx @@ -11,6 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +import { marked } from 'marked'; + import { panelDescriptionToHTML } from './PanelDescriptionTooltip'; describe('panelDescriptionToHTML', () => { @@ -43,6 +45,34 @@ describe('panelDescriptionToHTML', () => { expect(html).not.toContain('javascript:'); }); + it.each([ + ['style elements', 'foo\n\n', '', 'overlay', 'style='], + ['forms', '
', '', 'go', '', '', 'x', 'class='], + ['id attributes', 'x', 'id='], + ])('removes %s that could affect the page outside the tooltip', (_, description, forbidden) => { + expect(panelDescriptionToHTML(description)).not.toContain(forbidden); + }); + + it('renders task lists without input elements', () => { + expect(panelDescriptionToHTML('- [x] done\n- [ ] todo')).toBe('
    \n
  • ☑ done
  • \n
  • ☐ todo
  • \n
\n'); + }); + + it('is not affected by the global marked configuration', () => { + marked.use({ renderer: { strong: (): string => 'overridden' } }); + try { + expect(panelDescriptionToHTML('**bold**')).toBe('

bold

\n'); + } finally { + marked.setOptions(marked.getDefaults()); + } + }); + it('can be imported and falls back to escaped plain text when no DOM is available', async () => { vi.resetModules(); vi.stubGlobal('window', undefined); diff --git a/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx b/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx index 5d187bd4a..6ff0f5a10 100644 --- a/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx +++ b/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx @@ -15,10 +15,26 @@ import type { TooltipProps } from '@mui/material'; import { Box, styled, Tooltip, tooltipClasses } from '@mui/material'; import type { DOMPurify as DOMPurifyInstance } from 'dompurify'; import DOMPurify from 'dompurify'; -import { marked } from 'marked'; +import { Marked } from 'marked'; import type { ReactElement, ReactNode } from 'react'; import { useMemo } from 'react'; +// Dedicated Marked instance, so that global `marked.use()` / `marked.setOptions()` calls elsewhere in the host +// application do not change how descriptions are rendered. +const descriptionMarked = new Marked({ + gfm: true, + breaks: true, + renderer: { + // Task list items are rendered as text, since `` elements are removed by the sanitizer. + checkbox: ({ checked }): string => (checked ? '☑' : '☐'), + }, +}); + +// Elements and attributes that could affect the page outside the tooltip (which is portaled to `document.body`), +// e.g. restyle or cover the application, or collect user input. +const FORBIDDEN_TAGS = ['style', 'form', 'input', 'button', 'textarea', 'select']; +const FORBIDDEN_ATTRIBUTES = ['style', 'class', 'id']; + let descriptionPurifier: DOMPurifyInstance | undefined; // Lazily create an isolated DOMPurify instance, so that: @@ -63,8 +79,12 @@ export function panelDescriptionToHTML(description: string): string { if (!purifier.isSupported) { return escapeHTML(description); } - const html = marked.parse(description, { gfm: true, breaks: true, async: false }); - return purifier.sanitize(html, { ADD_ATTR: ['target', 'rel'] }); + const html = descriptionMarked.parse(description, { async: false }); + return purifier.sanitize(html, { + ADD_ATTR: ['target', 'rel'], + FORBID_TAGS: FORBIDDEN_TAGS, + FORBID_ATTR: FORBIDDEN_ATTRIBUTES, + }); } export interface PanelDescriptionTooltipProps { From 0a5c31ebb402c981c72425f79deb2c9b150ff495 Mon Sep 17 00:00:00 2001 From: Antoine THEBAUD Date: Fri, 30 Oct 2026 16:03:30 +0100 Subject: [PATCH 4/4] address review comment Signed-off-by: Antoine THEBAUD --- .../Panel/PanelDescriptionTooltip.test.tsx | 64 +++++++++++++------ .../Panel/PanelDescriptionTooltip.tsx | 11 +++- 2 files changed, 54 insertions(+), 21 deletions(-) diff --git a/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx b/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx index 1852ba46c..b92969e9c 100644 --- a/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx +++ b/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx @@ -15,6 +15,13 @@ import { marked } from 'marked'; import { panelDescriptionToHTML } from './PanelDescriptionTooltip'; +// Renders the HTML in a detached element, to check which elements and attributes the browser would actually create. +function toElement(html: string): HTMLElement { + const element = document.createElement('div'); + element.innerHTML = html; + return element; +} + describe('panelDescriptionToHTML', () => { it('keeps plain text descriptions unchanged', () => { expect(panelDescriptionToHTML('Simple description')).toBe('

Simple description

\n'); @@ -36,28 +43,49 @@ describe('panelDescriptionToHTML', () => { ); }); - it('sanitizes dangerous HTML', () => { - const html = panelDescriptionToHTML( - 'click', + it('displays raw HTML as text', () => { + expect(panelDescriptionToHTML('Expected format: :')).toBe( + '

Expected format: <host>:<port>

\n', + ); + expect(panelDescriptionToHTML('
\nblock\n
')).toBe('<div>\nblock\n</div>'); + }); + + it('still renders autolinks', () => { + expect(toElement(panelDescriptionToHTML('See ')).querySelector('a')).toHaveAttribute( + 'href', + 'https://example.com', ); - expect(html).not.toContain('body{display:none}', '', 'overlay', 'style='], - ['forms', '
', '', 'go', '', '', 'x', 'class='], - ['id attributes', 'x', 'id='], - ])('removes %s that could affect the page outside the tooltip', (_, description, forbidden) => { - expect(panelDescriptionToHTML(description)).not.toContain(forbidden); + ['scripts', '', 'script'], + ['event handlers', '', '[onerror]'], + ['style elements', 'foo\n\n', 'style'], + ['style elements inside svg', '', 'svg, style'], + ['inline styles', '
overlay
', '[style]'], + ['forms', '
', 'form, input'], + ['buttons', '', 'button'], + ['textareas', '', 'textarea'], + ['selects', '', 'select'], + ['class attributes', 'x', '[class]'], + ['id attributes', 'x', '[id]'], + ])('does not create %s from raw HTML', (_, description, forbiddenSelector) => { + const element = toElement(panelDescriptionToHTML(description)); + expect(element.querySelector(forbiddenSelector)).toBeNull(); + // The raw HTML is still visible as text. + expect(element.textContent).toContain(description.trim().split('\n').pop()); + }); + + it.each([ + ['links', '[click](javascript:alert(1))'], + ['images', '![img](javascript:alert(1))'], + ])('removes javascript: URLs from Markdown %s', (_, description) => { + const element = toElement(panelDescriptionToHTML(description)); + expect(element.querySelector('[href^="javascript:"], [src^="javascript:"]')).toBeNull(); + }); + + it('removes class attributes produced from Markdown', () => { + expect(toElement(panelDescriptionToHTML('```js\nconst a = 1;\n```')).querySelector('[class]')).toBeNull(); }); it('renders task lists without input elements', () => { diff --git a/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx b/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx index 6ff0f5a10..a5e0c0c77 100644 --- a/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx +++ b/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx @@ -27,11 +27,15 @@ const descriptionMarked = new Marked({ renderer: { // Task list items are rendered as text, since `` elements are removed by the sanitizer. checkbox: ({ checked }): string => (checked ? '☑' : '☐'), + // Raw HTML is not supported: it is displayed as text, so that e.g. `:` is not parsed as tags and + // then removed by the sanitizer. + html: ({ text }): string => escapeHTML(text), }, }); // Elements and attributes that could affect the page outside the tooltip (which is portaled to `document.body`), -// e.g. restyle or cover the application, or collect user input. +// e.g. restyle or cover the application, or collect user input. Raw HTML is already escaped by the renderer, so +// this is a second layer of defense for the HTML produced from Markdown. const FORBIDDEN_TAGS = ['style', 'form', 'input', 'button', 'textarea', 'select']; const FORBIDDEN_ATTRIBUTES = ['style', 'class', 'id']; @@ -59,7 +63,8 @@ function getDescriptionPurifier(): DOMPurifyInstance { /** * Escapes the HTML special characters of a text, so that it is displayed as-is instead of being interpreted as HTML. - * Used as a safe fallback when DOMPurify is not supported and the rendered Markdown therefore cannot be sanitized. + * Used for raw HTML in descriptions, and as a safe fallback when DOMPurify is not supported and the rendered Markdown + * therefore cannot be sanitized. */ function escapeHTML(text: string): string { return text @@ -71,7 +76,7 @@ function escapeHTML(text: string): string { } /** - * Converts a (GitHub Flavored) Markdown panel description into sanitized HTML. + * Converts a (GitHub Flavored) Markdown panel description into sanitized HTML. Raw HTML is displayed as text. * When HTML cannot be sanitized (no DOM available), the description is returned as escaped plain text. */ export function panelDescriptionToHTML(description: string): string {