Alerting: Fix fieldSelector encoding (#99751)

Co-authored-by: Sonia Aguilar <soniaaguilarpeiron@gmail.com>
This commit is contained in:
Gilles De Mey 2025-01-29 18:54:41 +01:00 committed by GitHub
parent 7d4895c3c9
commit 49bd8a608e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 42 additions and 2 deletions

View File

@ -10,7 +10,11 @@ import {
import { BaseAlertmanagerArgs, Skippable } from 'app/features/alerting/unified/types/hooks';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { PROVENANCE_NONE } from 'app/features/alerting/unified/utils/k8s/constants';
import { isK8sEntityProvisioned, shouldUseK8sApi } from 'app/features/alerting/unified/utils/k8s/utils';
import {
encodeFieldSelector,
isK8sEntityProvisioned,
shouldUseK8sApi,
} from 'app/features/alerting/unified/utils/k8s/utils';
import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types';
import { getAPINamespace } from '../../../../../api/utils';
@ -200,7 +204,8 @@ export const useGetMuteTiming = ({ alertmanager, name: nameToFind }: BaseAlertma
useEffect(() => {
if (useK8sApi) {
const namespace = getAPINamespace();
getGrafanaTimeInterval({ namespace, fieldSelector: `spec.name=${nameToFind}` }, true);
const entityName = encodeFieldSelector(nameToFind);
getGrafanaTimeInterval({ namespace, fieldSelector: `spec.name=${entityName}` }, true);
} else {
getAlertmanagerTimeInterval(alertmanager, true);
}

View File

@ -0,0 +1,27 @@
import { encodeFieldSelector } from './utils';
describe('encodeFieldSelector', () => {
it('should escape backslashes', () => {
expect(encodeFieldSelector('some\\value')).toBe('some\\\\value');
});
it('should escape equal signs', () => {
expect(encodeFieldSelector('key=value')).toBe('key\\=value');
});
it('should handle strings with no backslashes or equal signs', () => {
expect(encodeFieldSelector('simplevalue')).toBe('simplevalue');
});
it('should handle strings with multiple equal signs', () => {
expect(encodeFieldSelector('key=value=another=value')).toBe('key\\=value\\=another\\=value');
});
it('should escape commas', () => {
expect(encodeFieldSelector('value,another')).toBe('value\\,another');
});
it('should escape mixed special characters', () => {
expect(encodeFieldSelector('foo=bar,bar=baz,qux\\foo')).toBe('foo\\=bar\\,bar\\=baz\\,qux\\\\foo');
});
});

View File

@ -43,3 +43,11 @@ export const canAdminEntity = (k8sEntity: EntityToCheck) =>
export const canDeleteEntity = (k8sEntity: EntityToCheck) =>
getAnnotation(k8sEntity, K8sAnnotations.AccessDelete) === 'true';
/**
* Escape \ and = characters for field selectors.
* The Kubernetes API Machinery will decode those automatically.
*/
export const encodeFieldSelector = (value: string): string => {
return value.replaceAll(/\\/g, '\\\\').replaceAll(/\=/g, '\\=').replaceAll(/,/g, '\\,');
};