From bf835af74bf8de07cdf84b354fe089f61238fb11 Mon Sep 17 00:00:00 2001 From: Ivana Huckova <30407135+ivanahuckova@users.noreply.github.com> Date: Thu, 30 Jul 2020 18:07:22 +0200 Subject: [PATCH] Prometheus: Add backslash escaping for template variables (#26205) * Run query on splitOpen action * Escape \ in prometheusRegularEscape * Revert "Run query on splitOpen action" This reverts commit 3559b6c5739f351f4e797c57069bc937bd06c065. Co-authored-by: Andrej Ocenas --- .../app/plugins/datasource/prometheus/datasource.test.ts | 8 ++++++++ public/app/plugins/datasource/prometheus/datasource.ts | 6 ++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/public/app/plugins/datasource/prometheus/datasource.test.ts b/public/app/plugins/datasource/prometheus/datasource.test.ts index 51527ca5495..ad63d1fd066 100644 --- a/public/app/plugins/datasource/prometheus/datasource.test.ts +++ b/public/app/plugins/datasource/prometheus/datasource.test.ts @@ -415,9 +415,17 @@ describe('PrometheusDatasource', () => { expect(prometheusRegularEscape("looking'glass")).toEqual("looking\\\\'glass"); }); + it('should escape \\', () => { + expect(prometheusRegularEscape('looking\\glass')).toEqual('looking\\\\glass'); + }); + it('should escape multiple characters', () => { expect(prometheusRegularEscape("'looking'glass'")).toEqual("\\\\'looking\\\\'glass\\\\'"); }); + + it('should escape multiple different characters', () => { + expect(prometheusRegularEscape("'loo\\king'glass'")).toEqual("\\\\'loo\\\\king\\\\'glass\\\\'"); + }); }); describe('Prometheus regexes escaping', () => { diff --git a/public/app/plugins/datasource/prometheus/datasource.ts b/public/app/plugins/datasource/prometheus/datasource.ts index 42950787b33..041c4690a22 100644 --- a/public/app/plugins/datasource/prometheus/datasource.ts +++ b/public/app/plugins/datasource/prometheus/datasource.ts @@ -764,11 +764,9 @@ export function extractRuleMappingFromGroups(groups: any[]) { } export function prometheusRegularEscape(value: any) { - return typeof value === 'string' ? value.replace(/'/g, "\\\\'") : value; + return typeof value === 'string' ? value.replace(/\\/g, '\\\\').replace(/'/g, "\\\\'") : value; } export function prometheusSpecialRegexEscape(value: any) { - return typeof value === 'string' - ? prometheusRegularEscape(value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]+?.()|]/g, '\\\\$&')) - : value; + return typeof value === 'string' ? value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]\'+?.()|]/g, '\\\\$&') : value; }