diff --git a/docs/canvas/canvas-elements.asciidoc b/docs/canvas/canvas-elements.asciidoc index dc605a47de383..1160b735154dc 100644 --- a/docs/canvas/canvas-elements.asciidoc +++ b/docs/canvas/canvas-elements.asciidoc @@ -20,7 +20,9 @@ When you add elements to your workpad, you can: [[add-canvas-element]] === Add elements to your workpad -Choose the elements to display on your workpad, then familiarize yourself with the element using the preconfigured demo data. By default, every element you add to a workpad uses demo data until you change the data source. The demo data includes a small sample data set that you can use to experiment with your element. +Choose the elements to display on your workpad, then familiarize yourself with the element using the preconfigured demo data. By default, most elements use demo data until you change the data source. The demo data includes a small sample data set that you can use to experiment with your element. + +To add a Canvas element: . Click *Add element*. @@ -31,13 +33,26 @@ image::images/canvas-element-select.gif[Canvas elements] . Play around with the default settings and see what the element can do. -TIP: Want to use a different element? You can delete the element by selecting it, clicking the *Element options* icon in the top right, then selecting *Delete*. +To add a map: + +. Click *Embed object*. + +. Select the map you want to add to the workpad. ++ +[role="screenshot"] +image::images/canvas-map-embed.gif[] + +NOTE: Demo data is only supported on Canvas elements. Maps do not support demo data. + +Want to use a different element? You can delete the element by selecting it, clicking the *Element options* icon in the top right, then selecting *Delete*. [float] [[connect-element-data]] -=== Connect the element to your data +=== Connect the Canvas element to your data -When you have finished using the demo data, connect the element to a data source. +When you have finished using the demo data, connect the Canvas element to a data source. + +NOTE: Maps do not support data sources. To change the map data, refer to <>. . Make sure that the element is selected, then select *Data*. @@ -142,7 +157,7 @@ text.align: center; [[configure-auto-refresh-interval]] ==== Change the data auto-refresh interval -Increase or decrease how often your data refreshes on your workpad. +Increase or decrease how often your Canvas element data refreshes on your workpad. . In the top left corner, click the *Control settings* icon. @@ -153,6 +168,17 @@ image::images/canvas-refresh-interval.png[Element data refresh interval] TIP: To manually refresh the data, click the *Refresh data* icon. +[float] +[[canvas-time-range]] +==== Customize map time ranges + +Configure the maps on your workpad for a specific time range. + +From the panel menu, select *Customize time range* to expose a time filter dedicated to the map. + +[role="screenshot"] +image::images/canvas_map-time-filter.gif[] + [float] [[organize-element]] === Organize the elements on your workpad diff --git a/docs/images/canvas-map-embed.gif b/docs/images/canvas-map-embed.gif new file mode 100644 index 0000000000000..eadf521c3b4d1 Binary files /dev/null and b/docs/images/canvas-map-embed.gif differ diff --git a/docs/images/canvas_map-time-filter.gif b/docs/images/canvas_map-time-filter.gif new file mode 100644 index 0000000000000..301d7f4b44158 Binary files /dev/null and b/docs/images/canvas_map-time-filter.gif differ diff --git a/src/legacy/core_plugins/vis_type_timeseries/public/services.ts b/src/legacy/core_plugins/vis_type_timeseries/public/services.ts index c16ed47f54874..64ee897247b89 100644 --- a/src/legacy/core_plugins/vis_type_timeseries/public/services.ts +++ b/src/legacy/core_plugins/vis_type_timeseries/public/services.ts @@ -19,13 +19,13 @@ import { I18nStart, SavedObjectsStart, IUiSettingsClient, CoreStart } from 'src/core/public'; import { createGetterSetter } from '../../../../plugins/kibana_utils/public'; -import { DataPublicPluginStart, FieldFormatsStart } from '../../../../plugins/data/public'; +import { DataPublicPluginStart } from '../../../../plugins/data/public'; export const [getUISettings, setUISettings] = createGetterSetter('UISettings'); -export const [getFieldFormats, setFieldFormats] = createGetterSetter( - 'FieldFormats' -); +export const [getFieldFormats, setFieldFormats] = createGetterSetter< + DataPublicPluginStart['fieldFormats'] +>('FieldFormats'); export const [getSavedObjectsClient, setSavedObjectsClient] = createGetterSetter( 'SavedObjectsClient' diff --git a/src/plugins/data/public/autocomplete/autocomplete_service.ts b/src/plugins/data/public/autocomplete/autocomplete_service.ts index 78bd2ec85f477..bc557f31f7466 100644 --- a/src/plugins/data/public/autocomplete/autocomplete_service.ts +++ b/src/plugins/data/public/autocomplete/autocomplete_service.ts @@ -18,26 +18,23 @@ */ import { CoreSetup } from 'src/core/public'; -import { QuerySuggestionsGetFn } from './providers/query_suggestion_provider'; +import { QuerySuggestionGetFn } from './providers/query_suggestion_provider'; import { setupValueSuggestionProvider, ValueSuggestionsGetFn, } from './providers/value_suggestion_provider'; export class AutocompleteService { - private readonly querySuggestionProviders: Map = new Map(); + private readonly querySuggestionProviders: Map = new Map(); private getValueSuggestions?: ValueSuggestionsGetFn; - private addQuerySuggestionProvider = ( - language: string, - provider: QuerySuggestionsGetFn - ): void => { + private addQuerySuggestionProvider = (language: string, provider: QuerySuggestionGetFn): void => { if (language && provider) { this.querySuggestionProviders.set(language, provider); } }; - private getQuerySuggestions: QuerySuggestionsGetFn = args => { + private getQuerySuggestions: QuerySuggestionGetFn = args => { const { language } = args; const provider = this.querySuggestionProviders.get(language); diff --git a/src/plugins/data/public/autocomplete/index.ts b/src/plugins/data/public/autocomplete/index.ts index c2b21e84b7a38..d5bf4e2fd211b 100644 --- a/src/plugins/data/public/autocomplete/index.ts +++ b/src/plugins/data/public/autocomplete/index.ts @@ -16,7 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -import * as autocomplete from './static'; -export { AutocompleteService, AutocompleteSetup, AutocompleteStart } from './autocomplete_service'; -export { autocomplete }; +export { + QuerySuggestion, + QuerySuggestionTypes, + QuerySuggestionGetFn, + QuerySuggestionGetFnArgs, + QuerySuggestionBasic, + QuerySuggestionField, +} from './providers/query_suggestion_provider'; + +export { AutocompleteService, AutocompleteSetup, AutocompleteStart } from './autocomplete_service'; diff --git a/src/plugins/data/public/autocomplete/providers/query_suggestion_provider.ts b/src/plugins/data/public/autocomplete/providers/query_suggestion_provider.ts index 94054ed56f42a..16500ac9e239a 100644 --- a/src/plugins/data/public/autocomplete/providers/query_suggestion_provider.ts +++ b/src/plugins/data/public/autocomplete/providers/query_suggestion_provider.ts @@ -19,7 +19,7 @@ import { IFieldType, IIndexPattern } from '../../../common/index_patterns'; -export enum QuerySuggestionsTypes { +export enum QuerySuggestionTypes { Field = 'field', Value = 'value', Operator = 'operator', @@ -27,12 +27,12 @@ export enum QuerySuggestionsTypes { RecentSearch = 'recentSearch', } -export type QuerySuggestionsGetFn = ( - args: QuerySuggestionsGetFnArgs +export type QuerySuggestionGetFn = ( + args: QuerySuggestionGetFnArgs ) => Promise | undefined; /** @public **/ -export interface QuerySuggestionsGetFnArgs { +export interface QuerySuggestionGetFnArgs { language: string; indexPatterns: IIndexPattern[]; query: string; @@ -43,8 +43,8 @@ export interface QuerySuggestionsGetFnArgs { } /** @public **/ -export interface BasicQuerySuggestion { - type: QuerySuggestionsTypes; +export interface QuerySuggestionBasic { + type: QuerySuggestionTypes; description?: string | JSX.Element; end: number; start: number; @@ -53,10 +53,10 @@ export interface BasicQuerySuggestion { } /** @public **/ -export interface FieldQuerySuggestion extends BasicQuerySuggestion { - type: QuerySuggestionsTypes.Field; +export interface QuerySuggestionField extends QuerySuggestionBasic { + type: QuerySuggestionTypes.Field; field: IFieldType; } /** @public **/ -export type QuerySuggestion = BasicQuerySuggestion | FieldQuerySuggestion; +export type QuerySuggestion = QuerySuggestionBasic | QuerySuggestionField; diff --git a/src/plugins/data/public/autocomplete/static.ts b/src/plugins/data/public/autocomplete/static.ts deleted file mode 100644 index 7d627486c6d65..0000000000000 --- a/src/plugins/data/public/autocomplete/static.ts +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export { - QuerySuggestion, - QuerySuggestionsTypes, - QuerySuggestionsGetFn, - QuerySuggestionsGetFnArgs, - BasicQuerySuggestion, - FieldQuerySuggestion, -} from './providers/query_suggestion_provider'; diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index d861a1ee0dd83..6c14739d42bf1 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -104,7 +104,17 @@ export { FieldFormatConfig, FieldFormatId, } from '../common'; -export { autocomplete } from './autocomplete'; + +export { + QuerySuggestion, + QuerySuggestionTypes, + QuerySuggestionGetFn, + QuerySuggestionGetFnArgs, + QuerySuggestionBasic, + QuerySuggestionField, +} from './autocomplete'; + +export * from './field_formats'; export * from './index_patterns'; export * from './search'; export * from './query'; diff --git a/src/plugins/data/public/ui/query_string_input/query_string_input.tsx b/src/plugins/data/public/ui/query_string_input/query_string_input.tsx index 7a8c0f7269fa1..f8cb4050efdfb 100644 --- a/src/plugins/data/public/ui/query_string_input/query_string_input.tsx +++ b/src/plugins/data/public/ui/query_string_input/query_string_input.tsx @@ -35,7 +35,6 @@ import { InjectedIntl, injectI18n, FormattedMessage } from '@kbn/i18n/react'; import { debounce, compact, isEqual } from 'lodash'; import { Toast } from 'src/core/public'; import { - autocomplete, IDataPluginServices, IIndexPattern, PersistedLog, @@ -46,6 +45,8 @@ import { getQueryLog, Query, } from '../..'; +import { QuerySuggestion, QuerySuggestionTypes } from '../../autocomplete'; + import { withKibana, KibanaReactContextValue, toMountPoint } from '../../../../kibana_react/public'; import { fetchIndexPatterns } from './fetch_index_patterns'; import { QueryLanguageSwitcher } from './language_switcher'; @@ -70,7 +71,7 @@ interface Props { interface State { isSuggestionsVisible: boolean; index: number | null; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; suggestionLimit: number; selectionStart: number | null; selectionEnd: number | null; @@ -191,7 +192,7 @@ export class QueryStringInputUI extends Component { const text = toUser(recentSearch); const start = 0; const end = query.length; - return { type: autocomplete.QuerySuggestionsTypes.RecentSearch, text, start, end }; + return { type: QuerySuggestionTypes.RecentSearch, text, start, end }; }); }; @@ -317,7 +318,7 @@ export class QueryStringInputUI extends Component { } }; - private selectSuggestion = (suggestion: autocomplete.QuerySuggestion) => { + private selectSuggestion = (suggestion: QuerySuggestion) => { if (!this.inputRef) { return; } @@ -341,13 +342,13 @@ export class QueryStringInputUI extends Component { selectionEnd: start + (cursorIndex ? cursorIndex : text.length), }); - if (type === autocomplete.QuerySuggestionsTypes.RecentSearch) { + if (type === QuerySuggestionTypes.RecentSearch) { this.setState({ isSuggestionsVisible: false, index: null }); this.onSubmit({ query: newQueryString, language: this.props.query.language }); } }; - private handleNestedFieldSyntaxNotification = (suggestion: autocomplete.QuerySuggestion) => { + private handleNestedFieldSyntaxNotification = (suggestion: QuerySuggestion) => { if ( 'field' in suggestion && suggestion.field.subType && @@ -449,7 +450,7 @@ export class QueryStringInputUI extends Component { } }; - private onClickSuggestion = (suggestion: autocomplete.QuerySuggestion) => { + private onClickSuggestion = (suggestion: QuerySuggestion) => { if (!this.inputRef) { return; } diff --git a/src/plugins/data/public/ui/typeahead/suggestion_component.test.tsx b/src/plugins/data/public/ui/typeahead/suggestion_component.test.tsx index ba92be8947ea5..9fe33b003527e 100644 --- a/src/plugins/data/public/ui/typeahead/suggestion_component.test.tsx +++ b/src/plugins/data/public/ui/typeahead/suggestion_component.test.tsx @@ -19,19 +19,19 @@ import { mount, shallow } from 'enzyme'; import React from 'react'; -import { autocomplete } from '../..'; +import { QuerySuggestion, QuerySuggestionTypes } from '../../autocomplete'; import { SuggestionComponent } from './suggestion_component'; const noop = () => { return; }; -const mockSuggestion: autocomplete.QuerySuggestion = { +const mockSuggestion: QuerySuggestion = { description: 'This is not a helpful suggestion', end: 0, start: 42, text: 'as promised, not helpful', - type: autocomplete.QuerySuggestionsTypes.Value, + type: QuerySuggestionTypes.Value, }; describe('SuggestionComponent', () => { diff --git a/src/plugins/data/public/ui/typeahead/suggestion_component.tsx b/src/plugins/data/public/ui/typeahead/suggestion_component.tsx index 1d2ac8dee1a8a..4c46c4f802e6a 100644 --- a/src/plugins/data/public/ui/typeahead/suggestion_component.tsx +++ b/src/plugins/data/public/ui/typeahead/suggestion_component.tsx @@ -20,7 +20,7 @@ import { EuiIcon } from '@elastic/eui'; import classNames from 'classnames'; import React, { FunctionComponent } from 'react'; -import { autocomplete } from '../..'; +import { QuerySuggestion } from '../../autocomplete'; function getEuiIconType(type: string) { switch (type) { @@ -40,10 +40,10 @@ function getEuiIconType(type: string) { } interface Props { - onClick: (suggestion: autocomplete.QuerySuggestion) => void; + onClick: (suggestion: QuerySuggestion) => void; onMouseEnter: () => void; selected: boolean; - suggestion: autocomplete.QuerySuggestion; + suggestion: QuerySuggestion; innerRef: (node: HTMLDivElement) => void; ariaId: string; } diff --git a/src/plugins/data/public/ui/typeahead/suggestions_component.test.tsx b/src/plugins/data/public/ui/typeahead/suggestions_component.test.tsx index eebe438025949..b26582810ad4a 100644 --- a/src/plugins/data/public/ui/typeahead/suggestions_component.test.tsx +++ b/src/plugins/data/public/ui/typeahead/suggestions_component.test.tsx @@ -19,7 +19,7 @@ import { mount, shallow } from 'enzyme'; import React from 'react'; -import { autocomplete } from '../..'; +import { QuerySuggestion, QuerySuggestionTypes } from '../../autocomplete'; import { SuggestionComponent } from './suggestion_component'; import { SuggestionsComponent } from './suggestions_component'; @@ -27,20 +27,20 @@ const noop = () => { return; }; -const mockSuggestions: autocomplete.QuerySuggestion[] = [ +const mockSuggestions: QuerySuggestion[] = [ { description: 'This is not a helpful suggestion', end: 0, start: 42, text: 'as promised, not helpful', - type: autocomplete.QuerySuggestionsTypes.Value, + type: QuerySuggestionTypes.Value, }, { description: 'This is another unhelpful suggestion', end: 0, start: 42, text: 'yep', - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, }, ]; diff --git a/src/plugins/data/public/ui/typeahead/suggestions_component.tsx b/src/plugins/data/public/ui/typeahead/suggestions_component.tsx index b37a2e479e874..375bc63a2318c 100644 --- a/src/plugins/data/public/ui/typeahead/suggestions_component.tsx +++ b/src/plugins/data/public/ui/typeahead/suggestions_component.tsx @@ -19,15 +19,15 @@ import { isEmpty } from 'lodash'; import React, { Component } from 'react'; -import { autocomplete } from '../..'; +import { QuerySuggestion } from '../..'; import { SuggestionComponent } from './suggestion_component'; interface Props { index: number | null; - onClick: (suggestion: autocomplete.QuerySuggestion) => void; + onClick: (suggestion: QuerySuggestion) => void; onMouseEnter: (index: number) => void; show: boolean; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; loadMore: () => void; } diff --git a/x-pack/legacy/plugins/alerting/server/alerts_client.test.ts b/x-pack/legacy/plugins/alerting/server/alerts_client.test.ts index f9d1d97a521fe..e5c4daef88e94 100644 --- a/x-pack/legacy/plugins/alerting/server/alerts_client.test.ts +++ b/x-pack/legacy/plugins/alerting/server/alerts_client.test.ts @@ -79,15 +79,20 @@ function getMockData(overwrites: Record = {}) { } describe('create()', () => { - test('creates an alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - const data = getMockData(); - alertTypeRegistry.get.mockReturnValueOnce({ + let alertsClient: AlertsClient; + + beforeEach(() => { + alertsClient = new AlertsClient(alertsClientParams); + alertTypeRegistry.get.mockReturnValue({ id: '123', name: 'Test', actionGroups: ['default'], async executor() {}, }); + }); + + test('creates an alert', async () => { + const data = getMockData(); savedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { @@ -263,7 +268,6 @@ describe('create()', () => { }); test('creates an alert with multiple actions', async () => { - const alertsClient = new AlertsClient(alertsClientParams); const data = getMockData({ actions: [ { @@ -289,12 +293,6 @@ describe('create()', () => { }, ], }); - alertTypeRegistry.get.mockReturnValueOnce({ - id: '123', - name: 'Test', - actionGroups: ['default'], - async executor() {}, - }); savedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { @@ -446,14 +444,7 @@ describe('create()', () => { }); test('creates a disabled alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); const data = getMockData({ enabled: false }); - alertTypeRegistry.get.mockReturnValueOnce({ - id: '123', - name: 'Test', - actionGroups: ['default'], - async executor() {}, - }); savedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { @@ -527,9 +518,8 @@ describe('create()', () => { }); test('should validate params', async () => { - const alertsClient = new AlertsClient(alertsClientParams); const data = getMockData(); - alertTypeRegistry.get.mockReturnValueOnce({ + alertTypeRegistry.get.mockReturnValue({ id: '123', name: 'Test', actionGroups: [], @@ -547,14 +537,7 @@ describe('create()', () => { }); test('throws error if loading actions fails', async () => { - const alertsClient = new AlertsClient(alertsClientParams); const data = getMockData(); - alertTypeRegistry.get.mockReturnValueOnce({ - id: '123', - name: 'Test', - actionGroups: ['default'], - async executor() {}, - }); savedObjectsClient.bulkGet.mockRejectedValueOnce(new Error('Test Error')); await expect(alertsClient.create({ data })).rejects.toThrowErrorMatchingInlineSnapshot( `"Test Error"` @@ -564,14 +547,7 @@ describe('create()', () => { }); test('throws error if create saved object fails', async () => { - const alertsClient = new AlertsClient(alertsClientParams); const data = getMockData(); - alertTypeRegistry.get.mockReturnValueOnce({ - id: '123', - name: 'Test', - actionGroups: ['default'], - async executor() {}, - }); savedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { @@ -592,14 +568,7 @@ describe('create()', () => { }); test('attempts to remove saved object if scheduling failed', async () => { - const alertsClient = new AlertsClient(alertsClientParams); const data = getMockData(); - alertTypeRegistry.get.mockReturnValueOnce({ - id: '123', - name: 'Test', - actionGroups: ['default'], - async executor() {}, - }); savedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { @@ -655,14 +624,7 @@ describe('create()', () => { }); test('returns task manager error if cleanup fails, logs to console', async () => { - const alertsClient = new AlertsClient(alertsClientParams); const data = getMockData(); - alertTypeRegistry.get.mockReturnValueOnce({ - id: '123', - name: 'Test', - actionGroups: ['default'], - async executor() {}, - }); savedObjectsClient.bulkGet.mockResolvedValueOnce({ saved_objects: [ { @@ -714,7 +676,6 @@ describe('create()', () => { }); test('throws an error if alert type not registerd', async () => { - const alertsClient = new AlertsClient(alertsClientParams); const data = getMockData(); alertTypeRegistry.get.mockImplementation(() => { throw new Error('Invalid type'); @@ -725,14 +686,7 @@ describe('create()', () => { }); test('calls the API key function', async () => { - const alertsClient = new AlertsClient(alertsClientParams); const data = getMockData(); - alertTypeRegistry.get.mockReturnValueOnce({ - id: '123', - name: 'Test', - actionGroups: ['default'], - async executor() {}, - }); alertsClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '123', api_key: 'abc' }, @@ -845,23 +799,141 @@ describe('create()', () => { } ); }); -}); -describe('enable()', () => { - test('enables an alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({ + test(`doesn't create API key for disabled alerts`, async () => { + const data = getMockData({ enabled: false }); + savedObjectsClient.bulkGet.mockResolvedValueOnce({ + saved_objects: [ + { + id: '1', + type: 'action', + attributes: { + actionTypeId: 'test', + }, + references: [], + }, + ], + }); + savedObjectsClient.create.mockResolvedValueOnce({ id: '1', type: 'alert', attributes: { + alertTypeId: '123', schedule: { interval: '10s' }, - alertTypeId: '2', - enabled: false, + params: { + bar: true, + }, + actions: [ + { + group: 'default', + actionRef: 'action_0', + actionTypeId: 'test', + params: { + foo: true, + }, + }, + ], }, - version: '123', - references: [], + references: [ + { + name: 'action_0', + type: 'action', + id: '1', + }, + ], }); taskManager.schedule.mockResolvedValueOnce({ + id: 'task-123', + taskType: 'alerting:123', + scheduledAt: new Date(), + attempts: 1, + status: TaskStatus.Idle, + runAt: new Date(), + startedAt: null, + retryAt: null, + state: {}, + params: {}, + ownerId: null, + }); + savedObjectsClient.update.mockResolvedValueOnce({ + id: '1', + type: 'alert', + attributes: { + scheduledTaskId: 'task-123', + }, + references: [ + { + id: '1', + name: 'action_0', + type: 'action', + }, + ], + }); + await alertsClient.create({ data }); + + expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); + expect(savedObjectsClient.create).toHaveBeenCalledWith( + 'alert', + { + actions: [ + { + actionRef: 'action_0', + group: 'default', + actionTypeId: 'test', + params: { foo: true }, + }, + ], + alertTypeId: '123', + consumer: 'bar', + name: 'abc', + params: { bar: true }, + apiKey: null, + apiKeyOwner: null, + createdBy: 'elastic', + createdAt: '2019-02-12T21:01:22.479Z', + updatedBy: 'elastic', + enabled: false, + schedule: { interval: '10s' }, + throttle: null, + muteAll: false, + mutedInstanceIds: [], + tags: ['foo'], + }, + { + references: [ + { + id: '1', + name: 'action_0', + type: 'action', + }, + ], + } + ); + }); +}); + +describe('enable()', () => { + let alertsClient: AlertsClient; + const existingAlert = { + id: '1', + type: 'alert', + attributes: { + schedule: { interval: '10s' }, + alertTypeId: '2', + enabled: false, + }, + version: '123', + references: [], + }; + + beforeEach(() => { + alertsClient = new AlertsClient(alertsClientParams); + encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingAlert); + savedObjectsClient.get.mockResolvedValue(existingAlert); + alertsClientParams.createAPIKey.mockResolvedValue({ + apiKeysEnabled: false, + }); + taskManager.schedule.mockResolvedValue({ id: 'task-123', scheduledAt: new Date(), attempts: 0, @@ -874,8 +946,16 @@ describe('enable()', () => { retryAt: null, ownerId: null, }); + }); + test('enables an alert', async () => { await alertsClient.enable({ id: '1' }); + expect(savedObjectsClient.get).not.toHaveBeenCalled(); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { + namespace: 'default', + }); + expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); + expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); expect(savedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', @@ -891,9 +971,6 @@ describe('enable()', () => { version: '123', } ); - expect(savedObjectsClient.update).toHaveBeenCalledWith('alert', '1', { - scheduledTaskId: 'task-123', - }); expect(taskManager.schedule).toHaveBeenCalledWith({ taskType: `alerting:2`, params: { @@ -907,52 +984,45 @@ describe('enable()', () => { }, scope: ['alerting'], }); + expect(savedObjectsClient.update).toHaveBeenCalledWith('alert', '1', { + scheduledTaskId: 'task-123', + }); }); - test(`doesn't enable already enabled alerts`, async () => { - const alertsClient = new AlertsClient(alertsClientParams); - encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({ - id: '1', - type: 'alert', + test('invalidates API key if ever one existed prior to updating', async () => { + encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue({ + ...existingAlert, attributes: { - schedule: { interval: '10s' }, - alertTypeId: '2', - enabled: true, + ...existingAlert.attributes, + apiKey: Buffer.from('123:abc').toString('base64'), }, - references: [], }); await alertsClient.enable({ id: '1' }); - expect(taskManager.schedule).toHaveBeenCalledTimes(0); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(0); + expect(savedObjectsClient.get).not.toHaveBeenCalled(); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { + namespace: 'default', + }); + expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' }); }); - test('calls the API key function', async () => { - const alertsClient = new AlertsClient(alertsClientParams); + test(`doesn't enable already enabled alerts`, async () => { encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({ - id: '1', - type: 'alert', + ...existingAlert, attributes: { - schedule: { interval: '10s' }, - alertTypeId: '2', - enabled: false, + ...existingAlert.attributes, + enabled: true, }, - version: '123', - references: [], - }); - taskManager.schedule.mockResolvedValueOnce({ - id: 'task-123', - scheduledAt: new Date(), - attempts: 0, - status: TaskStatus.Idle, - runAt: new Date(), - state: {}, - params: {}, - taskType: '', - startedAt: null, - retryAt: null, - ownerId: null, }); + + await alertsClient.enable({ id: '1' }); + expect(alertsClientParams.getUserName).not.toHaveBeenCalled(); + expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); + expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(taskManager.schedule).not.toHaveBeenCalled(); + }); + + test('sets API key when createAPIKey returns one', async () => { alertsClientParams.createAPIKey.mockResolvedValueOnce({ apiKeysEnabled: true, result: { id: '123', api_key: 'abc' }, @@ -974,77 +1044,136 @@ describe('enable()', () => { version: '123', } ); - expect(savedObjectsClient.update).toHaveBeenCalledWith('alert', '1', { - scheduledTaskId: 'task-123', - }); - expect(taskManager.schedule).toHaveBeenCalledWith({ - taskType: `alerting:2`, - params: { - alertId: '1', - spaceId: 'default', - }, - state: { - alertInstances: {}, - alertTypeState: {}, - previousStartedAt: null, - }, - scope: ['alerting'], - }); }); - test('swallows error when invalidate API key throws', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - alertsClientParams.invalidateAPIKey.mockRejectedValueOnce(new Error('Fail')); - encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({ - id: '1', - type: 'alert', + test('falls back when failing to getDecryptedAsInternalUser', async () => { + encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); + + await alertsClient.enable({ id: '1' }); + expect(savedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + 'enable(): Failed to load API key to invalidate on alert 1: Fail' + ); + }); + + test('throws error when failing to load the saved object using SOC', async () => { + encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValue(new Error('Fail')); + savedObjectsClient.get.mockRejectedValueOnce(new Error('Fail to get')); + + await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + `"Fail to get"` + ); + expect(alertsClientParams.getUserName).not.toHaveBeenCalled(); + expect(alertsClientParams.createAPIKey).not.toHaveBeenCalled(); + expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(taskManager.schedule).not.toHaveBeenCalled(); + }); + + test('throws error when failing to update the first time', async () => { + savedObjectsClient.update.mockRejectedValueOnce(new Error('Fail to update')); + + await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + `"Fail to update"` + ); + expect(alertsClientParams.getUserName).toHaveBeenCalled(); + expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); + expect(savedObjectsClient.update).toHaveBeenCalledTimes(1); + expect(taskManager.schedule).not.toHaveBeenCalled(); + }); + + test('throws error when failing to update the second time', async () => { + savedObjectsClient.update.mockResolvedValueOnce({ + ...existingAlert, attributes: { - schedule: { interval: '10s' }, - alertTypeId: '2', - enabled: false, - apiKey: Buffer.from('123:abc').toString('base64'), + ...existingAlert.attributes, + enabled: true, }, - version: '123', - references: [], - }); - taskManager.schedule.mockResolvedValueOnce({ - id: 'task-123', - scheduledAt: new Date(), - attempts: 0, - status: TaskStatus.Idle, - runAt: new Date(), - state: {}, - params: {}, - taskType: '', - startedAt: null, - retryAt: null, - ownerId: null, }); + savedObjectsClient.update.mockRejectedValueOnce(new Error('Fail to update second time')); - await alertsClient.enable({ id: '1' }); - expect(alertsClientParams.logger.error).toHaveBeenCalledWith( - 'Failed to invalidate API Key: Fail' + await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + `"Fail to update second time"` ); + expect(alertsClientParams.getUserName).toHaveBeenCalled(); + expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); + expect(savedObjectsClient.update).toHaveBeenCalledTimes(2); + expect(taskManager.schedule).toHaveBeenCalled(); + }); + + test('throws error when failing to schedule task', async () => { + taskManager.schedule.mockRejectedValueOnce(new Error('Fail to schedule')); + + await expect(alertsClient.enable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + `"Fail to schedule"` + ); + expect(alertsClientParams.getUserName).toHaveBeenCalled(); + expect(alertsClientParams.createAPIKey).toHaveBeenCalled(); + expect(savedObjectsClient.update).toHaveBeenCalled(); }); }); describe('disable()', () => { + let alertsClient: AlertsClient; + const existingAlert = { + id: '1', + type: 'alert', + attributes: { + schedule: { interval: '10s' }, + alertTypeId: '2', + enabled: true, + scheduledTaskId: 'task-123', + }, + version: '123', + references: [], + }; + const existingDecryptedAlert = { + ...existingAlert, + attributes: { + ...existingAlert.attributes, + apiKey: Buffer.from('123:abc').toString('base64'), + }, + }; + + beforeEach(() => { + alertsClient = new AlertsClient(alertsClientParams); + savedObjectsClient.get.mockResolvedValue(existingAlert); + encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValue(existingDecryptedAlert); + }); + test('disables an alert', async () => { - const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ - id: '1', - type: 'alert', - attributes: { + await alertsClient.disable({ id: '1' }); + expect(savedObjectsClient.get).not.toHaveBeenCalled(); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { + namespace: 'default', + }); + expect(savedObjectsClient.update).toHaveBeenCalledWith( + 'alert', + '1', + { schedule: { interval: '10s' }, alertTypeId: '2', - enabled: true, - scheduledTaskId: 'task-123', + apiKey: null, + apiKeyOwner: null, + enabled: false, + scheduledTaskId: null, + updatedBy: 'elastic', }, - version: '123', - references: [], - }); + { + version: '123', + } + ); + expect(taskManager.remove).toHaveBeenCalledWith('task-123'); + expect(alertsClientParams.invalidateAPIKey).toHaveBeenCalledWith({ id: '123' }); + }); + + test('falls back when getDecryptedAsInternalUser throws an error', async () => { + encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail')); await alertsClient.disable({ id: '1' }); + expect(savedObjectsClient.get).toHaveBeenCalledWith('alert', '1'); + expect(encryptedSavedObjects.getDecryptedAsInternalUser).toHaveBeenCalledWith('alert', '1', { + namespace: 'default', + }); expect(savedObjectsClient.update).toHaveBeenCalledWith( 'alert', '1', @@ -1062,25 +1191,66 @@ describe('disable()', () => { } ); expect(taskManager.remove).toHaveBeenCalledWith('task-123'); + expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); }); test(`doesn't disable already disabled alerts`, async () => { - const alertsClient = new AlertsClient(alertsClientParams); - savedObjectsClient.get.mockResolvedValueOnce({ - id: '1', - type: 'alert', + encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce({ + ...existingDecryptedAlert, attributes: { - schedule: { interval: '10s' }, - alertTypeId: '2', + ...existingDecryptedAlert.attributes, enabled: false, - scheduledTaskId: 'task-123', }, - references: [], }); await alertsClient.disable({ id: '1' }); - expect(savedObjectsClient.update).toHaveBeenCalledTimes(0); - expect(taskManager.remove).toHaveBeenCalledTimes(0); + expect(savedObjectsClient.update).not.toHaveBeenCalled(); + expect(taskManager.remove).not.toHaveBeenCalled(); + expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); + }); + + test(`doesn't invalidate when no API key is used`, async () => { + encryptedSavedObjects.getDecryptedAsInternalUser.mockResolvedValueOnce(existingAlert); + + await alertsClient.disable({ id: '1' }); + expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); + }); + + test('swallows error when failing to load decrypted saved object', async () => { + encryptedSavedObjects.getDecryptedAsInternalUser.mockRejectedValueOnce(new Error('Fail')); + + await alertsClient.disable({ id: '1' }); + expect(savedObjectsClient.update).toHaveBeenCalled(); + expect(taskManager.remove).toHaveBeenCalled(); + expect(alertsClientParams.invalidateAPIKey).not.toHaveBeenCalled(); + expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + 'disable(): Failed to load API key to invalidate on alert 1: Fail' + ); + }); + + test('throws when savedObjectsClient update fails', async () => { + savedObjectsClient.update.mockRejectedValueOnce(new Error('Failed to update')); + + await expect(alertsClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + `"Failed to update"` + ); + }); + + test('swallows error when invalidate API key throws', async () => { + alertsClientParams.invalidateAPIKey.mockRejectedValueOnce(new Error('Fail')); + + await alertsClient.disable({ id: '1' }); + expect(alertsClientParams.logger.error).toHaveBeenCalledWith( + 'Failed to invalidate API Key: Fail' + ); + }); + + test('throws when failing to remove task from task manager', async () => { + taskManager.remove.mockRejectedValueOnce(new Error('Failed to remove task')); + + await expect(alertsClient.disable({ id: '1' })).rejects.toThrowErrorMatchingInlineSnapshot( + `"Failed to remove task"` + ); }); }); diff --git a/x-pack/legacy/plugins/alerting/server/alerts_client.ts b/x-pack/legacy/plugins/alerting/server/alerts_client.ts index f6841ed5a0e46..d54560ff5b776 100644 --- a/x-pack/legacy/plugins/alerting/server/alerts_client.ts +++ b/x-pack/legacy/plugins/alerting/server/alerts_client.ts @@ -152,13 +152,14 @@ export class AlertsClient { const alertType = this.alertTypeRegistry.get(data.alertTypeId); const validatedAlertTypeParams = validateAlertTypeParams(alertType, data.params); const username = await this.getUserName(); + const createdAPIKey = data.enabled ? await this.createAPIKey() : null; this.validateActions(alertType, data.actions); const { references, actions } = await this.denormalizeActions(data.actions); const rawAlert: RawAlert = { ...data, - ...this.apiKeyAsAlertAttributes(await this.createAPIKey(), username), + ...this.apiKeyAsAlertAttributes(createdAPIKey, username), actions, createdBy: username, updatedBy: username, @@ -329,10 +330,10 @@ export class AlertsClient { } private apiKeyAsAlertAttributes( - apiKey: CreateAPIKeyResult, + apiKey: CreateAPIKeyResult | null, username: string | null ): Pick { - return apiKey.apiKeysEnabled + return apiKey && apiKey.apiKeysEnabled ? { apiKeyOwner: username, apiKey: Buffer.from(`${apiKey.result.id}:${apiKey.result.api_key}`).toString('base64'), @@ -385,12 +386,27 @@ export class AlertsClient { } public async enable({ id }: { id: string }) { - const { - version, - attributes, - } = await this.encryptedSavedObjectsPlugin.getDecryptedAsInternalUser('alert', id, { - namespace: this.namespace, - }); + let apiKeyToInvalidate: string | null = null; + let attributes: RawAlert; + let version: string | undefined; + + try { + const decryptedAlert = await this.encryptedSavedObjectsPlugin.getDecryptedAsInternalUser< + RawAlert + >('alert', id, { namespace: this.namespace }); + apiKeyToInvalidate = decryptedAlert.attributes.apiKey; + attributes = decryptedAlert.attributes; + version = decryptedAlert.version; + } catch (e) { + // We'll skip invalidating the API key since we failed to load the decrypted saved object + this.logger.error( + `enable(): Failed to load API key to invalidate on alert ${id}: ${e.message}` + ); + // Still attempt to load the attributes and version using SOC + const alert = await this.savedObjectsClient.get('alert', id); + attributes = alert.attributes; + version = alert.version; + } if (attributes.enabled === false) { const username = await this.getUserName(); @@ -407,12 +423,35 @@ export class AlertsClient { ); const scheduledTask = await this.scheduleAlert(id, attributes.alertTypeId); await this.savedObjectsClient.update('alert', id, { scheduledTaskId: scheduledTask.id }); - await this.invalidateApiKey({ apiKey: attributes.apiKey }); + if (apiKeyToInvalidate) { + await this.invalidateApiKey({ apiKey: apiKeyToInvalidate }); + } } } public async disable({ id }: { id: string }) { - const { attributes, version } = await this.savedObjectsClient.get('alert', id); + let apiKeyToInvalidate: string | null = null; + let attributes: RawAlert; + let version: string | undefined; + + try { + const decryptedAlert = await this.encryptedSavedObjectsPlugin.getDecryptedAsInternalUser< + RawAlert + >('alert', id, { namespace: this.namespace }); + apiKeyToInvalidate = decryptedAlert.attributes.apiKey; + attributes = decryptedAlert.attributes; + version = decryptedAlert.version; + } catch (e) { + // We'll skip invalidating the API key since we failed to load the decrypted saved object + this.logger.error( + `disable(): Failed to load API key to invalidate on alert ${id}: ${e.message}` + ); + // Still attempt to load the attributes and version using SOC + const alert = await this.savedObjectsClient.get('alert', id); + attributes = alert.attributes; + version = alert.version; + } + if (attributes.enabled === true) { await this.savedObjectsClient.update( 'alert', @@ -427,7 +466,11 @@ export class AlertsClient { }, { version } ); - await this.taskManager.remove(attributes.scheduledTaskId); + + await Promise.all([ + attributes.scheduledTaskId ? this.taskManager.remove(attributes.scheduledTaskId) : null, + apiKeyToInvalidate ? this.invalidateApiKey({ apiKey: apiKeyToInvalidate }) : null, + ]); } } diff --git a/x-pack/legacy/plugins/apm/public/components/shared/KueryBar/index.tsx b/x-pack/legacy/plugins/apm/public/components/shared/KueryBar/index.tsx index 32432b7b85ef6..5bdc63ab47aa5 100644 --- a/x-pack/legacy/plugins/apm/public/components/shared/KueryBar/index.tsx +++ b/x-pack/legacy/plugins/apm/public/components/shared/KueryBar/index.tsx @@ -18,7 +18,7 @@ import { history } from '../../../utils/history'; import { useApmPluginContext } from '../../../hooks/useApmPluginContext'; import { useDynamicIndexPattern } from '../../../hooks/useDynamicIndexPattern'; import { - autocomplete, + QuerySuggestion, esKuery, IIndexPattern } from '../../../../../../../../src/plugins/data/public'; @@ -28,7 +28,7 @@ const Container = styled.div` `; interface State { - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; isLoadingSuggestions: boolean; } diff --git a/x-pack/legacy/plugins/beats_management/public/components/autocomplete_field/index.tsx b/x-pack/legacy/plugins/beats_management/public/components/autocomplete_field/index.tsx index f3e0f3dfbdae7..70b7bd3df0662 100644 --- a/x-pack/legacy/plugins/beats_management/public/components/autocomplete_field/index.tsx +++ b/x-pack/legacy/plugins/beats_management/public/components/autocomplete_field/index.tsx @@ -13,7 +13,7 @@ import { import React from 'react'; import styled from 'styled-components'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../src/plugins/data/public'; import { composeStateUpdaters } from '../../utils/typed_react'; import { SuggestionItem } from './suggestion_item'; @@ -25,7 +25,7 @@ interface AutocompleteFieldProps { onSubmit?: (value: string) => void; onChange?: (value: string) => void; placeholder?: string; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; value: string; } diff --git a/x-pack/legacy/plugins/beats_management/public/components/autocomplete_field/suggestion_item.tsx b/x-pack/legacy/plugins/beats_management/public/components/autocomplete_field/suggestion_item.tsx index 0132667b9e510..690d471b306ab 100644 --- a/x-pack/legacy/plugins/beats_management/public/components/autocomplete_field/suggestion_item.tsx +++ b/x-pack/legacy/plugins/beats_management/public/components/autocomplete_field/suggestion_item.tsx @@ -9,13 +9,13 @@ import { tint } from 'polished'; import React from 'react'; import styled from 'styled-components'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../src/plugins/data/public'; interface SuggestionItemProps { isSelected?: boolean; onClick?: React.MouseEventHandler; onMouseEnter?: React.MouseEventHandler; - suggestion: autocomplete.QuerySuggestion; + suggestion: QuerySuggestion; } export const SuggestionItem: React.FC = props => { diff --git a/x-pack/legacy/plugins/beats_management/public/components/table/table.tsx b/x-pack/legacy/plugins/beats_management/public/components/table/table.tsx index d1cbc0888dca8..534da6541b683 100644 --- a/x-pack/legacy/plugins/beats_management/public/components/table/table.tsx +++ b/x-pack/legacy/plugins/beats_management/public/components/table/table.tsx @@ -8,7 +8,7 @@ import { EuiBasicTable, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eu import { i18n } from '@kbn/i18n'; import React from 'react'; import styled from 'styled-components'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../src/plugins/data/public'; import { TABLE_CONFIG } from '../../../common/constants'; import { AutocompleteField } from '../autocomplete_field/index'; import { ControlSchema } from './action_schema'; @@ -31,7 +31,7 @@ export interface KueryBarProps { loadSuggestions: (value: string, cursorPosition: number, maxCount?: number) => void; onChange?: (value: string) => void; onSubmit?: (value: string) => void; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; value: string; } diff --git a/x-pack/legacy/plugins/beats_management/public/containers/with_kuery_autocompletion.tsx b/x-pack/legacy/plugins/beats_management/public/containers/with_kuery_autocompletion.tsx index db73a7cb38c11..66d52b8dcc5dc 100644 --- a/x-pack/legacy/plugins/beats_management/public/containers/with_kuery_autocompletion.tsx +++ b/x-pack/legacy/plugins/beats_management/public/containers/with_kuery_autocompletion.tsx @@ -6,7 +6,7 @@ import React from 'react'; -import { autocomplete } from '../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../src/plugins/data/public'; import { FrontendLibs } from '../lib/types'; import { RendererFunction } from '../utils/typed_react'; @@ -17,7 +17,7 @@ interface WithKueryAutocompletionLifecycleProps { children: RendererFunction<{ isLoadingSuggestions: boolean; loadSuggestions: (expression: string, cursorPosition: number, maxSuggestions?: number) => void; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; }>; } @@ -28,7 +28,7 @@ interface WithKueryAutocompletionLifecycleState { expression: string; cursorPosition: number; } | null; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; } export class WithKueryAutocompletion extends React.Component< diff --git a/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/adapter_types.ts b/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/adapter_types.ts index 12898027d5fb5..6e4665fb130de 100644 --- a/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/adapter_types.ts +++ b/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/adapter_types.ts @@ -3,10 +3,10 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { autocomplete } from '../../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../../src/plugins/data/public'; export interface ElasticsearchAdapter { convertKueryToEsQuery: (kuery: string) => Promise; - getSuggestions: (kuery: string, selectionStart: any) => Promise; + getSuggestions: (kuery: string, selectionStart: any) => Promise; isKueryValid(kuery: string): boolean; } diff --git a/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/memory.ts b/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/memory.ts index 111255b55c99b..fc4daf3df60b2 100644 --- a/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/memory.ts +++ b/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/memory.ts @@ -4,14 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { autocomplete } from '../../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../../src/plugins/data/public'; import { ElasticsearchAdapter } from './adapter_types'; export class MemoryElasticsearchAdapter implements ElasticsearchAdapter { constructor( private readonly mockIsKueryValid: (kuery: string) => boolean, private readonly mockKueryToEsQuery: (kuery: string) => string, - private readonly suggestions: autocomplete.QuerySuggestion[] + private readonly suggestions: QuerySuggestion[] ) {} public isKueryValid(kuery: string): boolean { @@ -20,10 +20,7 @@ export class MemoryElasticsearchAdapter implements ElasticsearchAdapter { public async convertKueryToEsQuery(kuery: string): Promise { return this.mockKueryToEsQuery(kuery); } - public async getSuggestions( - kuery: string, - selectionStart: any - ): Promise { + public async getSuggestions(kuery: string, selectionStart: any): Promise { return this.suggestions; } } diff --git a/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/rest.ts b/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/rest.ts index fc400c600e575..06e6fac0d75c4 100644 --- a/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/rest.ts +++ b/x-pack/legacy/plugins/beats_management/public/lib/adapters/elasticsearch/rest.ts @@ -7,7 +7,7 @@ import { isEmpty } from 'lodash'; import { npStart } from 'ui/new_platform'; import { ElasticsearchAdapter } from './adapter_types'; -import { autocomplete, esKuery } from '../../../../../../../../src/plugins/data/public'; +import { QuerySuggestion, esKuery } from '../../../../../../../../src/plugins/data/public'; export class RestElasticsearchAdapter implements ElasticsearchAdapter { private cachedIndexPattern: any = null; @@ -31,10 +31,7 @@ export class RestElasticsearchAdapter implements ElasticsearchAdapter { return JSON.stringify(esKuery.toElasticsearchQuery(ast, indexPattern)); } - public async getSuggestions( - kuery: string, - selectionStart: any - ): Promise { + public async getSuggestions(kuery: string, selectionStart: any): Promise { const indexPattern = await this.getIndexPattern(); return ( diff --git a/x-pack/legacy/plugins/beats_management/public/lib/compose/memory.ts b/x-pack/legacy/plugins/beats_management/public/lib/compose/memory.ts index 47df51dea8620..b8ecb644ff1b0 100644 --- a/x-pack/legacy/plugins/beats_management/public/lib/compose/memory.ts +++ b/x-pack/legacy/plugins/beats_management/public/lib/compose/memory.ts @@ -24,14 +24,14 @@ import { TagsLib } from '../tags'; import { FrontendLibs } from '../types'; import { MemoryElasticsearchAdapter } from './../adapters/elasticsearch/memory'; import { ElasticsearchLib } from './../elasticsearch'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../src/plugins/data/public'; const onKibanaReady = uiModules.get('kibana').run; export function compose( mockIsKueryValid: (kuery: string) => boolean, mockKueryToEsQuery: (kuery: string) => string, - suggestions: autocomplete.QuerySuggestion[] + suggestions: QuerySuggestion[] ): FrontendLibs { const esAdapter = new MemoryElasticsearchAdapter( mockIsKueryValid, diff --git a/x-pack/legacy/plugins/beats_management/public/lib/elasticsearch.ts b/x-pack/legacy/plugins/beats_management/public/lib/elasticsearch.ts index d71512e80d3d5..82576bff2cbfd 100644 --- a/x-pack/legacy/plugins/beats_management/public/lib/elasticsearch.ts +++ b/x-pack/legacy/plugins/beats_management/public/lib/elasticsearch.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { autocomplete } from '../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../src/plugins/data/public'; import { ElasticsearchAdapter } from './adapters/elasticsearch/adapter_types'; interface HiddenFields { @@ -35,7 +35,7 @@ export class ElasticsearchLib { kuery: string, selectionStart: any, fieldPrefix?: string - ): Promise { + ): Promise { const suggestions = await this.adapter.getSuggestions(kuery, selectionStart); const filteredSuggestions = suggestions.filter(suggestion => { diff --git a/x-pack/legacy/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx b/x-pack/legacy/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx index dc6eabb325d16..f483f2b1b3f57 100644 --- a/x-pack/legacy/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx +++ b/x-pack/legacy/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx @@ -12,7 +12,7 @@ import { } from '@elastic/eui'; import React from 'react'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../src/plugins/data/public'; import euiStyled from '../../../../../common/eui_styled_components'; import { composeStateUpdaters } from '../../utils/typed_react'; @@ -25,7 +25,7 @@ interface AutocompleteFieldProps { onSubmit?: (value: string) => void; onChange?: (value: string) => void; placeholder?: string; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; value: string; autoFocus?: boolean; 'aria-label'?: string; diff --git a/x-pack/legacy/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx b/x-pack/legacy/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx index 79b18f5888bd5..689eb47f289c2 100644 --- a/x-pack/legacy/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx +++ b/x-pack/legacy/plugins/infra/public/components/autocomplete_field/suggestion_item.tsx @@ -8,14 +8,14 @@ import { EuiIcon } from '@elastic/eui'; import { transparentize } from 'polished'; import React from 'react'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../src/plugins/data/public'; import euiStyled from '../../../../../common/eui_styled_components'; interface Props { isSelected?: boolean; onClick?: React.MouseEventHandler; onMouseEnter?: React.MouseEventHandler; - suggestion: autocomplete.QuerySuggestion; + suggestion: QuerySuggestion; } export const SuggestionItem: React.FC = props => { diff --git a/x-pack/legacy/plugins/infra/public/containers/with_kuery_autocompletion.tsx b/x-pack/legacy/plugins/infra/public/containers/with_kuery_autocompletion.tsx index c92e2ecec9261..8188517ba7617 100644 --- a/x-pack/legacy/plugins/infra/public/containers/with_kuery_autocompletion.tsx +++ b/x-pack/legacy/plugins/infra/public/containers/with_kuery_autocompletion.tsx @@ -6,14 +6,14 @@ import React from 'react'; import { npStart } from 'ui/new_platform'; -import { autocomplete, IIndexPattern } from 'src/plugins/data/public'; +import { QuerySuggestion, IIndexPattern } from 'src/plugins/data/public'; import { RendererFunction } from '../utils/typed_react'; interface WithKueryAutocompletionLifecycleProps { children: RendererFunction<{ isLoadingSuggestions: boolean; loadSuggestions: (expression: string, cursorPosition: number, maxSuggestions?: number) => void; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; }>; indexPattern: IIndexPattern; } @@ -25,7 +25,7 @@ interface WithKueryAutocompletionLifecycleState { expression: string; cursorPosition: number; } | null; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; } export class WithKueryAutocompletion extends React.Component< diff --git a/x-pack/legacy/plugins/security/index.js b/x-pack/legacy/plugins/security/index.js index 9016398463b5f..fd89c40f010b7 100644 --- a/x-pack/legacy/plugins/security/index.js +++ b/x-pack/legacy/plugins/security/index.js @@ -86,6 +86,7 @@ export const security = kibana => tenant: server.newPlatform.setup.core.http.basePath.serverBasePath, }, enableSpaceAwarePrivileges: server.config().get('xpack.spaces.enabled'), + logoutUrl: `${server.newPlatform.setup.core.http.basePath.serverBasePath}/logout`, }; }, }, diff --git a/x-pack/legacy/plugins/siem/public/components/autocomplete_field/__examples__/index.stories.tsx b/x-pack/legacy/plugins/siem/public/components/autocomplete_field/__examples__/index.stories.tsx index 85e2b3b3fe384..8f261da629f94 100644 --- a/x-pack/legacy/plugins/siem/public/components/autocomplete_field/__examples__/index.stories.tsx +++ b/x-pack/legacy/plugins/siem/public/components/autocomplete_field/__examples__/index.stories.tsx @@ -8,15 +8,18 @@ import * as React from 'react'; import { storiesOf } from '@storybook/react'; import { ThemeProvider } from 'styled-components'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; -import { autocomplete } from '../../../../../../../../src/plugins/data/public'; +import { + QuerySuggestion, + QuerySuggestionTypes, +} from '../../../../../../../../src/plugins/data/public'; import { SuggestionItem } from '../suggestion_item'; -const suggestion: autocomplete.QuerySuggestion = { +const suggestion: QuerySuggestion = { description: 'Description...', end: 3, start: 1, text: 'Text...', - type: autocomplete.QuerySuggestionsTypes.Value, + type: QuerySuggestionTypes.Value, }; storiesOf('components/SuggestionItem', module).add('example', () => ( diff --git a/x-pack/legacy/plugins/siem/public/components/autocomplete_field/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/autocomplete_field/index.test.tsx index 552aaa5889719..55e114818ffea 100644 --- a/x-pack/legacy/plugins/siem/public/components/autocomplete_field/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/autocomplete_field/index.test.tsx @@ -10,15 +10,18 @@ import { mount, shallow } from 'enzyme'; import { noop } from 'lodash/fp'; import React from 'react'; import { ThemeProvider } from 'styled-components'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { + QuerySuggestion, + QuerySuggestionTypes, +} from '../../../../../../../src/plugins/data/public'; import { TestProviders } from '../../mock'; import { AutocompleteField } from '.'; -const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ +const mockAutoCompleteData: QuerySuggestion[] = [ { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.ephemeral_id ', description: '

Filter results that contain agent.ephemeral_id

', @@ -26,7 +29,7 @@ const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ end: 1, }, { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.hostname ', description: '

Filter results that contain agent.hostname

', @@ -34,7 +37,7 @@ const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ end: 1, }, { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.id ', description: '

Filter results that contain agent.id

', @@ -42,7 +45,7 @@ const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ end: 1, }, { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.name ', description: '

Filter results that contain agent.name

', @@ -50,7 +53,7 @@ const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ end: 1, }, { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.type ', description: '

Filter results that contain agent.type

', @@ -58,7 +61,7 @@ const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ end: 1, }, { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.version ', description: '

Filter results that contain agent.version

', @@ -66,7 +69,7 @@ const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ end: 1, }, { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.test1 ', description: '

Filter results that contain agent.test1

', @@ -74,7 +77,7 @@ const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ end: 1, }, { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.test2 ', description: '

Filter results that contain agent.test2

', @@ -82,7 +85,7 @@ const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ end: 1, }, { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.test3 ', description: '

Filter results that contain agent.test3

', @@ -90,7 +93,7 @@ const mockAutoCompleteData: autocomplete.QuerySuggestion[] = [ end: 1, }, { - type: autocomplete.QuerySuggestionsTypes.Field, + type: QuerySuggestionTypes.Field, text: 'agent.test4 ', description: '

Filter results that contain agent.test4

', diff --git a/x-pack/legacy/plugins/siem/public/components/autocomplete_field/index.tsx b/x-pack/legacy/plugins/siem/public/components/autocomplete_field/index.tsx index 2f76ae21944be..f051e18f8acab 100644 --- a/x-pack/legacy/plugins/siem/public/components/autocomplete_field/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/autocomplete_field/index.tsx @@ -11,7 +11,7 @@ import { EuiPanel, } from '@elastic/eui'; import React from 'react'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../src/plugins/data/public'; import euiStyled from '../../../../../common/eui_styled_components'; @@ -25,7 +25,7 @@ interface AutocompleteFieldProps { onSubmit?: (value: string) => void; onChange?: (value: string) => void; placeholder?: string; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; value: string; } diff --git a/x-pack/legacy/plugins/siem/public/components/autocomplete_field/suggestion_item.tsx b/x-pack/legacy/plugins/siem/public/components/autocomplete_field/suggestion_item.tsx index 44bc65bb0dc15..f99a545d558f7 100644 --- a/x-pack/legacy/plugins/siem/public/components/autocomplete_field/suggestion_item.tsx +++ b/x-pack/legacy/plugins/siem/public/components/autocomplete_field/suggestion_item.tsx @@ -9,13 +9,13 @@ import { transparentize } from 'polished'; import React from 'react'; import styled from 'styled-components'; import euiStyled from '../../../../../common/eui_styled_components'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestion } from '../../../../../../../src/plugins/data/public'; interface SuggestionItemProps { isSelected?: boolean; onClick?: React.MouseEventHandler; onMouseEnter?: React.MouseEventHandler; - suggestion: autocomplete.QuerySuggestion; + suggestion: QuerySuggestion; } export const SuggestionItem = React.memo( diff --git a/x-pack/legacy/plugins/siem/public/containers/kuery_autocompletion/index.tsx b/x-pack/legacy/plugins/siem/public/containers/kuery_autocompletion/index.tsx index 4eb51dfe6407c..af4eb1ff7a5e1 100644 --- a/x-pack/legacy/plugins/siem/public/containers/kuery_autocompletion/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/kuery_autocompletion/index.tsx @@ -5,7 +5,7 @@ */ import React, { useState } from 'react'; -import { autocomplete, IIndexPattern } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestion, IIndexPattern } from '../../../../../../../src/plugins/data/public'; import { useKibana } from '../../lib/kibana'; type RendererResult = React.ReactElement | null; @@ -15,7 +15,7 @@ interface KueryAutocompletionLifecycleProps { children: RendererFunction<{ isLoadingSuggestions: boolean; loadSuggestions: (expression: string, cursorPosition: number, maxSuggestions?: number) => void; - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; }>; indexPattern: IIndexPattern; } @@ -30,7 +30,7 @@ export const KueryAutocompletion = React.memo const [currentRequest, setCurrentRequest] = useState( null ); - const [suggestions, setSuggestions] = useState([]); + const [suggestions, setSuggestions] = useState([]); const kibana = useKibana(); const loadSuggestions = async ( expression: string, diff --git a/x-pack/legacy/plugins/uptime/public/components/functional/kuery_bar/kuery_bar.tsx b/x-pack/legacy/plugins/uptime/public/components/functional/kuery_bar/kuery_bar.tsx index 63c8885fe5864..b1eb3f38097b2 100644 --- a/x-pack/legacy/plugins/uptime/public/components/functional/kuery_bar/kuery_bar.tsx +++ b/x-pack/legacy/plugins/uptime/public/components/functional/kuery_bar/kuery_bar.tsx @@ -14,7 +14,7 @@ import { useUrlParams } from '../../../hooks'; import { esKuery, IIndexPattern, - autocomplete, + QuerySuggestion, DataPublicPluginStart, } from '../../../../../../../../src/plugins/data/public'; @@ -23,7 +23,7 @@ const Container = styled.div` `; interface State { - suggestions: autocomplete.QuerySuggestion[]; + suggestions: QuerySuggestion[]; isLoadingIndexPattern: boolean; } diff --git a/x-pack/legacy/plugins/xpack_main/server/telemetry_collection/__tests__/get_xpack.js b/x-pack/legacy/plugins/xpack_main/server/telemetry_collection/__tests__/get_xpack.js index 3b25084e70e95..eca130b4d7465 100644 --- a/x-pack/legacy/plugins/xpack_main/server/telemetry_collection/__tests__/get_xpack.js +++ b/x-pack/legacy/plugins/xpack_main/server/telemetry_collection/__tests__/get_xpack.js @@ -17,6 +17,7 @@ function mockGetXPackLicense(callCluster, license, req) { path: '/_license', query: { local: 'true', + accept_enterprise: 'true', }, }) .returns( @@ -32,6 +33,7 @@ function mockGetXPackLicense(callCluster, license, req) { path: '/_license', query: { local: 'true', + accept_enterprise: 'true', }, }) // conveniently wraps the passed in license object as { license: response }, like it really is diff --git a/x-pack/legacy/plugins/xpack_main/server/telemetry_collection/get_xpack.js b/x-pack/legacy/plugins/xpack_main/server/telemetry_collection/get_xpack.js index 925d573b490b8..aaeb890981aa1 100644 --- a/x-pack/legacy/plugins/xpack_main/server/telemetry_collection/get_xpack.js +++ b/x-pack/legacy/plugins/xpack_main/server/telemetry_collection/get_xpack.js @@ -23,6 +23,8 @@ export function getXPackLicense(callCluster) { query: { // Fetching the local license is cheaper than getting it from the master and good enough local: 'true', + // For versions >= 7.6 and < 8.0, this flag is needed otherwise 'platinum' is returned for 'enterprise' license. + accept_enterprise: 'true', }, }).then(({ license }) => license); } diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts index d993c3d8ad51d..b0a3f64c6a479 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.test.ts @@ -5,14 +5,14 @@ */ import { setupGetConjunctionSuggestions } from './conjunction'; -import { autocomplete, esKuery } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestionGetFnArgs, esKuery } from '../../../../../../../src/plugins/data/public'; import { coreMock } from '../../../../../../../src/core/public/mocks'; const mockKueryNode = (kueryNode: Partial) => (kueryNode as unknown) as esKuery.KueryNode; describe('Kuery conjunction suggestions', () => { - const querySuggestionsArgs = (null as unknown) as autocomplete.QuerySuggestionsGetFnArgs; + const querySuggestionsArgs = (null as unknown) as QuerySuggestionGetFnArgs; let getSuggestions: ReturnType; beforeEach(() => { diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx index fa655562134cc..fedb43812d3d0 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/conjunction.tsx @@ -7,7 +7,10 @@ import React from 'react'; import { $Keys } from 'utility-types'; import { FormattedMessage } from '@kbn/i18n/react'; import { KqlQuerySuggestionProvider } from './types'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { + QuerySuggestion, + QuerySuggestionTypes, +} from '../../../../../../../src/plugins/data/public'; const bothArgumentsText = ( = { export const setupGetConjunctionSuggestions: KqlQuerySuggestionProvider = core => { return (querySuggestionsArgs, { text, end }) => { - let suggestions: autocomplete.QuerySuggestion[] | [] = []; + let suggestions: QuerySuggestion[] | [] = []; if (text.endsWith(' ')) { suggestions = Object.keys(conjunctions).map((key: $Keys) => ({ - type: autocomplete.QuerySuggestionsTypes.Conjunction, + type: QuerySuggestionTypes.Conjunction, text: `${key} `, description: conjunctions[key], start: end, diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts index d05fd49d266f2..00262d092947b 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.test.ts @@ -6,20 +6,24 @@ import indexPatternResponse from './__fixtures__/index_pattern_response.json'; import { setupGetFieldSuggestions } from './field'; -import { isFilterable, autocomplete, esKuery } from '../../../../../../../src/plugins/data/public'; +import { + isFilterable, + QuerySuggestionGetFnArgs, + esKuery, +} from '../../../../../../../src/plugins/data/public'; import { coreMock } from '../../../../../../../src/core/public/mocks'; const mockKueryNode = (kueryNode: Partial) => (kueryNode as unknown) as esKuery.KueryNode; describe('Kuery field suggestions', () => { - let querySuggestionsArgs: autocomplete.QuerySuggestionsGetFnArgs; + let querySuggestionsArgs: QuerySuggestionGetFnArgs; let getSuggestions: ReturnType; beforeEach(() => { querySuggestionsArgs = ({ indexPatterns: [indexPatternResponse], - } as unknown) as autocomplete.QuerySuggestionsGetFnArgs; + } as unknown) as QuerySuggestionGetFnArgs; getSuggestions = setupGetFieldSuggestions(coreMock.createSetup()); }); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx index f04312b925436..0dcbea893ace4 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/field.tsx @@ -11,7 +11,8 @@ import { sortPrefixFirst } from './sort_prefix_first'; import { IFieldType, isFilterable, - autocomplete, + QuerySuggestionField, + QuerySuggestionTypes, } from '../../../../../../../src/plugins/data/public'; import { KqlQuerySuggestionProvider } from './types'; @@ -38,7 +39,7 @@ const keywordComparator = (first: IFieldType, second: IFieldType) => { return first.name.localeCompare(second.name); }; -export const setupGetFieldSuggestions: KqlQuerySuggestionProvider = core => { +export const setupGetFieldSuggestions: KqlQuerySuggestionProvider = core => { return ({ indexPatterns }, { start, end, prefix, suffix, nestedPath = '' }) => { const allFields = flatten( indexPatterns.map(indexPattern => { @@ -59,7 +60,7 @@ export const setupGetFieldSuggestions: KqlQuerySuggestionProvider { + const suggestions: QuerySuggestionField[] = sortedFields.map(field => { const remainingPath = field.subType && field.subType.nested ? field.subType.nested.path.slice(nestedPath ? nestedPath.length + 1 : 0) @@ -77,7 +78,7 @@ export const setupGetFieldSuggestions: KqlQuerySuggestionProvider +const dedup = (suggestions: QuerySuggestion[]): QuerySuggestion[] => uniq(suggestions, ({ type, text, start, end }) => [type, text, start, end].join('|')); export const KUERY_LANGUAGE_NAME = 'kuery'; -export const setupKqlQuerySuggestionProvider = ( - core: CoreSetup -): autocomplete.QuerySuggestionsGetFn => { +export const setupKqlQuerySuggestionProvider = (core: CoreSetup): QuerySuggestionGetFn => { const providers = { field: setupGetFieldSuggestions(core), value: setupGetValueSuggestions(core), @@ -32,8 +35,8 @@ export const setupKqlQuerySuggestionProvider = ( const getSuggestionsByType = ( cursoredQuery: string, - querySuggestionsArgs: autocomplete.QuerySuggestionsGetFnArgs - ): Array> | [] => { + querySuggestionsArgs: QuerySuggestionGetFnArgs + ): Array> | [] => { try { const cursorNode = esKuery.fromKueryExpression(cursoredQuery, { cursorSymbol, diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts index 7e564b96064ef..186d455a518b4 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.test.ts @@ -6,7 +6,7 @@ import indexPatternResponse from './__fixtures__/index_pattern_response.json'; import { setupGetOperatorSuggestions } from './operator'; -import { autocomplete, esKuery } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestionGetFnArgs, esKuery } from '../../../../../../../src/plugins/data/public'; import { coreMock } from '../../../../../../../src/core/public/mocks'; const mockKueryNode = (kueryNode: Partial) => @@ -14,12 +14,12 @@ const mockKueryNode = (kueryNode: Partial) => describe('Kuery operator suggestions', () => { let getSuggestions: ReturnType; - let querySuggestionsArgs: autocomplete.QuerySuggestionsGetFnArgs; + let querySuggestionsArgs: QuerySuggestionGetFnArgs; beforeEach(() => { querySuggestionsArgs = ({ indexPatterns: [indexPatternResponse], - } as unknown) as autocomplete.QuerySuggestionsGetFnArgs; + } as unknown) as QuerySuggestionGetFnArgs; getSuggestions = setupGetOperatorSuggestions(coreMock.createSetup()); }); diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx index af90e7bfe1172..14c42d73f8d0b 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/operator.tsx @@ -10,7 +10,7 @@ import { $Keys } from 'utility-types'; import { flatten } from 'lodash'; import { KqlQuerySuggestionProvider } from './types'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestionTypes } from '../../../../../../../src/plugins/data/public'; const equalsText = ( { }); const suggestions = matchingOperators.map(operator => ({ - type: autocomplete.QuerySuggestionsTypes.Operator, + type: QuerySuggestionTypes.Operator, text: operator + ' ', description: getDescription(operator), start: end, diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/types.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/types.ts index 8e3146ab09848..eb7582fc6ec6b 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/types.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/types.ts @@ -5,11 +5,15 @@ */ import { CoreSetup } from 'kibana/public'; -import { esKuery, autocomplete } from '../../../../../../../src/plugins/data/public'; +import { + esKuery, + QuerySuggestionBasic, + QuerySuggestionGetFnArgs, +} from '../../../../../../../src/plugins/data/public'; -export type KqlQuerySuggestionProvider = ( +export type KqlQuerySuggestionProvider = ( core: CoreSetup ) => ( - querySuggestionsGetFnArgs: autocomplete.QuerySuggestionsGetFnArgs, + querySuggestionsGetFnArgs: QuerySuggestionGetFnArgs, kueryNode: esKuery.KueryNode ) => Promise; diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.test.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.test.ts index 14eeabda97d1a..41fee5fa930fd 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.test.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.test.ts @@ -6,7 +6,7 @@ import { setupGetValueSuggestions } from './value'; import indexPatternResponse from './__fixtures__/index_pattern_response.json'; import { coreMock } from '../../../../../../../src/core/public/mocks'; -import { autocomplete, esKuery } from '../../../../../../../src/plugins/data/public'; +import { QuerySuggestionGetFnArgs, esKuery } from '../../../../../../../src/plugins/data/public'; import { setAutocompleteService } from '../../../services'; const mockKueryNode = (kueryNode: Partial) => @@ -14,14 +14,14 @@ const mockKueryNode = (kueryNode: Partial) => describe('Kuery value suggestions', () => { let getSuggestions: ReturnType; - let querySuggestionsArgs: autocomplete.QuerySuggestionsGetFnArgs; + let querySuggestionsArgs: QuerySuggestionGetFnArgs; let autocompleteServiceMock: any; beforeEach(() => { getSuggestions = setupGetValueSuggestions(coreMock.createSetup()); querySuggestionsArgs = ({ indexPatterns: [indexPatternResponse], - } as unknown) as autocomplete.QuerySuggestionsGetFnArgs; + } as unknown) as QuerySuggestionGetFnArgs; autocompleteServiceMock = { getValueSuggestions: jest.fn(({ field }) => { diff --git a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts index 83b8024d8314d..bfd1e13ad9c39 100644 --- a/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts +++ b/x-pack/plugins/data_enhanced/public/autocomplete/providers/kql_query_suggestion/value.ts @@ -8,13 +8,16 @@ import { flatten } from 'lodash'; import { escapeQuotes } from './lib/escape_kuery'; import { KqlQuerySuggestionProvider } from './types'; import { getAutocompleteService } from '../../../services'; -import { autocomplete } from '../../../../../../../src/plugins/data/public'; +import { + QuerySuggestion, + QuerySuggestionTypes, +} from '../../../../../../../src/plugins/data/public'; const wrapAsSuggestions = (start: number, end: number, query: string, values: string[]) => values .filter(value => value.toLowerCase().includes(query.toLowerCase())) .map(value => ({ - type: autocomplete.QuerySuggestionsTypes.Value, + type: QuerySuggestionTypes.Value, text: `${value} `, start, end, @@ -24,7 +27,7 @@ export const setupGetValueSuggestions: KqlQuerySuggestionProvider = core => { return async ( { indexPatterns, boolFilter, signal }, { start, end, prefix, suffix, fieldName, nestedPath } - ): Promise => { + ): Promise => { const allFields = flatten( indexPatterns.map(indexPattern => indexPattern.fields.map(field => ({ diff --git a/x-pack/plugins/security/public/nav_control/nav_control_service.tsx b/x-pack/plugins/security/public/nav_control/nav_control_service.tsx index 035549ccaa2cb..813304148ec77 100644 --- a/x-pack/plugins/security/public/nav_control/nav_control_service.tsx +++ b/x-pack/plugins/security/public/nav_control/nav_control_service.tsx @@ -65,9 +65,7 @@ export class SecurityNavControlService { mount: (el: HTMLElement) => { const I18nContext = core.i18n.Context; - const serverBasePath = core.injectedMetadata.getInjectedVar('serverBasePath') as string; - - const logoutUrl = `${serverBasePath}/logout`; + const logoutUrl = core.injectedMetadata.getInjectedVar('logoutUrl') as string; const props = { user: currentUserPromise, diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/disable.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/disable.ts index bafca30abf28a..5007cfa6cf044 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/disable.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/disable.ts @@ -84,6 +84,62 @@ export default function createDisableAlertTests({ getService }: FtrProviderConte } }); + it('should still be able to disable alert when AAD is broken', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alert`) + .set('kbn-xsrf', 'foo') + .send(getTestAlertData({ enabled: true })) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert'); + + await supertest + .put(`${getUrlPrefix(space.id)}/api/saved_objects/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .send({ + attributes: { + name: 'bar', + }, + }) + .expect(200); + + const response = await alertUtils.getDisableRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(404); + expect(response.body).to.eql({ + statusCode: 404, + error: 'Not Found', + message: 'Not Found', + }); + // Ensure task still exists + await getScheduledTask(createdAlert.scheduledTaskId); + break; + case 'superuser at space1': + case 'space_1_all at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + try { + await getScheduledTask(createdAlert.scheduledTaskId); + throw new Error('Should have removed scheduled task'); + } catch (e) { + expect(e.status).to.eql(404); + } + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + it(`shouldn't disable alert from another space`, async () => { const { body: createdAlert } = await supertest .post(`${getUrlPrefix('other')}/api/alert`) diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/enable.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/enable.ts index 9df1f955232b1..d89172515757b 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/enable.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/enable.ts @@ -89,6 +89,67 @@ export default function createEnableAlertTests({ getService }: FtrProviderContex } }); + it('should still be able to enable alert when AAD is broken', async () => { + const { body: createdAlert } = await supertest + .post(`${getUrlPrefix(space.id)}/api/alert`) + .set('kbn-xsrf', 'foo') + .send(getTestAlertData({ enabled: false })) + .expect(200); + objectRemover.add(space.id, createdAlert.id, 'alert'); + + await supertest + .put(`${getUrlPrefix(space.id)}/api/saved_objects/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .send({ + attributes: { + name: 'bar', + }, + }) + .expect(200); + + const response = await alertUtils.getEnableRequest(createdAlert.id); + + switch (scenario.id) { + case 'no_kibana_privileges at space1': + case 'space_1_all at space2': + case 'global_read at space1': + expect(response.statusCode).to.eql(404); + expect(response.body).to.eql({ + statusCode: 404, + error: 'Not Found', + message: 'Not Found', + }); + break; + case 'superuser at space1': + case 'space_1_all at space1': + expect(response.statusCode).to.eql(204); + expect(response.body).to.eql(''); + const { body: updatedAlert } = await supertestWithoutAuth + .get(`${getUrlPrefix(space.id)}/api/alert/${createdAlert.id}`) + .set('kbn-xsrf', 'foo') + .auth(user.username, user.password) + .expect(200); + expect(typeof updatedAlert.scheduledTaskId).to.eql('string'); + const { _source: taskRecord } = await getScheduledTask(updatedAlert.scheduledTaskId); + expect(taskRecord.type).to.eql('task'); + expect(taskRecord.task.taskType).to.eql('alerting:test.noop'); + expect(JSON.parse(taskRecord.task.params)).to.eql({ + alertId: createdAlert.id, + spaceId: space.id, + }); + // Ensure AAD isn't broken + await checkAAD({ + supertest, + spaceId: space.id, + type: 'alert', + id: createdAlert.id, + }); + break; + default: + throw new Error(`Scenario untested: ${JSON.stringify(scenario)}`); + } + }); + it(`shouldn't enable alert from another space`, async () => { const { body: createdAlert } = await supertest .post(`${getUrlPrefix('other')}/api/alert`) diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/find.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/find.ts index d99ab794cd28f..65ffa9ebe9dfa 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/find.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/find.ts @@ -158,7 +158,7 @@ export default function createFindTests({ getService }: FtrProviderContext) { createdBy: 'elastic', throttle: '1m', updatedBy: 'elastic', - apiKeyOwner: 'elastic', + apiKeyOwner: null, muteAll: false, mutedInstanceIds: [], createdAt: match.createdAt,