Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: make data tables support html #24368

Merged
merged 14 commits into from
Jun 14, 2023
112 changes: 112 additions & 0 deletions superset-frontend/packages/superset-ui-core/src/utils/html.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 {
sanitizeHtml,
isProbablyHTML,
sanitizeHtmlIfNeeded,
safeHtmlSpan,
removeHTMLTags,
} from './html';

describe('sanitizeHtml', () => {
test('should sanitize the HTML string', () => {
const htmlString = '<script>alert("XSS")</script>';
const sanitizedString = sanitizeHtml(htmlString);
expect(sanitizedString).not.toContain('script');
});
});

describe('isProbablyHTML', () => {
test('should return true if the text contains HTML tags', () => {
const htmlText = '<div>Some HTML content</div>';
const isHTML = isProbablyHTML(htmlText);
expect(isHTML).toBe(true);
});

test('should return false if the text does not contain HTML tags', () => {
const plainText = 'Just a plain text';
const isHTML = isProbablyHTML(plainText);
expect(isHTML).toBe(false);
});
});

describe('sanitizeHtmlIfNeeded', () => {
test('should sanitize the HTML string if it contains HTML tags', () => {
const htmlString = '<div>Some <b>HTML</b> content</div>';
const sanitizedString = sanitizeHtmlIfNeeded(htmlString);
expect(sanitizedString).toEqual(htmlString);
});

test('should return the string as is if it does not contain HTML tags', () => {
const plainText = 'Just a plain text';
const sanitizedString = sanitizeHtmlIfNeeded(plainText);
expect(sanitizedString).toEqual(plainText);
});
});

describe('safeHtmlSpan', () => {
test('should return a safe HTML span when the input is HTML', () => {
const htmlString = '<div>Some <b>HTML</b> content</div>';
const safeSpan = safeHtmlSpan(htmlString);
expect(safeSpan).toEqual(
<span
className="safe-html-wrapper"
dangerouslySetInnerHTML={{ __html: htmlString }}
/>,
);
});

test('should return the input string as is when it is not HTML', () => {
const plainText = 'Just a plain text';
const result = safeHtmlSpan(plainText);
expect(result).toEqual(plainText);
});
});

describe('removeHTMLTags', () => {
test('should remove HTML tags from the string', () => {
const input = '<p>Hello, <strong>World!</strong></p>';
const output = removeHTMLTags(input);
expect(output).toBe('Hello, World!');
});

test('should return the same string when no HTML tags are present', () => {
const input = 'This is a plain text.';
const output = removeHTMLTags(input);
expect(output).toBe('This is a plain text.');
});

test('should remove nested HTML tags and return combined text content', () => {
const input = '<div><h1>Title</h1><p>Content</p></div>';
const output = removeHTMLTags(input);
expect(output).toBe('TitleContent');
});

test('should handle self-closing tags and return an empty string', () => {
const input = '<img src="image.png" alt="Image">';
const output = removeHTMLTags(input);
expect(output).toBe('');
});

test('should handle malformed HTML tags and remove only well-formed tags', () => {
const input = '<div><h1>Unclosed tag';
const output = removeHTMLTags(input);
expect(output).toBe('<div>Unclosed tag');
});
});
53 changes: 53 additions & 0 deletions superset-frontend/packages/superset-ui-core/src/utils/html.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React from 'react';
import { FilterXSS, getDefaultWhiteList } from 'xss';

const xssFilter = new FilterXSS({
whiteList: {
mistercrunch marked this conversation as resolved.
Show resolved Hide resolved
...getDefaultWhiteList(),
span: ['style', 'class', 'title'],
div: ['style', 'class'],
a: ['style', 'class', 'href', 'title', 'target'],
img: ['style', 'class', 'src', 'alt', 'title', 'width', 'height'],
video: [
'autoplay',
'controls',
'loop',
'preload',
'src',
'height',
'width',
'muted',
],
},
stripIgnoreTag: true,
css: false,
});

export function sanitizeHtml(htmlString: string) {
return xssFilter.process(htmlString);
}

export function isProbablyHTML(text: string) {
return /<[^>]+>/.test(text);
}

export function sanitizeHtmlIfNeeded(htmlString: string) {
return isProbablyHTML(htmlString) ? sanitizeHtml(htmlString) : htmlString;
}

export function safeHtmlSpan(possiblyHtmlString: string) {
const isHtml = isProbablyHTML(possiblyHtmlString);
if (isHtml) {
return (
<span
className="safe-html-wrapper"
dangerouslySetInnerHTML={{ __html: sanitizeHtml(possiblyHtmlString) }}
/>
);
}
return possiblyHtmlString;
}

