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

Fix 19570 tree chart not compliant strict csp styles #19717

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/.eslintrc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,11 @@ parserOptions:
sourceType: module
ecmaFeatures:
modules: true
project: "tsconfig.json"
project: "**/tsconfig.json"
plugins: ["@typescript-eslint"]
env:
es6: false
browser: true
globals:
jQuery: false
Promise: false
Expand Down
100 changes: 71 additions & 29 deletions src/component/tooltip/TooltipHTMLContent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,34 +73,49 @@ function assembleArrow(
borderColor = convertToColorString(borderColor);
const arrowPos = mirrorPos(arrowPosition);
const arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
let positionStyle = '';
let transformStyle = CSS_TRANSFORM_VENDOR + ':';

const arrowClasses = ['tooltip-arrow'];
const transformClasses = [];
let rotateDeg;
if (indexOf(['left', 'right'], arrowPos) > -1) {
positionStyle += 'top:50%';
transformStyle += `translateY(-50%) rotate(${rotateDeg = arrowPos === 'left' ? -225 : -45}deg)`;

if (['left', 'right'].includes(arrowPos)) {
arrowClasses.push('tooltip-arrow-horizontal');
transformClasses.push(`tooltip-arrow-rotate-${rotateDeg = arrowPos === 'left' ? -225 : -45}`);
}
else {
positionStyle += 'left:50%';
transformStyle += `translateX(-50%) rotate(${rotateDeg = arrowPos === 'top' ? 225 : 45}deg)`;
arrowClasses.push('tooltip-arrow-vertical');
transformClasses.push(`tooltip-arrow-rotate-${rotateDeg = arrowPos === 'top' ? 225 : 45}`);
}

function calculateArrowOffset(rotatedWH: number, borderWidth: number, arrowWH: number) {
return Math.round(
(
((rotatedWH - Math.SQRT2 * borderWidth) / 2
+ Math.SQRT2 * borderWidth
- (rotatedWH - arrowWH) / 2)
* 100
) / 100
);
}

function getColorClassName(color: ZRColor) {
const colorValue = convertToColorString(color);
return colorValue.replace(/[^a-zA-Z0-9]/g, '');
}

const rotateRadian = rotateDeg * Math.PI / 180;
const arrowWH = arrowSize + borderWidth;
const rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
const arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2
+ Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
positionStyle += `;${arrowPos}:-${arrowOffset}px`;

const borderStyle = `${borderColor} solid ${borderWidth}px;`;
const styleCss = [
`position:absolute;width:${arrowSize}px;height:${arrowSize}px;z-index:-1;`,
`${positionStyle};${transformStyle};`,
`border-bottom:${borderStyle}`,
`border-right:${borderStyle}`,
`background-color:${backgroundColor};`
];

return `<div style="${styleCss.join('')}"></div>`;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enabling a strict policy for the style-src directive in CSP offers several security benefits for your web application:

  • XSS attacks aim to inject malicious scripts into your website. By restricting stylesheet sources, you prevent attackers from embedding malicious code within stylesheets and potentially compromising user data or website functionality.
  • A strict policy grants you more control over the styles applied to your website. You determine the legitimate sources for stylesheets, preventing unauthorized styles from altering your website's appearance or behavior.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

styles properties that are set directly on the element's style property will not be blocked, allowing users to safely manipulate styles via JavaScript. e.g. this, document.body.style.background = 'green'; won't cause an unsafe-inline violation.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello @Ovilia ,
Could you review this PR or help me find the right person?

const arrowOffset = calculateArrowOffset(rotatedWH, borderWidth, arrowWH);

arrowClasses.push(`tooltip-arrow-offset-${arrowPos}-${arrowOffset}`);

const borderColorClass = `tooltip-arrow-border-color-${getColorClassName(borderColor)}`;
const backgroundColorClass = `tooltip-arrow-background-color-${getColorClassName(backgroundColor)}`;

const classes = [...arrowClasses, borderColorClass, backgroundColorClass, ...transformClasses];

return `<div class="${classes.join(' ')}"></div>`;
}

function assembleTransition(duration: number, onlyFade?: boolean): string {
Expand Down Expand Up @@ -418,24 +433,53 @@ class TooltipHTMLContent {
borderColor?: ZRColor,
arrowPosition?: TooltipOption['position']
) {
function clearContent(el: HTMLElement) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
}

function setTextContent(el: HTMLElement, text: string) {
clearContent(el);

const fragment = document.createRange().createContextualFragment(text);
while (fragment.firstChild) {
el.appendChild(fragment.firstChild);
}
}

function appendArrow(el: HTMLElement, arrow: string) {
if (!arrow) {
return;
}
const arrowEl = document.createElement('div');
arrowEl.classList.add('tooltip-arrow');
arrowEl.innerHTML = arrow;
el.appendChild(arrowEl);
}

const el = this.el;

if (content == null) {
el.innerHTML = '';
clearContent(el);
return;
}

let arrow = '';
if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item'
&& !shouldTooltipConfine(tooltipModel)) {
if (
isString(arrowPosition)
&& tooltipModel.get('trigger') === 'item'
&& !shouldTooltipConfine(tooltipModel)
) {
arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
}
if (isString(content)) {
el.innerHTML = content + arrow;
setTextContent(el, content);
appendArrow(el, arrow);
}
else if (content) {
// Clear previous
el.innerHTML = '';
clearContent(el);
if (!isArray(content)) {
content = [content];
}
Expand All @@ -448,9 +492,7 @@ class TooltipHTMLContent {
if (arrow && el.childNodes.length) {
// no need to create a new parent element, but it's not supported by IE 10 and older.
// const arrowEl = document.createRange().createContextualFragment(arrow);
const arrowEl = document.createElement('div');
arrowEl.innerHTML = arrow;
el.appendChild(arrowEl);
appendArrow(el, arrow);
}
}
}
Expand Down
91 changes: 65 additions & 26 deletions src/component/tooltip/tooltipMarkup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ type RichTextStyle = {

type TextStyle = string | RichTextStyle;

const TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1';

// TODO: more textStyle option
function getTooltipTextStyle(
textStyle: TooltipOption['textStyle'],
Expand All @@ -60,24 +58,28 @@ function getTooltipTextStyle(
if (renderMode === 'html') {
// `textStyle` is probably from user input, should be encoded to reduce security risk.
return {
// eslint-disable-next-line max-len
nameStyle: `font-size:${encodeHTML(nameFontSize + '')}px;color:${encodeHTML(nameFontColor)};font-weight:${encodeHTML(nameFontWeight + '')}`,
// eslint-disable-next-line max-len
valueStyle: `font-size:${encodeHTML(valueFontSize + '')}px;color:${encodeHTML(valueFontColor)};font-weight:${encodeHTML(valueFontWeight + '')}`
nameStyle: `tooltip-name-style tooltip-name-color-${nameFontColor.replace(
'#',
''
)} tooltip-name-size-${nameFontSize} tooltip-name-weight-${nameFontWeight}`,
valueStyle: `tooltip-value-style tooltip-value-color-${valueFontColor.replace(
'#',
''
)} tooltip-value-size-${valueFontSize} tooltip-value-weight-${valueFontWeight}`,
};
}
else {
return {
nameStyle: {
fontSize: nameFontSize,
fill: nameFontColor,
fontWeight: nameFontWeight
fontWeight: nameFontWeight,
},
valueStyle: {
fontSize: valueFontSize,
fill: valueFontColor,
fontWeight: valueFontWeight
}
fontWeight: valueFontWeight,
},
};
}
}
Expand Down Expand Up @@ -288,7 +290,7 @@ function buildSection(
}
else {
return wrapBlockHTML(
`<div style="${nameStyle};${TOOLTIP_LINE_HEIGHT_CSS};">`
'<div class="tooltip-content">'
+ encodeHTML(displayableHeader)
+ '</div>'
+ subMarkupText,
Expand Down Expand Up @@ -409,20 +411,40 @@ function wrapBlockHTML(
encodedContent: string,
topGap: number
): string {
const clearfix = '<div style="clear:both"></div>';
const marginCSS = `margin: ${topGap}px 0 0`;
return `<div style="${marginCSS};${TOOLTIP_LINE_HEIGHT_CSS};">`
+ encodedContent + clearfix
+ '</div>';
function createElementFromHTML(htmlString: string) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString.trim(), 'text/html');
const fragment = document.createDocumentFragment();

for (const child of doc.body.childNodes as any) {
fragment.appendChild(child);
}

return fragment;
}

const clearfixDiv = document.createElement('div');
clearfixDiv.classList.add('clearfix');

const contentDiv = document.createElement('div');
contentDiv.classList.add('tooltip-content');
contentDiv.classList.add(`margin-top-${topGap}`);

const contentFragment = createElementFromHTML(encodedContent);
contentDiv.appendChild(contentFragment);

contentDiv.appendChild(clearfixDiv);

return contentDiv.outerHTML;
}

function wrapInlineNameHTML(
name: string,
leftHasMarker: boolean,
style: string
): string {
const marginCss = leftHasMarker ? 'margin-left:2px' : '';
return `<span style="${style};${marginCss}">`
const marginCss = leftHasMarker ? 'margin-left-2px' : '';
return `<span class="${style} ${marginCss}">`
+ encodeHTML(name)
+ '</span>';
}
Expand All @@ -432,17 +454,34 @@ function wrapInlineValueHTML(
alignRight: boolean,
valueCloseToMarker: boolean,
style: string
): string {
): HTMLElement {
// Do not too close to marker, considering there are multiple values separated by spaces.
const paddingStr = valueCloseToMarker ? '10px' : '20px';
const alignCSS = alignRight ? `float:right;margin-left:${paddingStr}` : '';
const padding = valueCloseToMarker ? '10px' : '20px';
const alignClass = alignRight
? 'tooltip-value-right'
: 'tooltip-value-left';
const styleClasses = `tooltip-value-container ${alignClass} ${padding}`;

valueList = isArray(valueList) ? valueList : [valueList];
return (
`<span style="${alignCSS};${style}">`
// Value has commas inside, so use ' ' as delimiter for multiple values.
+ map(valueList, value => encodeHTML(value)).join('&nbsp;&nbsp;')
+ '</span>'
);

const valueSpan = document.createElement('span');
valueSpan.classList.add(...styleClasses.split(' '));

// Split the style argument by spaces and add each class separately
const styleClassList = style.split(' ');
valueSpan.classList.add(...styleClassList);

valueList.forEach((value) => {
const valueNode = document.createTextNode(encodeHTML(value));
valueSpan.appendChild(valueNode);

if (value !== valueList[valueList.length - 1]) {
const spacer = document.createTextNode('\u00A0\u00A0'); // Non-breaking spaces
valueSpan.appendChild(spacer);
}
});

return valueSpan;
}

function wrapInlineNameRichText(ctx: TooltipMarkupBuildContext, name: string, style: RichTextStyle): string {
Expand Down
15 changes: 6 additions & 9 deletions src/util/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,22 +192,19 @@ export function getTooltipMarker(inOpt: ColorString | GetTooltipMarkerOpt, extra
} : (inOpt || {}) as GetTooltipMarkerOpt;
const color = opt.color;
const type = opt.type;
extraCssText = opt.extraCssText;
const extraCssClasses = opt.extraCssText ? opt.extraCssText.split(' ') : [];
const renderMode = opt.renderMode || 'html';

if (!color) {
return '';
}

if (renderMode === 'html') {
return type === 'subItem'
? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
+ 'border-radius:4px;width:4px;height:4px;background-color:'
// Only support string
+ encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
: '<span style="display:inline-block;margin-right:4px;'
+ 'border-radius:10px;width:10px;height:10px;background-color:'
+ encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
const markerClass = type === 'subItem' ? 'tooltip-marker-sub' : 'tooltip-marker';
const colorClass = `tooltip-marker-color-${color.replace('#', '')}`;
const classes = [markerClass, colorClass, ...extraCssClasses];

return `<span class="${classes.join(' ')}"></span>`;
}
else {
// Should better not to auto generate style name by auto-increment number here.
Expand Down
12 changes: 2 additions & 10 deletions test/heatmap.html

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.