streamline kbn.addSlashes and add a test, streamline escaping in angular tip() function (#41066)

* streamline kbn.addSlashes and add a test, streamline escaping in angular tip() function
* switch to double-html-encoding when building intermediate string
This commit is contained in:
Dan Cech 2021-11-05 09:18:42 -04:00 committed by GitHub
parent d524dc6108
commit 993cb80fea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 13 additions and 10 deletions

View File

@ -1,7 +1,6 @@
import angular from 'angular';
import Clipboard from 'clipboard';
import coreModule from '../core/core_module';
import kbn from 'app/core/utils/kbn';
import { appEvents } from 'app/core/core';
import { AppEvents } from '@grafana/data';
@ -14,9 +13,11 @@ function tip($compile: any) {
'<i class="grafana-tip fa fa-' +
(attrs.icon || 'question-circle') +
'" bs-tooltip="\'' +
kbn.addSlashes(elem.text()) +
// here we double-html-encode any special characters in the source string
// this is needed so that the final html contains the encoded entities as they
// will be decoded when _t is parsed by angular
elem.text().replace(/[\'\"\\{}<>&]/g, (m: string) => '&amp;#' + m.charCodeAt(0) + ';') +
'\'"></i>';
_t = _t.replace(/{/g, '\\{').replace(/}/g, '\\}');
elem.replaceWith($compile(angular.element(_t))(scope));
},
};

View File

@ -73,3 +73,11 @@ describe('describe_interval', () => {
expect(() => kbn.describeInterval('xyz')).toThrow();
});
});
describe('addSlashes', () => {
it('properly escapes backslashes, single-quotes, double-quotes and the number zero', () => {
expect(kbn.addSlashes('this is a \'test\' with "quotes" backslashes (\\) and zero (0)')).toEqual(
'this is a \\\'test\\\' with \\"quotes\\" backslashes (\\\\) and zero (\\0)'
);
});
});

View File

@ -47,13 +47,7 @@ const kbn = {
return strings.join(':');
},
toPercent: (nr: number, outOf: number) => Math.floor((nr / outOf) * 10000) / 100 + '%',
addSlashes: (str: string) => {
str = str.replace(/\\/g, '\\\\');
str = str.replace(/\'/g, "\\'");
str = str.replace(/\"/g, '\\"');
str = str.replace(/\0/g, '\\0');
return str;
},
addSlashes: (str: string) => str.replace(/[\'\"\\0]/g, '\\$&'),
/** @deprecated since 7.2, use grafana/data */
describeInterval: (str: string) => {
deprecationWarning('kbn.ts', 'kbn.stringToJsRegex()', '@grafana/data');