[ES|QL] Automatically encapsulate index names with special chars with quotes (#187899)

## Summary

Addresses https://github.com/elastic/kibana/issues/186411. This PR
introduces quoted index names when auto populated/suggested if the index
name contains special characters.


94a37a82-9921-4419-b7d4-c8c50cc509f3

If user is already prefixing index name with a quote, e.g. `from "a` it
will suggest as normal.


### Checklis

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
This commit is contained in:
Quynh Nguyen (Quinn) 2024-07-11 01:56:56 -05:00 committed by GitHub
parent cc7588c8cb
commit 27dc08bcc4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 107 additions and 15 deletions

View file

@ -53,15 +53,27 @@ const fields: Array<{ name: string; type: string; suggestedAs?: string }> = [
];
const indexes = ([] as Array<{ name: string; hidden: boolean; suggestedAs?: string }>).concat(
['a', 'index', 'otherIndex', '.secretIndex', 'my-index'].map((name) => ({
[
'a',
'index',
'otherIndex',
'.secretIndex',
'my-index',
'my-index$',
'my_index{}',
'my-index+1',
'synthetics-*',
].map((name) => ({
name,
hidden: name.startsWith('.'),
})),
['my-index[quoted]', 'my-index$', 'my_index{}'].map((name) => ({
name,
hidden: false,
suggestedAs: `\`${name}\``,
}))
['my-index[quoted]', 'my:index', 'my,index', 'logstash-{now/d{yyyy.MM.dd|+12:00}}'].map(
(name) => ({
name,
hidden: false,
suggestedAs: `"${name}"`,
})
)
);
const integrations: Integration[] = ['nginx', 'k8s'].map((name) => ({
@ -365,8 +377,9 @@ describe('autocomplete', () => {
});
describe('from', () => {
const suggestedIndexes = indexes.filter(({ hidden }) => !hidden).map(({ name }) => name);
const suggestedIndexes = indexes
.filter(({ hidden }) => !hidden)
.map(({ name, suggestedAs }) => suggestedAs || name);
// Monaco will filter further down here
testSuggestions(
'f',
@ -394,8 +407,7 @@ describe('autocomplete', () => {
const dataSources = indexes.concat(integrations);
const suggestedDataSources = dataSources
.filter(({ hidden }) => !hidden)
.map(({ name }) => name);
.map(({ name, suggestedAs }) => suggestedAs || name);
testSuggestions('from ', suggestedDataSources, '', [undefined, dataSources, undefined]);
testSuggestions('from a,', suggestedDataSources, '', [undefined, dataSources, undefined]);
testSuggestions('from *,', suggestedDataSources, '', [undefined, dataSources, undefined]);

View file

@ -86,6 +86,7 @@ import {
getQueryForFields,
getSourcesFromCommands,
isAggFunctionUsedAlready,
removeQuoteForSuggestedSources,
} from './helper';
import { FunctionParameter } from '../definitions/types';
@ -857,19 +858,28 @@ async function getExpressionSuggestionsByType(
suggestions.push(...(policies.length ? policies : [buildNoPoliciesAvailableDefinition()]));
} else {
const index = getSourcesFromCommands(commands, 'index');
const canRemoveQuote = isNewExpression && innerText.includes('"');
// This is going to be empty for simple indices, and not empty for integrations
if (index && index.text && index.text !== EDITOR_MARKER) {
const source = index.text.replace(EDITOR_MARKER, '');
const dataSource = await getDatastreamsForIntegration(source);
const newDefinitions = buildSourcesDefinitions(
dataSource?.dataStreams?.map(({ name }) => ({ name, isIntegration: false })) || []
);
suggestions.push(...newDefinitions);
suggestions.push(
...(canRemoveQuote ? removeQuoteForSuggestedSources(newDefinitions) : newDefinitions)
);
} else {
// FROM <suggest>
// @TODO: filter down the suggestions here based on other existing sources defined
const sourcesDefinitions = await getSources();
suggestions.push(...sourcesDefinitions);
suggestions.push(
...(canRemoveQuote
? removeQuoteForSuggestedSources(sourcesDefinitions)
: sourcesDefinitions)
);
}
}
}

View file

@ -19,7 +19,7 @@ import {
CommandOptionsDefinition,
CommandModeDefinition,
} from '../definitions/types';
import { getCommandDefinition, shouldBeQuotedText } from '../shared/helpers';
import { shouldBeQuotedSource, getCommandDefinition, shouldBeQuotedText } from '../shared/helpers';
import { buildDocumentation, buildFunctionDocumentation } from './documentation_util';
import { DOUBLE_BACKTICK, SINGLE_TICK_REGEX } from '../shared/constants';
@ -37,6 +37,13 @@ function getSafeInsertText(text: string, options: { dashSupported?: boolean } =
? `\`${text.replace(SINGLE_TICK_REGEX, DOUBLE_BACKTICK)}\``
: text;
}
export function getQuotedText(text: string) {
return text.startsWith(`"`) && text.endsWith(`"`) ? text : `"${text}"`;
}
function getSafeInsertSourceText(text: string) {
return shouldBeQuotedSource(text) ? getQuotedText(text) : text;
}
export function getSuggestionFunctionDefinition(fn: FunctionDefinition): SuggestionRawDefinition {
const fullSignatures = getFunctionSignatures(fn);
@ -148,7 +155,7 @@ export const buildSourcesDefinitions = (
): SuggestionRawDefinition[] =>
sources.map(({ name, isIntegration, title }) => ({
label: title ?? name,
text: name,
text: getSafeInsertSourceText(name),
isSnippet: isIntegration,
...(isIntegration && { command: TRIGGER_SUGGESTION_COMMAND }),
kind: isIntegration ? 'Class' : 'Issue',

View file

@ -7,8 +7,9 @@
*/
import type { ESQLAstItem, ESQLCommand, ESQLFunction, ESQLSource } from '@kbn/esql-ast';
import { FunctionDefinition } from '../definitions/types';
import type { FunctionDefinition } from '../definitions/types';
import { getFunctionDefinition, isAssignment, isFunctionItem } from '../shared/helpers';
import type { SuggestionRawDefinition } from './types';
function extractFunctionArgs(args: ESQLAstItem[]): ESQLFunction[] {
return args.flatMap((arg) => (isAssignment(arg) ? arg.args[1] : arg)).filter(isFunctionItem);
@ -71,3 +72,11 @@ export function getSourcesFromCommands(commands: ESQLCommand[], sourceType: 'ind
return sources.length === 1 ? sources[0] : undefined;
}
export function removeQuoteForSuggestedSources(suggestions: SuggestionRawDefinition[]) {
return suggestions.map((d) => ({
...d,
// "text" -> text
text: d.text.startsWith('"') && d.text.endsWith('"') ? d.text.slice(1, -1) : d.text,
}));
}

View file

@ -0,0 +1,48 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { shouldBeQuotedSource } from './helpers';
describe('shouldBeQuotedSource', () => {
it('does not have to be quoted for sources with acceptable characters @-+$', () => {
expect(shouldBeQuotedSource('foo')).toBe(false);
expect(shouldBeQuotedSource('123-test@foo_bar+baz1')).toBe(false);
expect(shouldBeQuotedSource('my-index*')).toBe(false);
expect(shouldBeQuotedSource('my-index$')).toBe(false);
expect(shouldBeQuotedSource('.my-index$')).toBe(false);
});
it(`should be quoted if containing any of special characters [:"=|,[\]/ \t\r\n]`, () => {
expect(shouldBeQuotedSource('foo\ttest')).toBe(true);
expect(shouldBeQuotedSource('foo\rtest')).toBe(true);
expect(shouldBeQuotedSource('foo\ntest')).toBe(true);
expect(shouldBeQuotedSource('foo:test=bar')).toBe(true);
expect(shouldBeQuotedSource('foo|test=bar')).toBe(true);
expect(shouldBeQuotedSource('foo[test]=bar')).toBe(true);
expect(shouldBeQuotedSource('foo/test=bar')).toBe(true);
expect(shouldBeQuotedSource('foo test=bar')).toBe(true);
expect(shouldBeQuotedSource('foo,test-*,abc')).toBe(true);
expect(shouldBeQuotedSource('foo, test-*, abc, xyz')).toBe(true);
expect(shouldBeQuotedSource('foo, test-*, abc, xyz,test123')).toBe(true);
expect(shouldBeQuotedSource('foo,test,xyz')).toBe(true);
expect(
shouldBeQuotedSource('<logstash-{now/M{yyyy.MM}}>,<logstash-{now/d{yyyy.MM.dd|+12:00}}>')
).toBe(true);
expect(shouldBeQuotedSource('`backtick`,``multiple`back``ticks```')).toBe(true);
expect(shouldBeQuotedSource('test,metadata,metaata,.metadata')).toBe(true);
expect(shouldBeQuotedSource('cluster:index')).toBe(true);
expect(shouldBeQuotedSource('cluster:index|pattern')).toBe(true);
expect(shouldBeQuotedSource('cluster:.index')).toBe(true);
expect(shouldBeQuotedSource('cluster*:index*')).toBe(true);
expect(shouldBeQuotedSource('cluster*:*')).toBe(true);
expect(shouldBeQuotedSource('*:index*')).toBe(true);
expect(shouldBeQuotedSource('*:index|pattern')).toBe(true);
expect(shouldBeQuotedSource('*:*')).toBe(true);
expect(shouldBeQuotedSource('*:*,cluster*:index|pattern,i|p')).toBe(true);
expect(shouldBeQuotedSource('index-[dd-mm]')).toBe(true);
});
});

View file

@ -563,6 +563,10 @@ export function isRestartingExpression(text: string) {
return getLastCharFromTrimmed(text) === ',';
}
export function shouldBeQuotedSource(text: string) {
// Based on lexer `fragment UNQUOTED_SOURCE_PART`
return /[:"=|,[\]\/ \t\r\n]/.test(text);
}
export function shouldBeQuotedText(
text: string,
{ dashSupported }: { dashSupported?: boolean } = {}

View file

@ -39,11 +39,13 @@ export const ESQLLang: CustomLangModuleType<ESQLCallbacks> = {
{ open: '(', close: ')' },
{ open: '[', close: ']' },
{ open: `'`, close: `'` },
{ open: '"""', close: '"""' },
{ open: '"', close: '"' },
],
surroundingPairs: [
{ open: '(', close: ')' },
{ open: `'`, close: `'` },
{ open: '"""', close: '"""' },
{ open: '"', close: '"' },
],
},