diff --git a/dashboards/package.json b/dashboards/package.json index 9e868cd33..8f343ebb7 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-compiler-runtime": "^1.0.0", "react-hook-form": "^7.87.0", diff --git a/dashboards/src/components/Panel/Panel.test.tsx b/dashboards/src/components/Panel/Panel.test.tsx index de074ce60..51e785efe 100644 --- a/dashboards/src/components/Panel/Panel.test.tsx +++ b/dashboards/src/components/Panel/Panel.test.tsx @@ -22,7 +22,7 @@ import { 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 { act, fireEvent, screen, waitFor } from '@testing-library/react'; +import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import type { ReactElement } from 'react'; import { useSyncExternalStore } from 'react'; @@ -390,12 +390,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..b92969e9c --- /dev/null +++ b/dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx @@ -0,0 +1,116 @@ +// 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 { 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'); + }); + + 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('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', + ); + }); + + it.each([ + ['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', () => { + 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); + 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 new file mode 100644 index 000000000..a5e0c0c77 --- /dev/null +++ b/dashboards/src/components/Panel/PanelDescriptionTooltip.tsx @@ -0,0 +1,191 @@ +// 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 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'; + +// 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 ? '☑' : '☐'), + // 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. 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']; + +let descriptionPurifier: DOMPurifyInstance | undefined; + +// 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'); + }); + } + } + return descriptionPurifier; +} + +/** + * Escapes the HTML special characters of a text, so that it is displayed as-is instead of being interpreted as HTML. + * 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 + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +/** + * 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 { + const purifier = getDescriptionPurifier(); + if (!purifier.isSupported) { + return escapeHTML(description); + } + 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 { + 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 2648e786c..cdfb50741 100644 --- a/dashboards/src/components/PanelDrawer/PanelEditorForm.tsx +++ b/dashboards/src/components/PanelDrawer/PanelEditorForm.tsx @@ -223,9 +223,11 @@ export const PanelEditorForm = forwardRef(function PanelEditorForm( { field.onChange(event); diff --git a/package-lock.json b/package-lock.json index 50ee34240..ceeed46cf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -120,7 +120,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-compiler-runtime": "^1.0.0", "react-hook-form": "^7.87.0", @@ -5518,6 +5520,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", @@ -7181,6 +7190,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", @@ -8862,6 +8880,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",