Skip to content
Merged
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
2 changes: 2 additions & 0 deletions dashboards/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
28 changes: 25 additions & 3 deletions dashboards/src/components/Panel/Panel.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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();

Expand Down
5 changes: 3 additions & 2 deletions dashboards/src/components/Panel/PanelActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<Notice['type'], ReactNode> = {
error: <AlertCircleIcon color="error" />,
Expand Down Expand Up @@ -98,7 +99,7 @@ export const PanelActions: React.FC<PanelActionsProps> = ({
const descriptionAction = useMemo((): ReactNode | undefined => {
if (description && description.trim().length > 0) {
return (
<InfoTooltip id={descriptionTooltipId} description={description} enterDelay={100}>
<PanelDescriptionTooltip id={descriptionTooltipId} description={description} enterDelay={100}>
<HeaderIconButton aria-label="panel description" size="small">
<InformationOutlineIcon
aria-describedby="info-tooltip"
Expand All @@ -107,7 +108,7 @@ export const PanelActions: React.FC<PanelActionsProps> = ({
sx={{ color: (theme) => theme.palette.text.secondary }}
/>
</HeaderIconButton>
</InfoTooltip>
</PanelDescriptionTooltip>
);
}
return undefined;
Expand Down
116 changes: 116 additions & 0 deletions dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx
Original file line number Diff line number Diff line change
@@ -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('<p>Simple description</p>\n');
});

it('preserves single line breaks', () => {
expect(panelDescriptionToHTML('first line\nsecond line')).toBe('<p>first line<br>second line</p>\n');
});

it('renders markdown', () => {
const html = panelDescriptionToHTML('Some **bold** text\n\n- item 1\n- item 2');
expect(html).toContain('<strong>bold</strong>');
expect(html).toContain('<ul>\n<li>item 1</li>\n<li>item 2</li>\n</ul>');
});

it('opens links in a new tab', () => {
expect(panelDescriptionToHTML('[docs](https://example.com)')).toContain(
'<a href="https://example.com" target="_blank" rel="noopener noreferrer">docs</a>',
);
});

it('displays raw HTML as text', () => {
expect(panelDescriptionToHTML('Expected format: <host>:<port>')).toBe(
'<p>Expected format: &lt;host&gt;:&lt;port&gt;</p>\n',
);
expect(panelDescriptionToHTML('<div>\nblock\n</div>')).toBe('&lt;div&gt;\nblock\n&lt;/div&gt;');
});

it('still renders autolinks', () => {
expect(toElement(panelDescriptionToHTML('See <https://example.com>')).querySelector('a')).toHaveAttribute(
'href',
'https://example.com',
);
});

it.each([
['scripts', '<script>alert(1)</script>', 'script'],
['event handlers', '<img src="x" onerror="alert(1)">', '[onerror]'],
['style elements', 'foo\n\n<style>body{display:none}</style>', 'style'],
['style elements inside svg', '<svg><style>body{display:none}</style></svg>', 'svg, style'],
['inline styles', '<div style="position:fixed;inset:0">overlay</div>', '[style]'],
['forms', '<form action="https://example.com"><input type="password"><button>go</button></form>', 'form, input'],
['buttons', '<button>go</button>', 'button'],
['textareas', '<textarea></textarea>', 'textarea'],
['selects', '<select><option>a</option></select>', 'select'],
['class attributes', '<span class="MuiBackdrop-root">x</span>', '[class]'],
['id attributes', '<span id="root">x</span>', '[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('<ul>\n<li>☑ done</li>\n<li>☐ todo</li>\n</ul>\n');
});

it('is not affected by the global marked configuration', () => {
marked.use({ renderer: { strong: (): string => 'overridden' } });
try {
expect(panelDescriptionToHTML('**bold**')).toBe('<p><strong>bold</strong></p>\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** <img src=x onerror="alert(1)">')).toBe(
'**bold** &lt;img src=x onerror=&quot;alert(1)&quot;&gt;',
);
} finally {
vi.unstubAllGlobals();
}
});
});
191 changes: 191 additions & 0 deletions dashboards/src/components/Panel/PanelDescriptionTooltip.tsx
Original file line number Diff line number Diff line change
@@ -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: {
Comment thread
AntoineThebaud marked this conversation as resolved.
Resolved
// Task list items are rendered as text, since `<input>` elements are removed by the sanitizer.
checkbox: ({ checked }): string => (checked ? '☑' : '☐'),
// Raw HTML is not supported: it is displayed as text, so that e.g. `<host>:<port>` 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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}

/**
* 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(() => <PanelDescriptionContent description={description} />, [description]);
return (
<StyledTooltip arrow id={id} placement="top" title={title} enterDelay={enterDelay ?? 500} enterNextDelay={500}>
Comment thread
AntoineThebaud marked this conversation as resolved.
Resolved
{/* Wrap in a span so that the tooltip always has a child that can hold a ref. */}
<span>{children}</span>
</StyledTooltip>
);
}

// 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 <MarkdownContent data-testid="panel-description-content" dangerouslySetInnerHTML={innerHTML} />;
}

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 <Tooltip {...props} classes={classes} />;
}

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,
},
}));
Loading
Loading