export function removeHTMLTags(str: string): string {
return str.replace(/<[^>]*>/g, '');
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ export { getSelectedText } from './getSelectedText';
export * from './featureFlags';
export * from './random';
export * from './typedMemo';
export * from './html';
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* under the License.
*/

import { styled } from '@superset-ui/core';
import { styled, safeHtmlSpan } from '@superset-ui/core';
import React, { useMemo } from 'react';
import { filterXSS } from 'xss';

Expand Down Expand Up @@ -55,28 +55,12 @@ export default function Tooltip(props: TooltipProps) {
}

const { x, y, content } = tooltip;

if (typeof content === 'string') {
// eslint-disable-next-line react-hooks/rules-of-hooks
const contentHtml = useMemo(
() => ({
__html: filterXSS(content, { stripIgnoreTag: true }),
}),
[content],
);
return (
<StyledDiv top={y} left={x}>
<div
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={contentHtml}
/>
</StyledDiv>
);
}
const safeContent =
typeof content === 'string' ? safeHtmlSpan(content) : content;

return (
<StyledDiv top={y} left={x}>
{content}
{safeContent}
</StyledDiv>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,41 +16,16 @@
* specific language governing permissions and limitations
* under the License.
*/
import { FilterXSS, getDefaultWhiteList } from 'xss';
import {
DataRecordValue,
GenericDataType,
getNumberFormatter,
isProbablyHTML,
sanitizeHtml,
} from '@superset-ui/core';
import { DataColumnMeta } from '../types';
import DateWithFormatter from './DateWithFormatter';

const xss = new FilterXSS({
whiteList: {
...getDefaultWhiteList(),
span: ['style', 'class', 'title'],
div: ['style', 'class'],
a: ['style', 'class', 'href', 'title', 'target'],
img: ['style', 'class', 'src', 'alt', 'title', 'width', 'height'],
video: [
'autoplay',
'controls',
'loop',
'preload',
'src',
'height',
'width',
'muted',
],
},
stripIgnoreTag: true,
css: false,
});

function isProbablyHTML(text: string) {
return /<[^>]+>/.test(text);
}

/**
* Format text for cell value.
*/
Expand All @@ -76,7 +51,7 @@ function formatValue(
return [false, formatter(value as number)];
}
if (typeof value === 'string') {
return isProbablyHTML(value) ? [true, xss.process(value)] : [false, value];
return isProbablyHTML(value) ? [true, sanitizeHtml(value)] : [false, value];
}
return [false, value.toString()];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
extractQueryFields,
getChartMetadataRegistry,
QueryFormData,
removeHTMLTags,
styled,
t,
} from '@superset-ui/core';
Expand All @@ -49,8 +50,14 @@ const DisabledMenuItem = ({ children, ...props }: { children: ReactNode }) => (
</div>
</Menu.Item>
);

const Filter = styled.span`
const Filter = ({ children, stripHTML = false }) => {
const content =
stripHTML && typeof children === 'string'
? removeHTMLTags(children)
: children;
return <span>{content}</span>;
};
const StyledFilter = styled(Filter)`
${({ theme }) => `
font-weight: ${theme.typography.weights.bold};
color: ${theme.colors.primary.base};
Expand Down Expand Up @@ -191,7 +198,7 @@ const DrillDetailMenuItems = ({
onClick={openModal.bind(null, [filter])}
>
{`${DRILL_TO_DETAIL_TEXT} `}
<Filter>{filter.formattedVal}</Filter>
<StyledFilter stripHTML>{filter.formattedVal}</StyledFilter>
</MenuItemWithTruncation>
))}
{filters.length > 1 && (
Expand All @@ -202,7 +209,7 @@ const DrillDetailMenuItems = ({
>
<div>
{`${DRILL_TO_DETAIL_TEXT} `}
<Filter>{t('all')}</Filter>
<StyledFilter>{t('all')}</StyledFilter>
</div>
</Menu.Item>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ export default function DrillDetailPane({
}
resizable
virtualize
allowHTML
/>
</Resizable>
);
Expand Down
5 changes: 5 additions & 0 deletions superset-frontend/src/components/FilterableTable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { JSONTree } from 'react-json-tree';
import {
getMultipleTextDimensions,
t,
safeHtmlSpan,
styled,
useTheme,
} from '@superset-ui/core';
Expand Down Expand Up @@ -128,6 +129,7 @@ const FilterableTable = ({
height,
filterText = '',
expandedColumns = [],
allowHTML = true,
}: FilterableTableProps) => {
const formatTableData = (data: Record<string, unknown>[]): Datum[] =>
data.map(row => {
Expand Down Expand Up @@ -352,6 +354,9 @@ const FilterableTable = ({
if (jsonObject) {
return renderJsonModal(cellNode, jsonObject, cellData);
}
if (allowHTML) {
return safeHtmlSpan(cellData);
}
return content;
};

Expand Down
17 changes: 15 additions & 2 deletions superset-frontend/src/components/Table/VirtualTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ import classNames from 'classnames';
import { useResizeDetector } from 'react-resize-detector';
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { VariableSizeGrid as Grid } from 'react-window';
import { useTheme, styled } from '@superset-ui/core';
import { useTheme, styled, safeHtmlSpan } from '@superset-ui/core';

import { TableSize, ETableAction } from './index';

interface VirtualTableProps<RecordType> extends AntTableProps<RecordType> {
height?: number;
allowHTML?: boolean;
}

const StyledCell = styled('div')<{ height?: number }>(
Expand Down Expand Up @@ -71,7 +72,15 @@ const MIDDLE = 47;
const VirtualTable = <RecordType extends object>(
props: VirtualTableProps<RecordType>,
) => {
const { columns, pagination, onChange, height, scroll, size } = props;
const {
columns,
pagination,
onChange,
height,
scroll,
size,
allowHTML = false,
} = props;
const [tableWidth, setTableWidth] = useState<number>(0);
const onResize = useCallback((width: number) => {
setTableWidth(width);
Expand Down Expand Up @@ -213,6 +222,10 @@ const VirtualTable = <RecordType extends object>(
content = render(content, data, rowIndex);
}

if (allowHTML && typeof content === 'string') {
content = safeHtmlSpan(content);
}

return (
<StyledCell
className={classNames('virtual-table-cell', {
Expand Down
Loading