From e09e6a2b0b2a295d70e4336b803918f933cacd54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20C=C3=B4t=C3=A9?= Date: Tue, 28 Apr 2020 09:58:12 -0400 Subject: [PATCH 01/12] Fix flaky test in alert details page (#64572) --- .../apps/triggers_actions_ui/details.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts index 1b75f4a27766a7..d0ce18bbc1c54c 100644 --- a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts +++ b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts @@ -504,6 +504,12 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { } ); + // await first run to complete so we have an initial state + await retry.try(async () => { + const { alertInstances } = await alerting.alerts.getAlertState(alert.id); + expect(Object.keys(alertInstances).length).to.eql(instances.length); + }); + // refresh to see alert await browser.refresh(); @@ -514,12 +520,6 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { // click on first alert await pageObjects.triggersActionsUI.clickOnAlertInAlertsList(alert.name); - - // await first run to complete so we have an initial state - await retry.try(async () => { - const { alertInstances } = await alerting.alerts.getAlertState(alert.id); - expect(Object.keys(alertInstances).length).to.eql(instances.length); - }); }); const PAGE_SIZE = 10; From fa219bc2d85a126d4151c2c4952ebd5d8e5e16e0 Mon Sep 17 00:00:00 2001 From: Vadim Dalecky Date: Tue, 28 Apr 2020 16:40:46 +0200 Subject: [PATCH 02/12] =?UTF-8?q?fix:=20=F0=9F=90=9B=20subsribe=20to=20"ab?= =?UTF-8?q?ort"=20event=20in=20abort=20controller=20(#63199)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: 🐛 subsribe to "abort" event in abort controller * test: 💍 add test for execution cancellation after completion * feat: 🎸 use a more meaningful sentinel * refactor: 💡 use toPromise() from data plugin * chore: 🤖 disable most new tests * test: 💍 remove fake timers from abort tests * test: 💍 remove new tests completely There seems to be some async race condition in Jest test runner not related to this PR, but for some reason Jest fails. Removing these tests temporarily to check if this file cases Jest to fail. * chore: 🤖 try adding .catch clause to abortion promise * chore: 🤖 revert tests back and add .catch() comment --- src/plugins/data/common/utils/abort_utils.ts | 16 +++- .../execution/execution.abortion.test.ts | 96 +++++++++++++++++++ .../expressions/common/execution/execution.ts | 46 ++++++--- .../common/expression_types/specs/error.ts | 2 +- .../expressions/common/util/create_error.ts | 6 +- 5 files changed, 147 insertions(+), 19 deletions(-) create mode 100644 src/plugins/expressions/common/execution/execution.abortion.test.ts diff --git a/src/plugins/data/common/utils/abort_utils.ts b/src/plugins/data/common/utils/abort_utils.ts index 5051515f3a8265..9aec787170840f 100644 --- a/src/plugins/data/common/utils/abort_utils.ts +++ b/src/plugins/data/common/utils/abort_utils.ts @@ -33,19 +33,31 @@ export class AbortError extends Error { * Returns a `Promise` corresponding with when the given `AbortSignal` is aborted. Useful for * situations when you might need to `Promise.race` multiple `AbortSignal`s, or an `AbortSignal` * with any other expected errors (or completions). + * * @param signal The `AbortSignal` to generate the `Promise` from * @param shouldReject If `false`, the promise will be resolved, otherwise it will be rejected */ -export function toPromise(signal: AbortSignal, shouldReject = false) { - return new Promise((resolve, reject) => { +export function toPromise(signal: AbortSignal, shouldReject?: false): Promise; +export function toPromise(signal: AbortSignal, shouldReject?: true): Promise; +export function toPromise(signal: AbortSignal, shouldReject: boolean = false) { + const promise = new Promise((resolve, reject) => { const action = shouldReject ? reject : resolve; if (signal.aborted) action(); signal.addEventListener('abort', action); }); + + /** + * Below is to make sure we don't have unhandled promise rejections. Otherwise + * Jest tests fail. + */ + promise.catch(() => {}); + + return promise; } /** * Returns an `AbortSignal` that will be aborted when the first of the given signals aborts. + * * @param signals */ export function getCombinedSignal(signals: AbortSignal[]) { diff --git a/src/plugins/expressions/common/execution/execution.abortion.test.ts b/src/plugins/expressions/common/execution/execution.abortion.test.ts new file mode 100644 index 00000000000000..ecbf94eceae642 --- /dev/null +++ b/src/plugins/expressions/common/execution/execution.abortion.test.ts @@ -0,0 +1,96 @@ +/* + * 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. + */ + +import { Execution } from './execution'; +import { parseExpression } from '../ast'; +import { createUnitTestExecutor } from '../test_helpers'; + +jest.useFakeTimers(); + +beforeEach(() => { + jest.clearAllTimers(); +}); + +const createExecution = ( + expression: string = 'foo bar=123', + context: Record = {}, + debug: boolean = false +) => { + const executor = createUnitTestExecutor(); + const execution = new Execution({ + executor, + ast: parseExpression(expression), + context, + debug, + }); + return execution; +}; + +describe('Execution abortion tests', () => { + test('can abort an expression immediately', async () => { + const execution = createExecution('sleep 10'); + + execution.start(); + execution.cancel(); + + const result = await execution.result; + + expect(result).toMatchObject({ + type: 'error', + error: { + message: 'The expression was aborted.', + name: 'AbortError', + }, + }); + }); + + test('can abort an expression which has function running mid flight', async () => { + const execution = createExecution('sleep 300'); + + execution.start(); + jest.advanceTimersByTime(100); + execution.cancel(); + + const result = await execution.result; + + expect(result).toMatchObject({ + type: 'error', + error: { + message: 'The expression was aborted.', + name: 'AbortError', + }, + }); + }); + + test('cancelling execution after it completed has no effect', async () => { + jest.useRealTimers(); + + const execution = createExecution('sleep 1'); + + execution.start(); + + const result = await execution.result; + + execution.cancel(); + + expect(result).toBe(null); + + jest.useFakeTimers(); + }); +}); diff --git a/src/plugins/expressions/common/execution/execution.ts b/src/plugins/expressions/common/execution/execution.ts index d0ab178296408a..6ee12d97a64226 100644 --- a/src/plugins/expressions/common/execution/execution.ts +++ b/src/plugins/expressions/common/execution/execution.ts @@ -22,7 +22,7 @@ import { Executor } from '../executor'; import { createExecutionContainer, ExecutionContainer } from './container'; import { createError } from '../util'; import { Defer, now } from '../../../kibana_utils/common'; -import { AbortError } from '../../../data/common'; +import { toPromise } from '../../../data/common/utils/abort_utils'; import { RequestAdapter, DataAdapter } from '../../../inspector/common'; import { isExpressionValueError, ExpressionValueError } from '../expression_types/specs/error'; import { @@ -38,6 +38,12 @@ import { ArgumentType, ExpressionFunction } from '../expression_functions'; import { getByAlias } from '../util/get_by_alias'; import { ExecutionContract } from './execution_contract'; +const createAbortErrorValue = () => + createError({ + message: 'The expression was aborted.', + name: 'AbortError', + }); + export interface ExecutionParams< ExtraContext extends Record = Record > { @@ -70,7 +76,7 @@ export class Execution< /** * Dynamic state of the execution. */ - public readonly state: ExecutionContainer; + public readonly state: ExecutionContainer; /** * Initial input of the execution. @@ -91,6 +97,18 @@ export class Execution< */ private readonly abortController = new AbortController(); + /** + * Promise that rejects if/when abort controller sends "abort" signal. + */ + private readonly abortRejection = toPromise(this.abortController.signal, true); + + /** + * Races a given promise against the "abort" event of `abortController`. + */ + private race(promise: Promise): Promise { + return Promise.race([this.abortRejection, promise]); + } + /** * Whether .start() method has been called. */ @@ -99,7 +117,7 @@ export class Execution< /** * Future that tracks result or error of this execution. */ - private readonly firstResultFuture = new Defer(); + private readonly firstResultFuture = new Defer(); /** * Contract is a public representation of `Execution` instances. Contract we @@ -114,7 +132,7 @@ export class Execution< public readonly expression: string; - public get result(): Promise { + public get result(): Promise { return this.firstResultFuture.promise; } @@ -134,7 +152,7 @@ export class Execution< this.expression = params.expression || formatExpression(params.ast!); const ast = params.ast || parseExpression(this.expression); - this.state = createExecutionContainer({ + this.state = createExecutionContainer({ ...executor.state.get(), state: 'not-started', ast, @@ -173,7 +191,12 @@ export class Execution< this.state.transitions.start(); const { resolve, reject } = this.firstResultFuture; - this.invokeChain(this.state.get().ast.chain, input).then(resolve, reject); + const chainPromise = this.invokeChain(this.state.get().ast.chain, input); + + this.race(chainPromise).then(resolve, error => { + if (this.abortController.signal.aborted) resolve(createAbortErrorValue()); + else reject(error); + }); this.firstResultFuture.promise.then( result => { @@ -189,11 +212,6 @@ export class Execution< if (!chainArr.length) return input; for (const link of chainArr) { - // if execution was aborted return error - if (this.context.abortSignal && this.context.abortSignal.aborted) { - return createError(new AbortError('The expression was aborted.')); - } - const { function: fnName, arguments: fnArgs } = link; const fn = getByAlias(this.state.get().functions, fnName); @@ -207,10 +225,10 @@ export class Execution< try { // `resolveArgs` returns an object because the arguments themselves might // actually have a `then` function which would be treated as a `Promise`. - const { resolvedArgs } = await this.resolveArgs(fn, input, fnArgs); + const { resolvedArgs } = await this.race(this.resolveArgs(fn, input, fnArgs)); args = resolvedArgs; timeStart = this.params.debug ? now() : 0; - const output = await this.invokeFunction(fn, input, resolvedArgs); + const output = await this.race(this.invokeFunction(fn, input, resolvedArgs)); if (this.params.debug) { const timeEnd: number = now(); @@ -256,7 +274,7 @@ export class Execution< args: Record ): Promise { const normalizedInput = this.cast(input, fn.inputTypes); - const output = await fn.fn(normalizedInput, args, this.context); + const output = await this.race(fn.fn(normalizedInput, args, this.context)); // Validate that the function returned the type it said it would. // This isn't required, but it keeps function developers honest. diff --git a/src/plugins/expressions/common/expression_types/specs/error.ts b/src/plugins/expressions/common/expression_types/specs/error.ts index 4b255a0f967b26..35554954d08282 100644 --- a/src/plugins/expressions/common/expression_types/specs/error.ts +++ b/src/plugins/expressions/common/expression_types/specs/error.ts @@ -31,7 +31,7 @@ export type ExpressionValueError = ExpressionValueBoxed< name?: string; stack?: string; }; - info: unknown; + info?: unknown; } >; diff --git a/src/plugins/expressions/common/util/create_error.ts b/src/plugins/expressions/common/util/create_error.ts index 8236ff8709a823..bc27b0eda49598 100644 --- a/src/plugins/expressions/common/util/create_error.ts +++ b/src/plugins/expressions/common/util/create_error.ts @@ -17,9 +17,11 @@ * under the License. */ +import { ExpressionValueError } from '../../public'; + type ErrorLike = Partial>; -export const createError = (err: string | ErrorLike) => ({ +export const createError = (err: string | ErrorLike): ExpressionValueError => ({ type: 'error', error: { stack: @@ -28,7 +30,7 @@ export const createError = (err: string | ErrorLike) => ({ : typeof err === 'object' ? err.stack : undefined, - message: typeof err === 'string' ? err : err.message, + message: typeof err === 'string' ? err : String(err.message), name: typeof err === 'object' ? err.name || 'Error' : 'Error', }, }); From f7f245f4bc6630149c5867f626a042e33f59a158 Mon Sep 17 00:00:00 2001 From: Paul Tavares <56442535+paul-tavares@users.noreply.github.com> Date: Tue, 28 Apr 2020 11:31:06 -0400 Subject: [PATCH 03/12] [Endpoint] Bug fixes to Policy List and Details views (#64568) * Fix Datasource API calls to use correct object type in kuery * Fix policy details showing toaster multiple times * Fix taking last url param value (instead of first) --- .../endpoint/store/policy_list/index.test.ts | 35 +++++++++++++++---- .../endpoint/store/policy_list/selectors.ts | 10 ++++-- .../store/policy_list/services/ingest.test.ts | 5 +-- .../store/policy_list/services/ingest.ts | 3 +- .../endpoint/view/policy/policy_details.tsx | 4 +-- 5 files changed, 42 insertions(+), 15 deletions(-) diff --git a/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/index.test.ts b/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/index.test.ts index 69b11fb3c1f0ea..9912c9a81e6e14 100644 --- a/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/index.test.ts +++ b/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/index.test.ts @@ -16,6 +16,7 @@ import { setPolicyListApiMockImplementation } from './test_mock_utils'; import { INGEST_API_DATASOURCES } from './services/ingest'; import { Immutable } from '../../../../../common/types'; import { createSpyMiddleware, MiddlewareActionSpyHelper } from '../test_utils'; +import { DATASOURCE_SAVED_OBJECT_TYPE } from '../../../../../../ingest_manager/common'; describe('policy list store concerns', () => { let fakeCoreStart: ReturnType; @@ -121,7 +122,11 @@ describe('policy list store concerns', () => { }); await waitForAction('serverReturnedPolicyListData'); expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_DATASOURCES, { - query: { kuery: 'datasources.package.name: endpoint', page: 1, perPage: 10 }, + query: { + kuery: `${DATASOURCE_SAVED_OBJECT_TYPE}.package.name: endpoint`, + page: 1, + perPage: 10, + }, }); }); @@ -140,7 +145,11 @@ describe('policy list store concerns', () => { dispatchUserChangedUrl('?page_size=50&page_index=0'); await waitForAction('serverReturnedPolicyListData'); expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_DATASOURCES, { - query: { kuery: 'datasources.package.name: endpoint', page: 1, perPage: 50 }, + query: { + kuery: `${DATASOURCE_SAVED_OBJECT_TYPE}.package.name: endpoint`, + page: 1, + perPage: 50, + }, }); }); it('uses defaults for params not in url', async () => { @@ -159,21 +168,33 @@ describe('policy list store concerns', () => { dispatchUserChangedUrl('?page_size=-50&page_index=-99'); await waitForAction('serverReturnedPolicyListData'); expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_DATASOURCES, { - query: { kuery: 'datasources.package.name: endpoint', page: 1, perPage: 10 }, + query: { + kuery: `${DATASOURCE_SAVED_OBJECT_TYPE}.package.name: endpoint`, + page: 1, + perPage: 10, + }, }); }); it('it ignores non-numeric values for page_index and page_size', async () => { dispatchUserChangedUrl('?page_size=fifty&page_index=ten'); await waitForAction('serverReturnedPolicyListData'); expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_DATASOURCES, { - query: { kuery: 'datasources.package.name: endpoint', page: 1, perPage: 10 }, + query: { + kuery: `${DATASOURCE_SAVED_OBJECT_TYPE}.package.name: endpoint`, + page: 1, + perPage: 10, + }, }); }); it('accepts only known values for `page_size`', async () => { dispatchUserChangedUrl('?page_size=300&page_index=10'); await waitForAction('serverReturnedPolicyListData'); expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_DATASOURCES, { - query: { kuery: 'datasources.package.name: endpoint', page: 11, perPage: 10 }, + query: { + kuery: `${DATASOURCE_SAVED_OBJECT_TYPE}.package.name: endpoint`, + page: 11, + perPage: 10, + }, }); }); it(`ignores unknown url search params`, async () => { @@ -186,8 +207,8 @@ describe('policy list store concerns', () => { it(`uses last param value if param is defined multiple times`, async () => { dispatchUserChangedUrl('?page_size=20&page_size=50&page_index=20&page_index=40'); expect(urlSearchParams(getState())).toEqual({ - page_index: 20, - page_size: 20, + page_index: 40, + page_size: 50, }); }); }); diff --git a/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/selectors.ts b/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/selectors.ts index 6d2e952fa07bba..4986a342cca19e 100644 --- a/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/selectors.ts +++ b/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/selectors.ts @@ -46,12 +46,16 @@ export const urlSearchParams: ( const query = parse(location.search); // Search params can appear multiple times in the URL, in which case the value for them, - // once parsed, would be an array. In these case, we take the first value defined + // once parsed, would be an array. In these case, we take the last value defined searchParams.page_index = Number( - (Array.isArray(query.page_index) ? query.page_index[0] : query.page_index) ?? 0 + (Array.isArray(query.page_index) + ? query.page_index[query.page_index.length - 1] + : query.page_index) ?? 0 ); searchParams.page_size = Number( - (Array.isArray(query.page_size) ? query.page_size[0] : query.page_size) ?? 10 + (Array.isArray(query.page_size) + ? query.page_size[query.page_size.length - 1] + : query.page_size) ?? 10 ); // If pageIndex is not a valid positive integer, set it to 0 diff --git a/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/services/ingest.test.ts b/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/services/ingest.test.ts index c2865d36c95f2d..46f4c09e05a745 100644 --- a/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/services/ingest.test.ts +++ b/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/services/ingest.test.ts @@ -6,6 +6,7 @@ import { sendGetDatasource, sendGetEndpointSpecificDatasources } from './ingest'; import { httpServiceMock } from '../../../../../../../../../src/core/public/mocks'; +import { DATASOURCE_SAVED_OBJECT_TYPE } from '../../../../../../../ingest_manager/common'; describe('ingest service', () => { let http: ReturnType; @@ -19,7 +20,7 @@ describe('ingest service', () => { await sendGetEndpointSpecificDatasources(http); expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/datasources', { query: { - kuery: 'datasources.package.name: endpoint', + kuery: `${DATASOURCE_SAVED_OBJECT_TYPE}.package.name: endpoint`, }, }); }); @@ -29,7 +30,7 @@ describe('ingest service', () => { }); expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/datasources', { query: { - kuery: 'someValueHere and datasources.package.name: endpoint', + kuery: `someValueHere and ${DATASOURCE_SAVED_OBJECT_TYPE}.package.name: endpoint`, perPage: 10, page: 1, }, diff --git a/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/services/ingest.ts b/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/services/ingest.ts index 4356517e43c2cb..5c27680d6a35c7 100644 --- a/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/services/ingest.ts +++ b/x-pack/plugins/endpoint/public/applications/endpoint/store/policy_list/services/ingest.ts @@ -8,6 +8,7 @@ import { HttpFetchOptions, HttpStart } from 'kibana/public'; import { GetDatasourcesRequest, GetAgentStatusResponse, + DATASOURCE_SAVED_OBJECT_TYPE, } from '../../../../../../../ingest_manager/common'; import { GetPolicyListResponse, GetPolicyResponse, UpdatePolicyResponse } from '../../../types'; import { NewPolicyData } from '../../../../../../common/types'; @@ -33,7 +34,7 @@ export const sendGetEndpointSpecificDatasources = ( ...options.query, kuery: `${ options?.query?.kuery ? options.query.kuery + ' and ' : '' - }datasources.package.name: endpoint`, + }${DATASOURCE_SAVED_OBJECT_TYPE}.package.name: endpoint`, }, }); }; diff --git a/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_details.tsx b/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_details.tsx index ea9eb292dba1a9..d9bb7eabcf7b02 100644 --- a/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_details.tsx +++ b/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_details.tsx @@ -52,7 +52,7 @@ export const PolicyDetails = React.memo(() => { const [showConfirm, setShowConfirm] = useState(false); const policyName = policyItem?.name ?? ''; - // Handle showing udpate statuses + // Handle showing update statuses useEffect(() => { if (policyUpdateStatus) { if (policyUpdateStatus.success) { @@ -79,7 +79,7 @@ export const PolicyDetails = React.memo(() => { }); } } - }, [notifications.toasts, policyItem, policyName, policyUpdateStatus]); + }, [notifications.toasts, policyName, policyUpdateStatus]); const handleBackToListOnClick = useNavigateByRouterEventHandler('/policy'); From 4a04adf8124b265f0407161391623bbcc7ee0e92 Mon Sep 17 00:00:00 2001 From: Chris Cowan Date: Tue, 28 Apr 2020 08:33:32 -0700 Subject: [PATCH 04/12] [Metrics UI] Fixes for editing alerts in alert management (#64597) * [Metrics UI] Fixes for editing alerts in alert management * Change EuiFieldSearch to use onChange instead of onSearch * Fixing groupBy * Fixing the correct groupBy --- .../alerting/metrics/expression.tsx | 103 ++++++++++-------- 1 file changed, 59 insertions(+), 44 deletions(-) diff --git a/x-pack/plugins/infra/public/components/alerting/metrics/expression.tsx b/x-pack/plugins/infra/public/components/alerting/metrics/expression.tsx index cdefffeb35c156..d4d53b81109c61 100644 --- a/x-pack/plugins/infra/public/components/alerting/metrics/expression.tsx +++ b/x-pack/plugins/infra/public/components/alerting/metrics/expression.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useCallback, useMemo, useEffect, useState } from 'react'; +import React, { ChangeEvent, useCallback, useMemo, useEffect, useState } from 'react'; import { EuiFlexGroup, EuiFlexItem, @@ -13,6 +13,7 @@ import { EuiText, EuiFormRow, EuiButtonEmpty, + EuiFieldSearch, } from '@elastic/eui'; import { IFieldType } from 'src/plugins/data/public'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -147,7 +148,7 @@ export const Expressions: React.FC = props => { const onGroupByChange = useCallback( (group: string | null) => { - setAlertParams('groupBy', group || undefined); + setAlertParams('groupBy', group || ''); }, [setAlertParams] ); @@ -215,10 +216,20 @@ export const Expressions: React.FC = props => { } setAlertParams('sourceId', source?.id); } else { - setAlertParams('criteria', [defaultExpression]); + if (!alertParams.criteria) { + setAlertParams('criteria', [defaultExpression]); + } + if (!alertParams.sourceId) { + setAlertParams('sourceId', source?.id || 'default'); + } } }, [alertsContext.metadata, defaultExpression, source]); // eslint-disable-line react-hooks/exhaustive-deps + const handleFieldSearchChange = useCallback( + (e: ChangeEvent) => onFilterQuerySubmit(e.target.value), + [onFilterQuerySubmit] + ); + return ( <> @@ -273,48 +284,52 @@ export const Expressions: React.FC = props => { - {alertsContext.metadata && ( - <> - - - - - - + {(alertsContext.metadata && ( + + )) || ( + - - - - )} + /> + )} + + + + + + ); }; From 36b4864b66d110fc14d97dbde548d4e172f5bfc6 Mon Sep 17 00:00:00 2001 From: Aleh Zasypkin Date: Tue, 28 Apr 2020 18:00:31 +0200 Subject: [PATCH 05/12] Introduce Access Agreement UI. (#63563) Co-authored-by: Ryan Keairns --- .../common/licensing/license_features.ts | 5 + .../common/licensing/license_service.test.ts | 14 +- .../common/licensing/license_service.ts | 3 + .../security/{public => common}/types.ts | 10 +- .../access_agreement_page.test.tsx.snap | 30 +++ .../_access_agreement_page.scss | 21 ++ .../access_agreement/_index.scss | 1 + .../access_agreement_app.test.ts | 62 +++++ .../access_agreement/access_agreement_app.ts | 38 +++ .../access_agreement_page.test.tsx | 160 +++++++++++++ .../access_agreement_page.tsx | 133 +++++++++++ .../authentication/access_agreement/index.ts | 7 + .../authentication/authentication_service.ts | 2 + .../authentication_state_page.test.tsx.snap | 4 +- .../authentication_state_page.test.tsx | 10 + .../authentication_state_page.tsx | 5 +- .../overwritten_session_page.test.tsx.snap | 6 +- x-pack/plugins/security/public/index.ts | 1 - .../public/session/session_timeout.test.tsx | 7 + .../public/session/session_timeout.tsx | 4 +- .../server/audit/audit_logger.test.ts | 20 +- .../security/server/audit/audit_logger.ts | 9 + .../security/server/audit/index.mock.ts | 1 + .../authentication/authenticator.test.ts | 225 +++++++++++++++++- .../server/authentication/authenticator.ts | 139 +++++++++-- .../server/authentication/index.mock.ts | 1 + .../server/authentication/index.test.ts | 4 + .../security/server/authentication/index.ts | 9 +- x-pack/plugins/security/server/config.test.ts | 45 +--- x-pack/plugins/security/server/config.ts | 19 +- x-pack/plugins/security/server/plugin.test.ts | 4 - x-pack/plugins/security/server/plugin.ts | 25 +- .../routes/authentication/common.test.ts | 60 +++++ .../server/routes/authentication/common.ts | 30 ++- .../server/routes/licensed_route_handler.ts | 18 +- .../routes/users/change_password.test.ts | 2 +- .../routes/views/access_agreement.test.ts | 177 ++++++++++++++ .../server/routes/views/access_agreement.ts | 64 +++++ .../server/routes/views/index.test.ts | 15 +- .../security/server/routes/views/index.ts | 2 + .../server/routes/views/logged_out.test.ts | 2 +- .../server/routes/views/login.test.ts | 1 + .../api_integration/apis/security/session.ts | 2 +- 43 files changed, 1297 insertions(+), 100 deletions(-) rename x-pack/plugins/security/{public => common}/types.ts (65%) create mode 100644 x-pack/plugins/security/public/authentication/access_agreement/__snapshots__/access_agreement_page.test.tsx.snap create mode 100644 x-pack/plugins/security/public/authentication/access_agreement/_access_agreement_page.scss create mode 100644 x-pack/plugins/security/public/authentication/access_agreement/_index.scss create mode 100644 x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.test.ts create mode 100644 x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.ts create mode 100644 x-pack/plugins/security/public/authentication/access_agreement/access_agreement_page.test.tsx create mode 100644 x-pack/plugins/security/public/authentication/access_agreement/access_agreement_page.tsx create mode 100644 x-pack/plugins/security/public/authentication/access_agreement/index.ts create mode 100644 x-pack/plugins/security/server/routes/views/access_agreement.test.ts create mode 100644 x-pack/plugins/security/server/routes/views/access_agreement.ts diff --git a/x-pack/plugins/security/common/licensing/license_features.ts b/x-pack/plugins/security/common/licensing/license_features.ts index 5184ab0e962bd2..571d2630b2b177 100644 --- a/x-pack/plugins/security/common/licensing/license_features.ts +++ b/x-pack/plugins/security/common/licensing/license_features.ts @@ -33,6 +33,11 @@ export interface SecurityLicenseFeatures { */ readonly showRoleMappingsManagement: boolean; + /** + * Indicates whether we allow users to access agreement UI and acknowledge it. + */ + readonly allowAccessAgreement: boolean; + /** * Indicates whether we allow users to define document level security in roles. */ diff --git a/x-pack/plugins/security/common/licensing/license_service.test.ts b/x-pack/plugins/security/common/licensing/license_service.test.ts index 5bdfa7d4886aac..9dec665614635f 100644 --- a/x-pack/plugins/security/common/licensing/license_service.test.ts +++ b/x-pack/plugins/security/common/licensing/license_service.test.ts @@ -18,6 +18,7 @@ describe('license features', function() { allowLogin: false, showLinks: false, showRoleMappingsManagement: false, + allowAccessAgreement: false, allowRoleDocumentLevelSecurity: false, allowRoleFieldLevelSecurity: false, layout: 'error-es-unavailable', @@ -37,6 +38,7 @@ describe('license features', function() { allowLogin: false, showLinks: false, showRoleMappingsManagement: false, + allowAccessAgreement: false, allowRoleDocumentLevelSecurity: false, allowRoleFieldLevelSecurity: false, layout: 'error-xpack-unavailable', @@ -60,6 +62,7 @@ describe('license features', function() { expect(subscriptionHandler.mock.calls[0]).toMatchInlineSnapshot(` Array [ Object { + "allowAccessAgreement": false, "allowLogin": false, "allowRbac": false, "allowRoleDocumentLevelSecurity": false, @@ -78,6 +81,7 @@ describe('license features', function() { expect(subscriptionHandler.mock.calls[1]).toMatchInlineSnapshot(` Array [ Object { + "allowAccessAgreement": true, "allowLogin": true, "allowRbac": true, "allowRoleDocumentLevelSecurity": true, @@ -94,7 +98,7 @@ describe('license features', function() { } }); - it('should show login page and other security elements, allow RBAC but forbid role mappings, DLS, and sub-feature privileges if license is basic.', () => { + it('should show login page and other security elements, allow RBAC but forbid paid features if license is basic.', () => { const mockRawLicense = licensingMock.createLicense({ features: { security: { isEnabled: true, isAvailable: true } }, }); @@ -109,6 +113,7 @@ describe('license features', function() { allowLogin: true, showLinks: true, showRoleMappingsManagement: false, + allowAccessAgreement: false, allowRoleDocumentLevelSecurity: false, allowRoleFieldLevelSecurity: false, allowRbac: true, @@ -131,6 +136,7 @@ describe('license features', function() { allowLogin: false, showLinks: false, showRoleMappingsManagement: false, + allowAccessAgreement: false, allowRoleDocumentLevelSecurity: false, allowRoleFieldLevelSecurity: false, allowRbac: false, @@ -138,7 +144,7 @@ describe('license features', function() { }); }); - it('should allow role mappings and sub-feature privileges, but not DLS/FLS if license = gold', () => { + it('should allow role mappings, access agreement and sub-feature privileges, but not DLS/FLS if license = gold', () => { const mockRawLicense = licensingMock.createLicense({ license: { mode: 'gold', type: 'gold' }, features: { security: { isEnabled: true, isAvailable: true } }, @@ -152,6 +158,7 @@ describe('license features', function() { allowLogin: true, showLinks: true, showRoleMappingsManagement: true, + allowAccessAgreement: true, allowRoleDocumentLevelSecurity: false, allowRoleFieldLevelSecurity: false, allowRbac: true, @@ -159,7 +166,7 @@ describe('license features', function() { }); }); - it('should allow to login, allow RBAC, role mappings, sub-feature privileges, and DLS if license >= platinum', () => { + it('should allow to login, allow RBAC, role mappings, access agreement, sub-feature privileges, and DLS if license >= platinum', () => { const mockRawLicense = licensingMock.createLicense({ license: { mode: 'platinum', type: 'platinum' }, features: { security: { isEnabled: true, isAvailable: true } }, @@ -173,6 +180,7 @@ describe('license features', function() { allowLogin: true, showLinks: true, showRoleMappingsManagement: true, + allowAccessAgreement: true, allowRoleDocumentLevelSecurity: true, allowRoleFieldLevelSecurity: true, allowRbac: true, diff --git a/x-pack/plugins/security/common/licensing/license_service.ts b/x-pack/plugins/security/common/licensing/license_service.ts index 34bc44b88e40d9..7815798d6a9f3d 100644 --- a/x-pack/plugins/security/common/licensing/license_service.ts +++ b/x-pack/plugins/security/common/licensing/license_service.ts @@ -71,6 +71,7 @@ export class SecurityLicenseService { allowLogin: false, showLinks: false, showRoleMappingsManagement: false, + allowAccessAgreement: false, allowRoleDocumentLevelSecurity: false, allowRoleFieldLevelSecurity: false, allowRbac: false, @@ -88,6 +89,7 @@ export class SecurityLicenseService { allowLogin: false, showLinks: false, showRoleMappingsManagement: false, + allowAccessAgreement: false, allowRoleDocumentLevelSecurity: false, allowRoleFieldLevelSecurity: false, allowRbac: false, @@ -102,6 +104,7 @@ export class SecurityLicenseService { allowLogin: true, showLinks: true, showRoleMappingsManagement: isLicenseGoldOrBetter, + allowAccessAgreement: isLicenseGoldOrBetter, allowSubFeaturePrivileges: isLicenseGoldOrBetter, // Only platinum and trial licenses are compliant with field- and document-level security. allowRoleDocumentLevelSecurity: isLicensePlatinumOrBetter, diff --git a/x-pack/plugins/security/public/types.ts b/x-pack/plugins/security/common/types.ts similarity index 65% rename from x-pack/plugins/security/public/types.ts rename to x-pack/plugins/security/common/types.ts index e9c4b6e281cf3e..c668c6ccf71d16 100644 --- a/x-pack/plugins/security/public/types.ts +++ b/x-pack/plugins/security/common/types.ts @@ -4,9 +4,17 @@ * you may not use this file except in compliance with the Elastic License. */ +/** + * Type and name tuple to identify provider used to authenticate user. + */ +export interface AuthenticationProvider { + type: string; + name: string; +} + export interface SessionInfo { now: number; idleTimeoutExpiration: number | null; lifespanExpiration: number | null; - provider: string; + provider: AuthenticationProvider; } diff --git a/x-pack/plugins/security/public/authentication/access_agreement/__snapshots__/access_agreement_page.test.tsx.snap b/x-pack/plugins/security/public/authentication/access_agreement/__snapshots__/access_agreement_page.test.tsx.snap new file mode 100644 index 00000000000000..2227cbe8a495cf --- /dev/null +++ b/x-pack/plugins/security/public/authentication/access_agreement/__snapshots__/access_agreement_page.test.tsx.snap @@ -0,0 +1,30 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`AccessAgreementPage renders as expected when state is available 1`] = ` + +
+

+ This is + + link + +

+
+
+`; diff --git a/x-pack/plugins/security/public/authentication/access_agreement/_access_agreement_page.scss b/x-pack/plugins/security/public/authentication/access_agreement/_access_agreement_page.scss new file mode 100644 index 00000000000000..08e7be248619f0 --- /dev/null +++ b/x-pack/plugins/security/public/authentication/access_agreement/_access_agreement_page.scss @@ -0,0 +1,21 @@ +.secAccessAgreementPage .secAuthenticationStatePage__content { + max-width: 600px; +} + +.secAccessAgreementPage__textWrapper { + overflow-y: hidden; +} + +.secAccessAgreementPage__text { + @include euiYScrollWithShadows; + max-height: 400px; + padding: $euiSize $euiSizeL 0; +} + +.secAccessAgreementPage__footer { + padding: $euiSize $euiSizeL $euiSizeL; +} + +.secAccessAgreementPage__footerInner { + text-align: left; +} diff --git a/x-pack/plugins/security/public/authentication/access_agreement/_index.scss b/x-pack/plugins/security/public/authentication/access_agreement/_index.scss new file mode 100644 index 00000000000000..dbab8347b096f1 --- /dev/null +++ b/x-pack/plugins/security/public/authentication/access_agreement/_index.scss @@ -0,0 +1 @@ +@import './access_agreement_page'; diff --git a/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.test.ts b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.test.ts new file mode 100644 index 00000000000000..add2db6a3c170d --- /dev/null +++ b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.test.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +jest.mock('./access_agreement_page'); + +import { AppMount, ScopedHistory } from 'src/core/public'; +import { accessAgreementApp } from './access_agreement_app'; + +import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; + +describe('accessAgreementApp', () => { + it('properly registers application', () => { + const coreSetupMock = coreMock.createSetup(); + + accessAgreementApp.create({ + application: coreSetupMock.application, + getStartServices: coreSetupMock.getStartServices, + }); + + expect(coreSetupMock.application.register).toHaveBeenCalledTimes(1); + + const [[appRegistration]] = coreSetupMock.application.register.mock.calls; + expect(appRegistration).toEqual({ + id: 'security_access_agreement', + chromeless: true, + appRoute: '/security/access_agreement', + title: 'Access Agreement', + mount: expect.any(Function), + }); + }); + + it('properly renders application', async () => { + const coreSetupMock = coreMock.createSetup(); + const coreStartMock = coreMock.createStart(); + coreSetupMock.getStartServices.mockResolvedValue([coreStartMock, {}, {}]); + const containerMock = document.createElement('div'); + + accessAgreementApp.create({ + application: coreSetupMock.application, + getStartServices: coreSetupMock.getStartServices, + }); + + const [[{ mount }]] = coreSetupMock.application.register.mock.calls; + await (mount as AppMount)({ + element: containerMock, + appBasePath: '', + onAppLeave: jest.fn(), + history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + }); + + const mockRenderApp = jest.requireMock('./access_agreement_page').renderAccessAgreementPage; + expect(mockRenderApp).toHaveBeenCalledTimes(1); + expect(mockRenderApp).toHaveBeenCalledWith(coreStartMock.i18n, containerMock, { + http: coreStartMock.http, + notifications: coreStartMock.notifications, + fatalErrors: coreStartMock.fatalErrors, + }); + }); +}); diff --git a/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.ts b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.ts new file mode 100644 index 00000000000000..156a76542a28fb --- /dev/null +++ b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.ts @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +import { StartServicesAccessor, ApplicationSetup, AppMountParameters } from 'src/core/public'; + +interface CreateDeps { + application: ApplicationSetup; + getStartServices: StartServicesAccessor; +} + +export const accessAgreementApp = Object.freeze({ + id: 'security_access_agreement', + create({ application, getStartServices }: CreateDeps) { + application.register({ + id: this.id, + title: i18n.translate('xpack.security.accessAgreementAppTitle', { + defaultMessage: 'Access Agreement', + }), + chromeless: true, + appRoute: '/security/access_agreement', + async mount({ element }: AppMountParameters) { + const [[coreStart], { renderAccessAgreementPage }] = await Promise.all([ + getStartServices(), + import('./access_agreement_page'), + ]); + return renderAccessAgreementPage(coreStart.i18n, element, { + http: coreStart.http, + notifications: coreStart.notifications, + fatalErrors: coreStart.fatalErrors, + }); + }, + }); + }, +}); diff --git a/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_page.test.tsx b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_page.test.tsx new file mode 100644 index 00000000000000..89b7489d45ebb2 --- /dev/null +++ b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_page.test.tsx @@ -0,0 +1,160 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import ReactMarkdown from 'react-markdown'; +import { EuiLoadingContent } from '@elastic/eui'; +import { act } from '@testing-library/react'; +import { mountWithIntl, nextTick } from 'test_utils/enzyme_helpers'; +import { findTestSubject } from 'test_utils/find_test_subject'; +import { coreMock } from '../../../../../../src/core/public/mocks'; +import { AccessAgreementPage } from './access_agreement_page'; + +describe('AccessAgreementPage', () => { + beforeAll(() => { + Object.defineProperty(window, 'location', { + value: { href: 'http://some-host/bar', protocol: 'http' }, + writable: true, + }); + }); + + afterAll(() => { + delete (window as any).location; + }); + + it('renders as expected when state is available', async () => { + const coreStartMock = coreMock.createStart(); + coreStartMock.http.get.mockResolvedValue({ accessAgreement: 'This is [link](../link)' }); + + const wrapper = mountWithIntl( + + ); + + expect(wrapper.exists(EuiLoadingContent)).toBe(true); + expect(wrapper.exists(ReactMarkdown)).toBe(false); + + await act(async () => { + await nextTick(); + wrapper.update(); + }); + + expect(wrapper.find(ReactMarkdown)).toMatchSnapshot(); + expect(wrapper.exists(EuiLoadingContent)).toBe(false); + + expect(coreStartMock.http.get).toHaveBeenCalledTimes(1); + expect(coreStartMock.http.get).toHaveBeenCalledWith( + '/internal/security/access_agreement/state' + ); + expect(coreStartMock.fatalErrors.add).not.toHaveBeenCalled(); + }); + + it('fails when state is not available', async () => { + const coreStartMock = coreMock.createStart(); + const error = Symbol(); + coreStartMock.http.get.mockRejectedValue(error); + + const wrapper = mountWithIntl( + + ); + + await act(async () => { + await nextTick(); + wrapper.update(); + }); + + expect(coreStartMock.http.get).toHaveBeenCalledTimes(1); + expect(coreStartMock.http.get).toHaveBeenCalledWith( + '/internal/security/access_agreement/state' + ); + expect(coreStartMock.fatalErrors.add).toHaveBeenCalledTimes(1); + expect(coreStartMock.fatalErrors.add).toHaveBeenCalledWith(error); + }); + + it('properly redirects after successful acknowledgement', async () => { + const coreStartMock = coreMock.createStart({ basePath: '/some-base-path' }); + coreStartMock.http.get.mockResolvedValue({ accessAgreement: 'This is [link](../link)' }); + coreStartMock.http.post.mockResolvedValue(undefined); + + window.location.href = `https://some-host/security/access_agreement?next=${encodeURIComponent( + '/some-base-path/app/kibana#/home?_g=()' + )}`; + const wrapper = mountWithIntl( + + ); + + await act(async () => { + await nextTick(); + wrapper.update(); + }); + + findTestSubject(wrapper, 'accessAgreementAcknowledge').simulate('click'); + + await act(async () => { + await nextTick(); + }); + + expect(coreStartMock.http.post).toHaveBeenCalledTimes(1); + expect(coreStartMock.http.post).toHaveBeenCalledWith( + '/internal/security/access_agreement/acknowledge' + ); + + expect(window.location.href).toBe('/some-base-path/app/kibana#/home?_g=()'); + expect(coreStartMock.notifications.toasts.addError).not.toHaveBeenCalled(); + }); + + it('shows error toast if acknowledgement fails', async () => { + const currentURL = `https://some-host/login?next=${encodeURIComponent( + '/some-base-path/app/kibana#/home?_g=()' + )}`; + + const failureReason = new Error('Oh no!'); + const coreStartMock = coreMock.createStart({ basePath: '/some-base-path' }); + coreStartMock.http.get.mockResolvedValue({ accessAgreement: 'This is [link](../link)' }); + coreStartMock.http.post.mockRejectedValue(failureReason); + + window.location.href = currentURL; + const wrapper = mountWithIntl( + + ); + + await act(async () => { + await nextTick(); + wrapper.update(); + }); + + findTestSubject(wrapper, 'accessAgreementAcknowledge').simulate('click'); + + await act(async () => { + await nextTick(); + }); + + expect(coreStartMock.http.post).toHaveBeenCalledTimes(1); + expect(coreStartMock.http.post).toHaveBeenCalledWith( + '/internal/security/access_agreement/acknowledge' + ); + + expect(window.location.href).toBe(currentURL); + expect(coreStartMock.notifications.toasts.addError).toHaveBeenCalledWith(failureReason, { + title: 'Could not acknowledge access agreement.', + }); + }); +}); diff --git a/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_page.tsx b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_page.tsx new file mode 100644 index 00000000000000..0315e229c678b9 --- /dev/null +++ b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_page.tsx @@ -0,0 +1,133 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import './_index.scss'; + +import React, { FormEvent, MouseEvent, useCallback, useEffect, useState } from 'react'; +import ReactDOM from 'react-dom'; +import ReactMarkdown from 'react-markdown'; +import { + EuiButton, + EuiPanel, + EuiFlexGroup, + EuiFlexItem, + EuiLoadingContent, + EuiSpacer, + EuiText, +} from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { CoreStart, FatalErrorsStart, HttpStart, NotificationsStart } from 'src/core/public'; + +import { parseNext } from '../../../common/parse_next'; +import { AuthenticationStatePage } from '../components'; + +interface Props { + http: HttpStart; + notifications: NotificationsStart; + fatalErrors: FatalErrorsStart; +} + +export function AccessAgreementPage({ http, fatalErrors, notifications }: Props) { + const [isLoading, setIsLoading] = useState(false); + + const [accessAgreement, setAccessAgreement] = useState(null); + useEffect(() => { + http + .get<{ accessAgreement: string }>('/internal/security/access_agreement/state') + .then(response => setAccessAgreement(response.accessAgreement)) + .catch(err => fatalErrors.add(err)); + }, [http, fatalErrors]); + + const onAcknowledge = useCallback( + async (e: MouseEvent | FormEvent) => { + e.preventDefault(); + + try { + setIsLoading(true); + await http.post('/internal/security/access_agreement/acknowledge'); + window.location.href = parseNext(window.location.href, http.basePath.serverBasePath); + } catch (err) { + notifications.toasts.addError(err, { + title: i18n.translate('xpack.security.accessAgreement.acknowledgeErrorMessage', { + defaultMessage: 'Could not acknowledge access agreement.', + }), + }); + + setIsLoading(false); + } + }, + [http, notifications] + ); + + const content = accessAgreement ? ( +
+ + + +
+ + {accessAgreement} + +
+
+ +
+ + + +
+
+
+
+
+ ) : ( + + + + ); + + return ( + + } + > + {content} + + + ); +} + +export function renderAccessAgreementPage( + i18nStart: CoreStart['i18n'], + element: Element, + props: Props +) { + ReactDOM.render( + + + , + element + ); + + return () => ReactDOM.unmountComponentAtNode(element); +} diff --git a/x-pack/plugins/security/public/authentication/access_agreement/index.ts b/x-pack/plugins/security/public/authentication/access_agreement/index.ts new file mode 100644 index 00000000000000..8f7661a89a269d --- /dev/null +++ b/x-pack/plugins/security/public/authentication/access_agreement/index.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { accessAgreementApp } from './access_agreement_app'; diff --git a/x-pack/plugins/security/public/authentication/authentication_service.ts b/x-pack/plugins/security/public/authentication/authentication_service.ts index 2e73b8cd044826..6657f5c0a900cf 100644 --- a/x-pack/plugins/security/public/authentication/authentication_service.ts +++ b/x-pack/plugins/security/public/authentication/authentication_service.ts @@ -8,6 +8,7 @@ import { ApplicationSetup, StartServicesAccessor, HttpSetup } from 'src/core/pub import { AuthenticatedUser } from '../../common/model'; import { ConfigType } from '../config'; import { PluginStartDependencies } from '../plugin'; +import { accessAgreementApp } from './access_agreement'; import { loginApp } from './login'; import { logoutApp } from './logout'; import { loggedOutApp } from './logged_out'; @@ -46,6 +47,7 @@ export class AuthenticationService { ((await http.get('/internal/security/api_key/_enabled')) as { apiKeysEnabled: boolean }) .apiKeysEnabled; + accessAgreementApp.create({ application, getStartServices }); loginApp.create({ application, config, getStartServices, http }); logoutApp.create({ application, http }); loggedOutApp.create({ application, getStartServices, http }); diff --git a/x-pack/plugins/security/public/authentication/components/authentication_state_page/__snapshots__/authentication_state_page.test.tsx.snap b/x-pack/plugins/security/public/authentication/components/authentication_state_page/__snapshots__/authentication_state_page.test.tsx.snap index 3590fa460a4010..585dc368da7077 100644 --- a/x-pack/plugins/security/public/authentication/components/authentication_state_page/__snapshots__/authentication_state_page.test.tsx.snap +++ b/x-pack/plugins/security/public/authentication/components/authentication_state_page/__snapshots__/authentication_state_page.test.tsx.snap @@ -2,7 +2,7 @@ exports[`AuthenticationStatePage renders 1`] = `
{ ) ).toMatchSnapshot(); }); + + it('renders with custom CSS class', () => { + expect( + shallowWithIntl( + + hello world + + ).exists('.secAuthenticationStatePage.customClassName') + ).toBe(true); + }); }); diff --git a/x-pack/plugins/security/public/authentication/components/authentication_state_page/authentication_state_page.tsx b/x-pack/plugins/security/public/authentication/components/authentication_state_page/authentication_state_page.tsx index 66176129407cd0..7567f455bcca67 100644 --- a/x-pack/plugins/security/public/authentication/components/authentication_state_page/authentication_state_page.tsx +++ b/x-pack/plugins/security/public/authentication/components/authentication_state_page/authentication_state_page.tsx @@ -10,16 +10,17 @@ import { EuiIcon, EuiSpacer, EuiTitle } from '@elastic/eui'; import React from 'react'; interface Props { + className?: string; title: React.ReactNode; } export const AuthenticationStatePage: React.FC = props => ( -
+
- +

{props.title}

diff --git a/x-pack/plugins/security/public/authentication/overwritten_session/__snapshots__/overwritten_session_page.test.tsx.snap b/x-pack/plugins/security/public/authentication/overwritten_session/__snapshots__/overwritten_session_page.test.tsx.snap index 2ff760891fa4e2..02b1a7d0d3fa03 100644 --- a/x-pack/plugins/security/public/authentication/overwritten_session/__snapshots__/overwritten_session_page.test.tsx.snap +++ b/x-pack/plugins/security/public/authentication/overwritten_session/__snapshots__/overwritten_session_page.test.tsx.snap @@ -11,7 +11,7 @@ exports[`OverwrittenSessionPage renders as expected 1`] = ` } >
diff --git a/x-pack/plugins/security/public/index.ts b/x-pack/plugins/security/public/index.ts index 458f7ab801fdf9..fc4e158652a0ae 100644 --- a/x-pack/plugins/security/public/index.ts +++ b/x-pack/plugins/security/public/index.ts @@ -15,7 +15,6 @@ import { } from './plugin'; export { SecurityPluginSetup, SecurityPluginStart }; -export { SessionInfo } from './types'; export { AuthenticatedUser } from '../common/model'; export { SecurityLicense, SecurityLicenseFeatures } from '../common/licensing'; diff --git a/x-pack/plugins/security/public/session/session_timeout.test.tsx b/x-pack/plugins/security/public/session/session_timeout.test.tsx index eca3e7d6727df8..11aadcff377ef7 100644 --- a/x-pack/plugins/security/public/session/session_timeout.test.tsx +++ b/x-pack/plugins/security/public/session/session_timeout.test.tsx @@ -74,6 +74,7 @@ describe('Session Timeout', () => { now, idleTimeoutExpiration: now + 2 * 60 * 1000, lifespanExpiration: null, + provider: { type: 'basic', name: 'basic1' }, }; let notifications: ReturnType['notifications']; let http: ReturnType['http']; @@ -192,6 +193,7 @@ describe('Session Timeout', () => { now, idleTimeoutExpiration: null, lifespanExpiration: now + 2 * 60 * 1000, + provider: { type: 'basic', name: 'basic1' }, }; http.fetch.mockResolvedValue(sessionInfo); await sessionTimeout.start(); @@ -225,6 +227,7 @@ describe('Session Timeout', () => { now, idleTimeoutExpiration: null, lifespanExpiration: now + 2 * 60 * 1000, + provider: { type: 'basic', name: 'basic1' }, }; http.fetch.mockResolvedValue(sessionInfo); await sessionTimeout.start(); @@ -251,6 +254,7 @@ describe('Session Timeout', () => { now: now + elapsed, idleTimeoutExpiration: now + elapsed + 2 * 60 * 1000, lifespanExpiration: null, + provider: { type: 'basic', name: 'basic1' }, }); await sessionTimeout.extend('/foo'); expect(http.fetch).toHaveBeenCalledTimes(3); @@ -303,6 +307,7 @@ describe('Session Timeout', () => { now, idleTimeoutExpiration: now + 64 * 1000, lifespanExpiration: null, + provider: { type: 'basic', name: 'basic1' }, }); await sessionTimeout.start(); expect(http.fetch).toHaveBeenCalled(); @@ -336,6 +341,7 @@ describe('Session Timeout', () => { now: now + elapsed, idleTimeoutExpiration: now + elapsed + 2 * 60 * 1000, lifespanExpiration: null, + provider: { type: 'basic', name: 'basic1' }, }; http.fetch.mockResolvedValue(sessionInfo); await sessionTimeout.extend('/foo'); @@ -358,6 +364,7 @@ describe('Session Timeout', () => { now, idleTimeoutExpiration: now + 4 * 1000, lifespanExpiration: null, + provider: { type: 'basic', name: 'basic1' }, }); await sessionTimeout.start(); diff --git a/x-pack/plugins/security/public/session/session_timeout.tsx b/x-pack/plugins/security/public/session/session_timeout.tsx index bd6dbad7dbf149..b06d8fffd4b629 100644 --- a/x-pack/plugins/security/public/session/session_timeout.tsx +++ b/x-pack/plugins/security/public/session/session_timeout.tsx @@ -6,10 +6,10 @@ import { NotificationsSetup, Toast, HttpSetup, ToastInput } from 'src/core/public'; import { BroadcastChannel } from 'broadcast-channel'; +import { SessionInfo } from '../../common/types'; import { createToast as createIdleTimeoutToast } from './session_idle_timeout_warning'; import { createToast as createLifespanToast } from './session_lifespan_warning'; import { ISessionExpired } from './session_expired'; -import { SessionInfo } from '../types'; /** * Client session timeout is decreased by this number so that Kibana server @@ -127,7 +127,7 @@ export class SessionTimeout implements ISessionTimeout { this.sessionInfo = sessionInfo; // save the provider name in session storage, we will need it when we log out const key = `${this.tenant}/session_provider`; - sessionStorage.setItem(key, sessionInfo.provider); + sessionStorage.setItem(key, sessionInfo.provider.name); const { timeout, isLifespanTimeout } = this.getTimeout(); if (timeout == null) { diff --git a/x-pack/plugins/security/server/audit/audit_logger.test.ts b/x-pack/plugins/security/server/audit/audit_logger.test.ts index f7ee210a21a741..4dfd69a2ccb1ff 100644 --- a/x-pack/plugins/security/server/audit/audit_logger.test.ts +++ b/x-pack/plugins/security/server/audit/audit_logger.test.ts @@ -62,7 +62,7 @@ describe(`#savedObjectsAuthorizationFailure`, () => { }); describe(`#savedObjectsAuthorizationSuccess`, () => { - test('logs via auditLogger when xpack.security.audit.enabled is true', () => { + test('logs via auditLogger', () => { const auditLogger = createMockAuditLogger(); const securityAuditLogger = new SecurityAuditLogger(() => auditLogger); const username = 'foo-user'; @@ -92,3 +92,21 @@ describe(`#savedObjectsAuthorizationSuccess`, () => { ); }); }); + +describe(`#accessAgreementAcknowledged`, () => { + test('logs via auditLogger', () => { + const auditLogger = createMockAuditLogger(); + const securityAuditLogger = new SecurityAuditLogger(() => auditLogger); + const username = 'foo-user'; + const provider = { type: 'saml', name: 'saml1' }; + + securityAuditLogger.accessAgreementAcknowledged(username, provider); + + expect(auditLogger.log).toHaveBeenCalledTimes(1); + expect(auditLogger.log).toHaveBeenCalledWith( + 'access_agreement_acknowledged', + 'foo-user acknowledged access agreement (saml/saml1).', + { username, provider } + ); + }); +}); diff --git a/x-pack/plugins/security/server/audit/audit_logger.ts b/x-pack/plugins/security/server/audit/audit_logger.ts index 40b525b5d21888..d7243ecbe13f87 100644 --- a/x-pack/plugins/security/server/audit/audit_logger.ts +++ b/x-pack/plugins/security/server/audit/audit_logger.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { AuthenticationProvider } from '../../common/types'; import { LegacyAPI } from '../plugin'; export class SecurityAuditLogger { @@ -57,4 +58,12 @@ export class SecurityAuditLogger { } ); } + + accessAgreementAcknowledged(username: string, provider: AuthenticationProvider) { + this.getAuditLogger().log( + 'access_agreement_acknowledged', + `${username} acknowledged access agreement (${provider.type}/${provider.name}).`, + { username, provider } + ); + } } diff --git a/x-pack/plugins/security/server/audit/index.mock.ts b/x-pack/plugins/security/server/audit/index.mock.ts index c14b98ed4781eb..888aa3361faf04 100644 --- a/x-pack/plugins/security/server/audit/index.mock.ts +++ b/x-pack/plugins/security/server/audit/index.mock.ts @@ -11,6 +11,7 @@ export const securityAuditLoggerMock = { return ({ savedObjectsAuthorizationFailure: jest.fn(), savedObjectsAuthorizationSuccess: jest.fn(), + accessAgreementAcknowledged: jest.fn(), } as unknown) as jest.Mocked; }, }; diff --git a/x-pack/plugins/security/server/authentication/authenticator.test.ts b/x-pack/plugins/security/server/authentication/authenticator.test.ts index a595b63faaf9b3..49b7b40659cfc1 100644 --- a/x-pack/plugins/security/server/authentication/authenticator.test.ts +++ b/x-pack/plugins/security/server/authentication/authenticator.test.ts @@ -20,7 +20,10 @@ import { elasticsearchServiceMock, sessionStorageMock, } from '../../../../../src/core/server/mocks'; +import { licenseMock } from '../../common/licensing/index.mock'; import { mockAuthenticatedUser } from '../../common/model/authenticated_user.mock'; +import { securityAuditLoggerMock } from '../audit/index.mock'; +import { SecurityLicenseFeatures } from '../../common/licensing'; import { ConfigSchema, createConfig } from '../config'; import { AuthenticationResult } from './authentication_result'; import { Authenticator, AuthenticatorOptions, ProviderSession } from './authenticator'; @@ -39,8 +42,11 @@ function getMockOptions({ selector?: AuthenticatorOptions['config']['authc']['selector']; } = {}) { return { + auditLogger: securityAuditLoggerMock.create(), + getCurrentUser: jest.fn(), clusterClient: elasticsearchServiceMock.createClusterClient(), basePath: httpServiceMock.createSetupContract().basePath, + license: licenseMock.create(), loggers: loggingServiceMock.create(), config: createConfig( ConfigSchema.validate({ session, authc: { selector, providers, http } }), @@ -1108,6 +1114,141 @@ describe('Authenticator', () => { expect(mockBasicAuthenticationProvider.authenticate).not.toHaveBeenCalled(); }); }); + + describe('with Access Agreement', () => { + const mockUser = mockAuthenticatedUser(); + beforeEach(() => { + mockOptions = getMockOptions({ + providers: { + basic: { basic1: { order: 0, accessAgreement: { message: 'some notice' } } }, + }, + }); + mockOptions.sessionStorageFactory.asScoped.mockReturnValue(mockSessionStorage); + mockOptions.license.getFeatures.mockReturnValue({ + allowAccessAgreement: true, + } as SecurityLicenseFeatures); + + mockBasicAuthenticationProvider.authenticate.mockResolvedValue( + AuthenticationResult.succeeded(mockUser) + ); + + authenticator = new Authenticator(mockOptions); + }); + + it('does not redirect to Access Agreement if there is no active session', async () => { + const request = httpServerMock.createKibanaRequest(); + mockSessionStorage.get.mockResolvedValue(null); + + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.succeeded(mockUser) + ); + }); + + it('does not redirect AJAX requests to Access Agreement', async () => { + const request = httpServerMock.createKibanaRequest({ headers: { 'kbn-xsrf': 'xsrf' } }); + mockSessionStorage.get.mockResolvedValue(mockSessVal); + + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.succeeded(mockUser) + ); + }); + + it('does not redirect to Access Agreement if request cannot be handled', async () => { + const request = httpServerMock.createKibanaRequest(); + mockSessionStorage.get.mockResolvedValue(mockSessVal); + + mockBasicAuthenticationProvider.authenticate.mockResolvedValue( + AuthenticationResult.notHandled() + ); + + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.notHandled() + ); + }); + + it('does not redirect to Access Agreement if authentication fails', async () => { + const request = httpServerMock.createKibanaRequest(); + mockSessionStorage.get.mockResolvedValue(mockSessVal); + + const failureReason = new Error('something went wrong'); + mockBasicAuthenticationProvider.authenticate.mockResolvedValue( + AuthenticationResult.failed(failureReason) + ); + + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.failed(failureReason) + ); + }); + + it('does not redirect to Access Agreement if redirect is required to complete authentication', async () => { + const request = httpServerMock.createKibanaRequest(); + mockSessionStorage.get.mockResolvedValue(mockSessVal); + + mockBasicAuthenticationProvider.authenticate.mockResolvedValue( + AuthenticationResult.redirectTo('/some-url') + ); + + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.redirectTo('/some-url') + ); + }); + + it('does not redirect to Access Agreement if user has already acknowledged it', async () => { + const request = httpServerMock.createKibanaRequest(); + mockSessionStorage.get.mockResolvedValue({ + ...mockSessVal, + accessAgreementAcknowledged: true, + }); + + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.succeeded(mockUser) + ); + }); + + it('does not redirect to Access Agreement its own requests', async () => { + const request = httpServerMock.createKibanaRequest({ path: '/security/access_agreement' }); + mockSessionStorage.get.mockResolvedValue(mockSessVal); + + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.succeeded(mockUser) + ); + }); + + it('does not redirect to Access Agreement if it is not configured', async () => { + mockOptions = getMockOptions({ providers: { basic: { basic1: { order: 0 } } } }); + mockOptions.sessionStorageFactory.asScoped.mockReturnValue(mockSessionStorage); + mockSessionStorage.get.mockResolvedValue(mockSessVal); + authenticator = new Authenticator(mockOptions); + + const request = httpServerMock.createKibanaRequest(); + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.succeeded(mockUser) + ); + }); + + it('does not redirect to Access Agreement if license doesnt allow it.', async () => { + const request = httpServerMock.createKibanaRequest(); + mockSessionStorage.get.mockResolvedValue(mockSessVal); + mockOptions.license.getFeatures.mockReturnValue({ + allowAccessAgreement: false, + } as SecurityLicenseFeatures); + + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.succeeded(mockUser) + ); + }); + + it('redirects to Access Agreement when needed.', async () => { + mockSessionStorage.get.mockResolvedValue(mockSessVal); + + const request = httpServerMock.createKibanaRequest(); + await expect(authenticator.authenticate(request)).resolves.toEqual( + AuthenticationResult.redirectTo( + '/mock-server-basepath/security/access_agreement?next=%2Fmock-server-basepath%2Fpath' + ) + ); + }); + }); }); describe('`logout` method', () => { @@ -1228,13 +1369,13 @@ describe('Authenticator', () => { now: currentDate, idleTimeoutExpiration: currentDate + 60000, lifespanExpiration: currentDate + 120000, - provider: 'basic1', + provider: { type: 'basic' as 'basic', name: 'basic1' }, }; mockSessionStorage.get.mockResolvedValue({ idleTimeoutExpiration: mockInfo.idleTimeoutExpiration, lifespanExpiration: mockInfo.lifespanExpiration, state, - provider: { type: 'basic', name: mockInfo.provider }, + provider: mockInfo.provider, path: mockOptions.basePath.serverBasePath, }); jest.spyOn(Date, 'now').mockImplementation(() => currentDate); @@ -1274,4 +1415,84 @@ describe('Authenticator', () => { expect(authenticator.isProviderTypeEnabled('saml')).toBe(true); }); }); + + describe('`acknowledgeAccessAgreement` method', () => { + let authenticator: Authenticator; + let mockOptions: ReturnType; + let mockSessionStorage: jest.Mocked>; + let mockSessionValue: any; + beforeEach(() => { + mockOptions = getMockOptions({ providers: { basic: { basic1: { order: 0 } } } }); + mockSessionStorage = sessionStorageMock.create(); + mockOptions.sessionStorageFactory.asScoped.mockReturnValue(mockSessionStorage); + mockSessionValue = { + idleTimeoutExpiration: null, + lifespanExpiration: null, + state: { authorization: 'Basic xxx' }, + provider: { type: 'basic', name: 'basic1' }, + path: mockOptions.basePath.serverBasePath, + }; + mockSessionStorage.get.mockResolvedValue(mockSessionValue); + mockOptions.getCurrentUser.mockReturnValue(mockAuthenticatedUser()); + mockOptions.license.getFeatures.mockReturnValue({ + allowAccessAgreement: true, + } as SecurityLicenseFeatures); + + authenticator = new Authenticator(mockOptions); + }); + + it('fails if user is not authenticated', async () => { + mockOptions.getCurrentUser.mockReturnValue(null); + + await expect( + authenticator.acknowledgeAccessAgreement(httpServerMock.createKibanaRequest()) + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Cannot acknowledge access agreement for unauthenticated user."` + ); + + expect(mockSessionStorage.set).not.toHaveBeenCalled(); + }); + + it('fails if cannot retrieve user session', async () => { + mockSessionStorage.get.mockResolvedValue(null); + + await expect( + authenticator.acknowledgeAccessAgreement(httpServerMock.createKibanaRequest()) + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Cannot acknowledge access agreement for unauthenticated user."` + ); + + expect(mockSessionStorage.set).not.toHaveBeenCalled(); + }); + + it('fails if license doesn allow access agreement acknowledgement', async () => { + mockOptions.license.getFeatures.mockReturnValue({ + allowAccessAgreement: false, + } as SecurityLicenseFeatures); + + await expect( + authenticator.acknowledgeAccessAgreement(httpServerMock.createKibanaRequest()) + ).rejects.toThrowErrorMatchingInlineSnapshot( + `"Current license does not allow access agreement acknowledgement."` + ); + + expect(mockSessionStorage.set).not.toHaveBeenCalled(); + }); + + it('properly acknowledges access agreement for the authenticated user', async () => { + await authenticator.acknowledgeAccessAgreement(httpServerMock.createKibanaRequest()); + + expect(mockSessionStorage.set).toHaveBeenCalledTimes(1); + expect(mockSessionStorage.set).toHaveBeenCalledWith({ + ...mockSessionValue, + accessAgreementAcknowledged: true, + }); + + expect(mockOptions.auditLogger.accessAgreementAcknowledged).toHaveBeenCalledTimes(1); + expect(mockOptions.auditLogger.accessAgreementAcknowledged).toHaveBeenCalledWith('user', { + type: 'basic', + name: 'basic1', + }); + }); + }); }); diff --git a/x-pack/plugins/security/server/authentication/authenticator.ts b/x-pack/plugins/security/server/authentication/authenticator.ts index caf5b485d05e35..58dea2b23e5463 100644 --- a/x-pack/plugins/security/server/authentication/authenticator.ts +++ b/x-pack/plugins/security/server/authentication/authenticator.ts @@ -14,6 +14,10 @@ import { HttpServiceSetup, IClusterClient, } from '../../../../../src/core/server'; +import { SecurityLicense } from '../../common/licensing'; +import { AuthenticatedUser } from '../../common/model'; +import { AuthenticationProvider, SessionInfo } from '../../common/types'; +import { SecurityAuditLogger } from '../audit'; import { ConfigType } from '../config'; import { getErrorStatusCode } from '../errors'; @@ -32,7 +36,6 @@ import { import { AuthenticationResult } from './authentication_result'; import { DeauthenticationResult } from './deauthentication_result'; import { Tokens } from './tokens'; -import { SessionInfo } from '../../public'; import { canRedirectRequest } from './can_redirect_request'; import { HTTPAuthorizationHeader } from './http_authentication'; @@ -43,7 +46,7 @@ export interface ProviderSession { /** * Name and type of the provider this session belongs to. */ - provider: { type: string; name: string }; + provider: AuthenticationProvider; /** * The Unix time in ms when the session should be considered expired. If `null`, session will stay @@ -67,6 +70,11 @@ export interface ProviderSession { * Cookie "Path" attribute that is validated against the current Kibana server configuration. */ path: string; + + /** + * Indicates whether user acknowledged access agreement or not. + */ + accessAgreementAcknowledged?: boolean; } /** @@ -76,7 +84,7 @@ export interface ProviderLoginAttempt { /** * Name or type of the provider this login attempt is targeted for. */ - provider: { name: string } | { type: string }; + provider: Pick | Pick; /** * Login attempt can have any form and defined by the specific provider. @@ -85,8 +93,11 @@ export interface ProviderLoginAttempt { } export interface AuthenticatorOptions { + auditLogger: SecurityAuditLogger; + getCurrentUser: (request: KibanaRequest) => AuthenticatedUser | null; config: Pick; basePath: HttpServiceSetup['basePath']; + license: SecurityLicense; loggers: LoggerFactory; clusterClient: IClusterClient; sessionStorageFactory: SessionStorageFactory; @@ -109,6 +120,11 @@ const providerMap = new Map< [PKIAuthenticationProvider.type, PKIAuthenticationProvider], ]); +/** + * The route to the access agreement UI. + */ +const ACCESS_AGREEMENT_ROUTE = '/security/access_agreement'; + function assertRequest(request: KibanaRequest) { if (!(request instanceof KibanaRequest)) { throw new Error(`Request should be a valid "KibanaRequest" instance, was [${typeof request}].`); @@ -135,7 +151,7 @@ function isLoginAttemptWithProviderName( function isLoginAttemptWithProviderType( attempt: unknown -): attempt is { value: unknown; provider: { type: string } } { +): attempt is { value: unknown; provider: Pick } { return ( typeof attempt === 'object' && (attempt as any)?.provider?.type && @@ -341,14 +357,7 @@ export class Authenticator { const sessionStorage = this.options.sessionStorageFactory.asScoped(request); const existingSession = await this.getSessionValue(sessionStorage); - // If request doesn't have any session information, isn't attributed with HTTP Authorization - // header and Login Selector is enabled, we must redirect user to the login selector. - const useLoginSelector = - !existingSession && - this.options.config.authc.selector.enabled && - canRedirectRequest(request) && - HTTPAuthorizationHeader.parseFromRequest(request) == null; - if (useLoginSelector) { + if (this.shouldRedirectToLoginSelector(request, existingSession)) { this.logger.debug('Redirecting request to Login Selector.'); return AuthenticationResult.redirectTo( `${this.options.basePath.serverBasePath}/login?next=${encodeURIComponent( @@ -368,7 +377,7 @@ export class Authenticator { ownsSession ? existingSession!.state : null ); - this.updateSessionValue(sessionStorage, { + const updatedSession = this.updateSessionValue(sessionStorage, { provider: { type: provider.type, name: providerName }, isSystemRequest: request.isSystemRequest, authenticationResult, @@ -376,6 +385,20 @@ export class Authenticator { }); if (!authenticationResult.notHandled()) { + if ( + authenticationResult.succeeded() && + this.shouldRedirectToAccessAgreement(request, updatedSession) + ) { + this.logger.debug('Redirecting user to the access agreement screen.'); + return AuthenticationResult.redirectTo( + `${ + this.options.basePath.serverBasePath + }${ACCESS_AGREEMENT_ROUTE}?next=${encodeURIComponent( + `${this.options.basePath.get(request)}${request.url.path}` + )}` + ); + } + return authenticationResult; } } @@ -441,7 +464,7 @@ export class Authenticator { now: Date.now(), idleTimeoutExpiration: sessionValue.idleTimeoutExpiration, lifespanExpiration: sessionValue.lifespanExpiration, - provider: sessionValue.provider.name, + provider: sessionValue.provider, }; } return null; @@ -455,6 +478,32 @@ export class Authenticator { return [...this.providers.values()].some(provider => provider.type === providerType); } + /** + * Acknowledges access agreement on behalf of the currently authenticated user. + * @param request Request instance. + */ + async acknowledgeAccessAgreement(request: KibanaRequest) { + assertRequest(request); + + const sessionStorage = this.options.sessionStorageFactory.asScoped(request); + const existingSession = await this.getSessionValue(sessionStorage); + const currentUser = this.options.getCurrentUser(request); + if (!existingSession || !currentUser) { + throw new Error('Cannot acknowledge access agreement for unauthenticated user.'); + } + + if (!this.options.license.getFeatures().allowAccessAgreement) { + throw new Error('Current license does not allow access agreement acknowledgement.'); + } + + sessionStorage.set({ ...existingSession, accessAgreementAcknowledged: true }); + + this.options.auditLogger.accessAgreementAcknowledged( + currentUser.username, + existingSession.provider + ); + } + /** * Initializes HTTP Authentication provider and appends it to the end of the list of enabled * authentication providers. @@ -538,14 +587,14 @@ export class Authenticator { existingSession, isSystemRequest, }: { - provider: { type: string; name: string }; + provider: AuthenticationProvider; authenticationResult: AuthenticationResult; existingSession: ProviderSession | null; isSystemRequest: boolean; } ) { if (!existingSession && !authenticationResult.shouldUpdateState()) { - return; + return null; } // If authentication succeeds or requires redirect we should automatically extend existing user session, @@ -563,9 +612,12 @@ export class Authenticator { (authenticationResult.failed() && getErrorStatusCode(authenticationResult.error) === 401) ) { sessionStorage.clear(); - } else if (sessionCanBeUpdated) { + return null; + } + + if (sessionCanBeUpdated) { const { idleTimeoutExpiration, lifespanExpiration } = this.calculateExpiry(existingSession); - sessionStorage.set({ + const updatedSession = { state: authenticationResult.shouldUpdateState() ? authenticationResult.state : existingSession!.state, @@ -573,8 +625,13 @@ export class Authenticator { idleTimeoutExpiration, lifespanExpiration, path: this.serverBasePath, - }); + accessAgreementAcknowledged: existingSession?.accessAgreementAcknowledged, + }; + sessionStorage.set(updatedSession); + return updatedSession; } + + return existingSession; } private getProviderName(query: any): string | null { @@ -600,4 +657,48 @@ export class Authenticator { return { idleTimeoutExpiration, lifespanExpiration }; } + + /** + * Checks whether request should be redirected to the Login Selector UI. + * @param request Request instance. + * @param session Current session value if any. + */ + private shouldRedirectToLoginSelector(request: KibanaRequest, session: ProviderSession | null) { + // Request should be redirected to Login Selector UI only if all following conditions are met: + // 1. Request can be redirected (not API call) + // 2. Request is not authenticated yet + // 3. Login Selector UI is enabled + // 4. Request isn't attributed with HTTP Authorization header + return ( + canRedirectRequest(request) && + !session && + this.options.config.authc.selector.enabled && + HTTPAuthorizationHeader.parseFromRequest(request) == null + ); + } + + /** + * Checks whether request should be redirected to the Access Agreement UI. + * @param request Request instance. + * @param session Current session value if any. + */ + private shouldRedirectToAccessAgreement(request: KibanaRequest, session: ProviderSession | null) { + // Request should be redirected to Access Agreement UI only if all following conditions are met: + // 1. Request can be redirected (not API call) + // 2. Request is authenticated, but user hasn't acknowledged access agreement in the current + // session yet (based on the flag we store in the session) + // 3. Request is authenticated by the provider that has `accessAgreement` configured + // 4. Current license allows access agreement + // 5. And it's not a request to the Access Agreement UI itself + return ( + canRedirectRequest(request) && + session != null && + !session.accessAgreementAcknowledged && + (this.options.config.authc.providers as Record)[session.provider.type]?.[ + session.provider.name + ]?.accessAgreement && + this.options.license.getFeatures().allowAccessAgreement && + request.url.pathname !== ACCESS_AGREEMENT_ROUTE + ); + } } diff --git a/x-pack/plugins/security/server/authentication/index.mock.ts b/x-pack/plugins/security/server/authentication/index.mock.ts index 9397a7a42b3262..7cd3ac18634f78 100644 --- a/x-pack/plugins/security/server/authentication/index.mock.ts +++ b/x-pack/plugins/security/server/authentication/index.mock.ts @@ -19,5 +19,6 @@ export const authenticationMock = { invalidateAPIKeyAsInternalUser: jest.fn(), isAuthenticated: jest.fn(), getSessionInfo: jest.fn(), + acknowledgeAccessAgreement: jest.fn(), }), }; diff --git a/x-pack/plugins/security/server/authentication/index.test.ts b/x-pack/plugins/security/server/authentication/index.test.ts index 6609f8707976b7..1c1e0ed781f18e 100644 --- a/x-pack/plugins/security/server/authentication/index.test.ts +++ b/x-pack/plugins/security/server/authentication/index.test.ts @@ -19,6 +19,7 @@ import { elasticsearchServiceMock, } from '../../../../../src/core/server/mocks'; import { mockAuthenticatedUser } from '../../common/model/authenticated_user.mock'; +import { securityAuditLoggerMock } from '../audit/index.mock'; import { AuthenticationHandler, @@ -40,9 +41,11 @@ import { InvalidateAPIKeyParams, } from './api_keys'; import { SecurityLicense } from '../../common/licensing'; +import { SecurityAuditLogger } from '../audit'; describe('setupAuthentication()', () => { let mockSetupAuthenticationParams: { + auditLogger: jest.Mocked; config: ConfigType; loggers: LoggerFactory; http: jest.Mocked; @@ -52,6 +55,7 @@ describe('setupAuthentication()', () => { let mockScopedClusterClient: jest.Mocked>; beforeEach(() => { mockSetupAuthenticationParams = { + auditLogger: securityAuditLoggerMock.create(), http: coreMock.createSetup().http, config: createConfig( ConfigSchema.validate({ diff --git a/x-pack/plugins/security/server/authentication/index.ts b/x-pack/plugins/security/server/authentication/index.ts index d76a5a533d4983..779b852195b028 100644 --- a/x-pack/plugins/security/server/authentication/index.ts +++ b/x-pack/plugins/security/server/authentication/index.ts @@ -10,12 +10,13 @@ import { KibanaRequest, LoggerFactory, } from '../../../../../src/core/server'; +import { SecurityLicense } from '../../common/licensing'; import { AuthenticatedUser } from '../../common/model'; +import { SecurityAuditLogger } from '../audit'; import { ConfigType } from '../config'; import { getErrorStatusCode } from '../errors'; import { Authenticator, ProviderSession } from './authenticator'; import { APIKeys, CreateAPIKeyParams, InvalidateAPIKeyParams } from './api_keys'; -import { SecurityLicense } from '../../common/licensing'; export { canRedirectRequest } from './can_redirect_request'; export { Authenticator, ProviderLoginAttempt } from './authenticator'; @@ -35,6 +36,7 @@ export { } from './http_authentication'; interface SetupAuthenticationParams { + auditLogger: SecurityAuditLogger; http: CoreSetup['http']; clusterClient: IClusterClient; config: ConfigType; @@ -45,6 +47,7 @@ interface SetupAuthenticationParams { export type Authentication = UnwrapPromise>; export async function setupAuthentication({ + auditLogger, http, clusterClient, config, @@ -82,9 +85,12 @@ export async function setupAuthentication({ }; const authenticator = new Authenticator({ + auditLogger, + getCurrentUser, clusterClient, basePath: http.basePath, config: { session: config.session, authc: config.authc }, + license, loggers, sessionStorageFactory: await http.createCookieSessionStorageFactory({ encryptionKey: config.encryptionKey, @@ -171,6 +177,7 @@ export async function setupAuthentication({ logout: authenticator.logout.bind(authenticator), getSessionInfo: authenticator.getSessionInfo.bind(authenticator), isProviderTypeEnabled: authenticator.isProviderTypeEnabled.bind(authenticator), + acknowledgeAccessAgreement: authenticator.acknowledgeAccessAgreement.bind(authenticator), getCurrentUser, areAPIKeysEnabled: () => apiKeys.areAPIKeysEnabled(), createAPIKey: (request: KibanaRequest, params: CreateAPIKeyParams) => diff --git a/x-pack/plugins/security/server/config.test.ts b/x-pack/plugins/security/server/config.test.ts index 9899cd688d6ddb..2c248646499774 100644 --- a/x-pack/plugins/security/server/config.test.ts +++ b/x-pack/plugins/security/server/config.test.ts @@ -27,6 +27,7 @@ describe('config schema', () => { "providers": Object { "basic": Object { "basic": Object { + "accessAgreement": undefined, "description": undefined, "enabled": true, "hint": undefined, @@ -71,6 +72,7 @@ describe('config schema', () => { "providers": Object { "basic": Object { "basic": Object { + "accessAgreement": undefined, "description": undefined, "enabled": true, "hint": undefined, @@ -115,6 +117,7 @@ describe('config schema', () => { "providers": Object { "basic": Object { "basic": Object { + "accessAgreement": undefined, "description": undefined, "enabled": true, "hint": undefined, @@ -897,20 +900,12 @@ describe('createConfig()', () => { "sortedProviders": Array [ Object { "name": "saml", - "options": Object { - "description": undefined, - "order": 0, - "showInSelector": true, - }, + "order": 0, "type": "saml", }, Object { "name": "basic", - "options": Object { - "description": undefined, - "order": 1, - "showInSelector": true, - }, + "order": 1, "type": "basic", }, ], @@ -1001,47 +996,27 @@ describe('createConfig()', () => { Array [ Object { "name": "oidc1", - "options": Object { - "description": undefined, - "order": 0, - "showInSelector": true, - }, + "order": 0, "type": "oidc", }, Object { "name": "saml2", - "options": Object { - "description": undefined, - "order": 1, - "showInSelector": true, - }, + "order": 1, "type": "saml", }, Object { "name": "saml1", - "options": Object { - "description": undefined, - "order": 2, - "showInSelector": true, - }, + "order": 2, "type": "saml", }, Object { "name": "basic1", - "options": Object { - "description": "Log in with Elasticsearch", - "order": 3, - "showInSelector": true, - }, + "order": 3, "type": "basic", }, Object { "name": "oidc2", - "options": Object { - "description": undefined, - "order": 4, - "showInSelector": true, - }, + "order": 4, "type": "oidc", }, ] diff --git a/x-pack/plugins/security/server/config.ts b/x-pack/plugins/security/server/config.ts index 7fe38b05f72d60..8fe79a788ac51c 100644 --- a/x-pack/plugins/security/server/config.ts +++ b/x-pack/plugins/security/server/config.ts @@ -33,6 +33,7 @@ function getCommonProviderSchemaProperties(overrides: Partial = []; for (const [type, providerGroup] of Object.entries(providers)) { - for (const [name, { enabled, showInSelector, order, description }] of Object.entries( - providerGroup ?? {} - )) { + for (const [name, { enabled, order }] of Object.entries(providerGroup ?? {})) { if (!enabled) { delete providerGroup![name]; } else { - sortedProviders.push({ - type: type as any, - name, - options: { order, showInSelector, description }, - }); + sortedProviders.push({ type: type as any, name, order }); } } } - sortedProviders.sort(({ options: { order: orderA } }, { options: { order: orderB } }) => + sortedProviders.sort(({ order: orderA }, { order: orderB }) => orderA < orderB ? -1 : orderA > orderB ? 1 : 0 ); @@ -268,7 +264,8 @@ export function createConfig( typeof config.authc.selector.enabled === 'boolean' ? config.authc.selector.enabled : !isUsingLegacyProvidersFormat && - sortedProviders.filter(provider => provider.options.showInSelector).length > 1; + sortedProviders.filter(({ type, name }) => providers[type]?.[name].showInSelector).length > + 1; return { ...config, diff --git a/x-pack/plugins/security/server/plugin.test.ts b/x-pack/plugins/security/server/plugin.test.ts index 3ce0198273af97..22a30f03c646a1 100644 --- a/x-pack/plugins/security/server/plugin.test.ts +++ b/x-pack/plugins/security/server/plugin.test.ts @@ -72,14 +72,10 @@ describe('Security Plugin', () => { "areAPIKeysEnabled": [Function], "createAPIKey": [Function], "getCurrentUser": [Function], - "getSessionInfo": [Function], "grantAPIKeyAsInternalUser": [Function], "invalidateAPIKey": [Function], "invalidateAPIKeyAsInternalUser": [Function], "isAuthenticated": [Function], - "isProviderTypeEnabled": [Function], - "login": [Function], - "logout": [Function], }, "authz": Object { "actions": Actions { diff --git a/x-pack/plugins/security/server/plugin.ts b/x-pack/plugins/security/server/plugin.ts index 9dd4aaafa3494f..e30b0caf76ddc0 100644 --- a/x-pack/plugins/security/server/plugin.ts +++ b/x-pack/plugins/security/server/plugin.ts @@ -48,7 +48,16 @@ export interface LegacyAPI { * Describes public Security plugin contract returned at the `setup` stage. */ export interface SecurityPluginSetup { - authc: Authentication; + authc: Pick< + Authentication, + | 'isAuthenticated' + | 'getCurrentUser' + | 'areAPIKeysEnabled' + | 'createAPIKey' + | 'invalidateAPIKey' + | 'grantAPIKeyAsInternalUser' + | 'invalidateAPIKeyAsInternalUser' + >; authz: Pick; /** @@ -126,7 +135,9 @@ export class Plugin { license$: licensing.license$, }); + const auditLogger = new SecurityAuditLogger(() => this.getLegacyAPI().auditLogger); const authc = await setupAuthentication({ + auditLogger, http: core.http, clusterClient: this.clusterClient, config, @@ -146,7 +157,7 @@ export class Plugin { }); setupSavedObjects({ - auditLogger: new SecurityAuditLogger(() => this.getLegacyAPI().auditLogger), + auditLogger, authz, savedObjects: core.savedObjects, getSpacesService: this.getSpacesService, @@ -167,7 +178,15 @@ export class Plugin { }); return deepFreeze({ - authc, + authc: { + isAuthenticated: authc.isAuthenticated, + getCurrentUser: authc.getCurrentUser, + areAPIKeysEnabled: authc.areAPIKeysEnabled, + createAPIKey: authc.createAPIKey, + invalidateAPIKey: authc.invalidateAPIKey, + grantAPIKeyAsInternalUser: authc.grantAPIKeyAsInternalUser, + invalidateAPIKeyAsInternalUser: authc.invalidateAPIKeyAsInternalUser, + }, authz: { actions: authz.actions, diff --git a/x-pack/plugins/security/server/routes/authentication/common.test.ts b/x-pack/plugins/security/server/routes/authentication/common.test.ts index 156c03e90210b7..5a0401e6320b46 100644 --- a/x-pack/plugins/security/server/routes/authentication/common.test.ts +++ b/x-pack/plugins/security/server/routes/authentication/common.test.ts @@ -12,6 +12,7 @@ import { RequestHandlerContext, RouteConfig, } from '../../../../../../src/core/server'; +import { SecurityLicense, SecurityLicenseFeatures } from '../../../common/licensing'; import { Authentication, AuthenticationResult, @@ -28,11 +29,13 @@ import { routeDefinitionParamsMock } from '../index.mock'; describe('Common authentication routes', () => { let router: jest.Mocked; let authc: jest.Mocked; + let license: jest.Mocked; let mockContext: RequestHandlerContext; beforeEach(() => { const routeParamsMock = routeDefinitionParamsMock.create(); router = routeParamsMock.router; authc = routeParamsMock.authc; + license = routeParamsMock.license; mockContext = ({ licensing: { @@ -433,4 +436,61 @@ describe('Common authentication routes', () => { }); }); }); + + describe('acknowledge access agreement', () => { + let routeHandler: RequestHandler; + let routeConfig: RouteConfig; + beforeEach(() => { + const [acsRouteConfig, acsRouteHandler] = router.post.mock.calls.find( + ([{ path }]) => path === '/internal/security/access_agreement/acknowledge' + )!; + + license.getFeatures.mockReturnValue({ + allowAccessAgreement: true, + } as SecurityLicenseFeatures); + + routeConfig = acsRouteConfig; + routeHandler = acsRouteHandler; + }); + + it('correctly defines route.', () => { + expect(routeConfig.options).toBeUndefined(); + expect(routeConfig.validate).toBe(false); + }); + + it(`returns 403 if current license doesn't allow access agreement acknowledgement.`, async () => { + license.getFeatures.mockReturnValue({ + allowAccessAgreement: false, + } as SecurityLicenseFeatures); + + const request = httpServerMock.createKibanaRequest(); + await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({ + status: 403, + payload: { message: `Current license doesn't support access agreement.` }, + options: { body: { message: `Current license doesn't support access agreement.` } }, + }); + }); + + it('returns 500 if acknowledge throws unhandled exception.', async () => { + const unhandledException = new Error('Something went wrong.'); + authc.acknowledgeAccessAgreement.mockRejectedValue(unhandledException); + + const request = httpServerMock.createKibanaRequest(); + await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({ + status: 500, + payload: 'Internal Error', + options: {}, + }); + }); + + it('returns 204 if successfully acknowledged.', async () => { + authc.acknowledgeAccessAgreement.mockResolvedValue(undefined); + + const request = httpServerMock.createKibanaRequest(); + await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({ + status: 204, + options: {}, + }); + }); + }); }); diff --git a/x-pack/plugins/security/server/routes/authentication/common.ts b/x-pack/plugins/security/server/routes/authentication/common.ts index abab67c9cd1d28..91783140539a5b 100644 --- a/x-pack/plugins/security/server/routes/authentication/common.ts +++ b/x-pack/plugins/security/server/routes/authentication/common.ts @@ -18,7 +18,13 @@ import { RouteDefinitionParams } from '..'; /** * Defines routes that are common to various authentication mechanisms. */ -export function defineCommonRoutes({ router, authc, basePath, logger }: RouteDefinitionParams) { +export function defineCommonRoutes({ + router, + authc, + basePath, + license, + logger, +}: RouteDefinitionParams) { // Generate two identical routes with new and deprecated URL and issue a warning if route with deprecated URL is ever used. for (const path of ['/api/security/logout', '/api/security/v1/logout']) { router.get( @@ -135,4 +141,26 @@ export function defineCommonRoutes({ router, authc, basePath, logger }: RouteDef } }) ); + + router.post( + { path: '/internal/security/access_agreement/acknowledge', validate: false }, + createLicensedRouteHandler(async (context, request, response) => { + // If license doesn't allow access agreement we shouldn't handle request. + if (!license.getFeatures().allowAccessAgreement) { + logger.warn(`Attempted to acknowledge access agreement when license doesn't allow it.`); + return response.forbidden({ + body: { message: `Current license doesn't support access agreement.` }, + }); + } + + try { + await authc.acknowledgeAccessAgreement(request); + } catch (err) { + logger.error(err); + return response.internalError(); + } + + return response.noContent(); + }) + ); } diff --git a/x-pack/plugins/security/server/routes/licensed_route_handler.ts b/x-pack/plugins/security/server/routes/licensed_route_handler.ts index b113b2ca59e3ef..d8c212aa2d2174 100644 --- a/x-pack/plugins/security/server/routes/licensed_route_handler.ts +++ b/x-pack/plugins/security/server/routes/licensed_route_handler.ts @@ -4,10 +4,22 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RequestHandler } from 'kibana/server'; +import { KibanaResponseFactory, RequestHandler, RouteMethod } from 'kibana/server'; -export const createLicensedRouteHandler = (handler: RequestHandler) => { - const licensedRouteHandler: RequestHandler = (context, request, responseToolkit) => { +export const createLicensedRouteHandler = < + P, + Q, + B, + M extends RouteMethod, + R extends KibanaResponseFactory +>( + handler: RequestHandler +) => { + const licensedRouteHandler: RequestHandler = ( + context, + request, + responseToolkit + ) => { const { license } = context.licensing; const licenseCheck = license.check('security', 'basic'); if (licenseCheck.state === 'unavailable' || licenseCheck.state === 'invalid') { diff --git a/x-pack/plugins/security/server/routes/users/change_password.test.ts b/x-pack/plugins/security/server/routes/users/change_password.test.ts index fd05821f9d5206..c163ff4e256cd2 100644 --- a/x-pack/plugins/security/server/routes/users/change_password.test.ts +++ b/x-pack/plugins/security/server/routes/users/change_password.test.ts @@ -53,7 +53,7 @@ describe('Change password', () => { now: Date.now(), idleTimeoutExpiration: null, lifespanExpiration: null, - provider: 'basic', + provider: { type: 'basic', name: 'basic' }, }); mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); diff --git a/x-pack/plugins/security/server/routes/views/access_agreement.test.ts b/x-pack/plugins/security/server/routes/views/access_agreement.test.ts new file mode 100644 index 00000000000000..3d616575b84131 --- /dev/null +++ b/x-pack/plugins/security/server/routes/views/access_agreement.test.ts @@ -0,0 +1,177 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + RequestHandler, + RouteConfig, + kibanaResponseFactory, + IRouter, + HttpResources, + HttpResourcesRequestHandler, + RequestHandlerContext, +} from '../../../../../../src/core/server'; +import { SecurityLicense, SecurityLicenseFeatures } from '../../../common/licensing'; +import { AuthenticationProvider } from '../../../common/types'; +import { ConfigType } from '../../config'; +import { defineAccessAgreementRoutes } from './access_agreement'; + +import { httpResourcesMock, httpServerMock } from '../../../../../../src/core/server/mocks'; +import { routeDefinitionParamsMock } from '../index.mock'; +import { Authentication } from '../../authentication'; + +describe('Access agreement view routes', () => { + let httpResources: jest.Mocked; + let router: jest.Mocked; + let config: ConfigType; + let authc: jest.Mocked; + let license: jest.Mocked; + let mockContext: RequestHandlerContext; + beforeEach(() => { + const routeParamsMock = routeDefinitionParamsMock.create(); + router = routeParamsMock.router; + httpResources = routeParamsMock.httpResources; + authc = routeParamsMock.authc; + config = routeParamsMock.config; + license = routeParamsMock.license; + + license.getFeatures.mockReturnValue({ + allowAccessAgreement: true, + } as SecurityLicenseFeatures); + + mockContext = ({ + licensing: { + license: { check: jest.fn().mockReturnValue({ check: 'valid' }) }, + }, + } as unknown) as RequestHandlerContext; + + defineAccessAgreementRoutes(routeParamsMock); + }); + + describe('View route', () => { + let routeHandler: HttpResourcesRequestHandler; + let routeConfig: RouteConfig; + beforeEach(() => { + const [viewRouteConfig, viewRouteHandler] = httpResources.register.mock.calls.find( + ([{ path }]) => path === '/security/access_agreement' + )!; + + routeConfig = viewRouteConfig; + routeHandler = viewRouteHandler; + }); + + it('correctly defines route.', () => { + expect(routeConfig.options).toBeUndefined(); + expect(routeConfig.validate).toBe(false); + }); + + it('does not render view if current license does not allow access agreement.', async () => { + const request = httpServerMock.createKibanaRequest(); + const responseFactory = httpResourcesMock.createResponseFactory(); + + license.getFeatures.mockReturnValue({ + allowAccessAgreement: false, + } as SecurityLicenseFeatures); + + await routeHandler(mockContext, request, responseFactory); + + expect(responseFactory.renderCoreApp).not.toHaveBeenCalledWith(); + expect(responseFactory.forbidden).toHaveBeenCalledTimes(1); + }); + + it('renders view.', async () => { + const request = httpServerMock.createKibanaRequest(); + const responseFactory = httpResourcesMock.createResponseFactory(); + + await routeHandler(mockContext, request, responseFactory); + + expect(responseFactory.renderCoreApp).toHaveBeenCalledWith(); + }); + }); + + describe('Access agreement state route', () => { + let routeHandler: RequestHandler; + let routeConfig: RouteConfig; + beforeEach(() => { + const [loginStateRouteConfig, loginStateRouteHandler] = router.get.mock.calls.find( + ([{ path }]) => path === '/internal/security/access_agreement/state' + )!; + + routeConfig = loginStateRouteConfig; + routeHandler = loginStateRouteHandler; + }); + + it('correctly defines route.', () => { + expect(routeConfig.options).toBeUndefined(); + expect(routeConfig.validate).toBe(false); + }); + + it('returns `403` if current license does not allow access agreement.', async () => { + const request = httpServerMock.createKibanaRequest(); + + license.getFeatures.mockReturnValue({ + allowAccessAgreement: false, + } as SecurityLicenseFeatures); + + await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({ + status: 403, + payload: { message: `Current license doesn't support access agreement.` }, + options: { body: { message: `Current license doesn't support access agreement.` } }, + }); + }); + + it('returns empty `accessAgreement` if session info is not available.', async () => { + const request = httpServerMock.createKibanaRequest(); + + authc.getSessionInfo.mockResolvedValue(null); + + await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({ + options: { body: { accessAgreement: '' } }, + payload: { accessAgreement: '' }, + status: 200, + }); + }); + + it('returns non-empty `accessAgreement` only if it is configured.', async () => { + const request = httpServerMock.createKibanaRequest(); + + config.authc = routeDefinitionParamsMock.create({ + authc: { + providers: { + basic: { basic1: { order: 0 } }, + saml: { + saml1: { + order: 1, + realm: 'realm1', + accessAgreement: { message: 'Some access agreement' }, + }, + }, + }, + }, + }).config.authc; + + const cases: Array<[AuthenticationProvider, string]> = [ + [{ type: 'basic', name: 'basic1' }, ''], + [{ type: 'saml', name: 'saml1' }, 'Some access agreement'], + [{ type: 'unknown-type', name: 'unknown-name' }, ''], + ]; + + for (const [sessionProvider, expectedAccessAgreement] of cases) { + authc.getSessionInfo.mockResolvedValue({ + now: Date.now(), + idleTimeoutExpiration: null, + lifespanExpiration: null, + provider: sessionProvider, + }); + + await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({ + options: { body: { accessAgreement: expectedAccessAgreement } }, + payload: { accessAgreement: expectedAccessAgreement }, + status: 200, + }); + } + }); + }); +}); diff --git a/x-pack/plugins/security/server/routes/views/access_agreement.ts b/x-pack/plugins/security/server/routes/views/access_agreement.ts new file mode 100644 index 00000000000000..49e1ff42a28a2a --- /dev/null +++ b/x-pack/plugins/security/server/routes/views/access_agreement.ts @@ -0,0 +1,64 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ConfigType } from '../../config'; +import { createLicensedRouteHandler } from '../licensed_route_handler'; +import { RouteDefinitionParams } from '..'; + +/** + * Defines routes required for the Access Agreement view. + */ +export function defineAccessAgreementRoutes({ + authc, + httpResources, + license, + config, + router, + logger, +}: RouteDefinitionParams) { + // If license doesn't allow access agreement we shouldn't handle request. + const canHandleRequest = () => license.getFeatures().allowAccessAgreement; + + httpResources.register( + { path: '/security/access_agreement', validate: false }, + createLicensedRouteHandler(async (context, request, response) => + canHandleRequest() + ? response.renderCoreApp() + : response.forbidden({ + body: { message: `Current license doesn't support access agreement.` }, + }) + ) + ); + + router.get( + { path: '/internal/security/access_agreement/state', validate: false }, + createLicensedRouteHandler(async (context, request, response) => { + if (!canHandleRequest()) { + return response.forbidden({ + body: { message: `Current license doesn't support access agreement.` }, + }); + } + + // It's not guaranteed that we'll have session for the authenticated user (e.g. when user is + // authenticated with the help of HTTP authentication), that means we should safely check if + // we have it and can get a corresponding configuration. + try { + const session = await authc.getSessionInfo(request); + const accessAgreement = + (session && + config.authc.providers[ + session.provider.type as keyof ConfigType['authc']['providers'] + ]?.[session.provider.name]?.accessAgreement?.message) || + ''; + + return response.ok({ body: { accessAgreement } }); + } catch (err) { + logger.error(err); + return response.internalError(); + } + }) + ); +} diff --git a/x-pack/plugins/security/server/routes/views/index.test.ts b/x-pack/plugins/security/server/routes/views/index.test.ts index a8e7e905b119af..7cddef9bf2b982 100644 --- a/x-pack/plugins/security/server/routes/views/index.test.ts +++ b/x-pack/plugins/security/server/routes/views/index.test.ts @@ -20,15 +20,18 @@ describe('View routes', () => { expect(routeParamsMock.httpResources.register.mock.calls.map(([{ path }]) => path)) .toMatchInlineSnapshot(` Array [ + "/security/access_agreement", "/security/account", "/security/logged_out", "/logout", "/security/overwritten_session", ] `); - expect(routeParamsMock.router.get.mock.calls.map(([{ path }]) => path)).toMatchInlineSnapshot( - `Array []` - ); + expect(routeParamsMock.router.get.mock.calls.map(([{ path }]) => path)).toMatchInlineSnapshot(` + Array [ + "/internal/security/access_agreement/state", + ] + `); }); it('registers Login routes if `basic` provider is enabled', () => { @@ -43,6 +46,7 @@ describe('View routes', () => { .toMatchInlineSnapshot(` Array [ "/login", + "/security/access_agreement", "/security/account", "/security/logged_out", "/logout", @@ -52,6 +56,7 @@ describe('View routes', () => { expect(routeParamsMock.router.get.mock.calls.map(([{ path }]) => path)).toMatchInlineSnapshot(` Array [ "/internal/security/login_state", + "/internal/security/access_agreement/state", ] `); }); @@ -68,6 +73,7 @@ describe('View routes', () => { .toMatchInlineSnapshot(` Array [ "/login", + "/security/access_agreement", "/security/account", "/security/logged_out", "/logout", @@ -77,6 +83,7 @@ describe('View routes', () => { expect(routeParamsMock.router.get.mock.calls.map(([{ path }]) => path)).toMatchInlineSnapshot(` Array [ "/internal/security/login_state", + "/internal/security/access_agreement/state", ] `); }); @@ -93,6 +100,7 @@ describe('View routes', () => { .toMatchInlineSnapshot(` Array [ "/login", + "/security/access_agreement", "/security/account", "/security/logged_out", "/logout", @@ -102,6 +110,7 @@ describe('View routes', () => { expect(routeParamsMock.router.get.mock.calls.map(([{ path }]) => path)).toMatchInlineSnapshot(` Array [ "/internal/security/login_state", + "/internal/security/access_agreement/state", ] `); }); diff --git a/x-pack/plugins/security/server/routes/views/index.ts b/x-pack/plugins/security/server/routes/views/index.ts index 255989dfeb90cd..b9de58d47fe407 100644 --- a/x-pack/plugins/security/server/routes/views/index.ts +++ b/x-pack/plugins/security/server/routes/views/index.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { defineAccessAgreementRoutes } from './access_agreement'; import { defineAccountManagementRoutes } from './account_management'; import { defineLoggedOutRoutes } from './logged_out'; import { defineLoginRoutes } from './login'; @@ -20,6 +21,7 @@ export function defineViewRoutes(params: RouteDefinitionParams) { defineLoginRoutes(params); } + defineAccessAgreementRoutes(params); defineAccountManagementRoutes(params); defineLoggedOutRoutes(params); defineLogoutRoutes(params); diff --git a/x-pack/plugins/security/server/routes/views/logged_out.test.ts b/x-pack/plugins/security/server/routes/views/logged_out.test.ts index 3ff05d242d9dde..7cb73c49f9cbc8 100644 --- a/x-pack/plugins/security/server/routes/views/logged_out.test.ts +++ b/x-pack/plugins/security/server/routes/views/logged_out.test.ts @@ -39,7 +39,7 @@ describe('LoggedOut view routes', () => { it('redirects user to the root page if they have a session already.', async () => { authc.getSessionInfo.mockResolvedValue({ - provider: 'basic', + provider: { type: 'basic', name: 'basic' }, now: 0, idleTimeoutExpiration: null, lifespanExpiration: null, diff --git a/x-pack/plugins/security/server/routes/views/login.test.ts b/x-pack/plugins/security/server/routes/views/login.test.ts index 8bc2bb32325fc0..014ad390a3d53b 100644 --- a/x-pack/plugins/security/server/routes/views/login.test.ts +++ b/x-pack/plugins/security/server/routes/views/login.test.ts @@ -163,6 +163,7 @@ describe('Login view routes', () => { it('returns only required license features.', async () => { license.getFeatures.mockReturnValue({ + allowAccessAgreement: true, allowLogin: true, allowRbac: false, allowRoleDocumentLevelSecurity: true, diff --git a/x-pack/test/api_integration/apis/security/session.ts b/x-pack/test/api_integration/apis/security/session.ts index ef7e48388ff660..fcdf268ff27b0a 100644 --- a/x-pack/test/api_integration/apis/security/session.ts +++ b/x-pack/test/api_integration/apis/security/session.ts @@ -56,7 +56,7 @@ export default function({ getService }: FtrProviderContext) { expect(body.now).to.be.a('number'); expect(body.idleTimeoutExpiration).to.be.a('number'); expect(body.lifespanExpiration).to.be(null); - expect(body.provider).to.be('basic'); + expect(body.provider).to.eql({ type: 'basic', name: 'basic' }); }); it('should not extend the session', async () => { From 296855f8beae6cc9ef9e0624782fc2c3fb1073bf Mon Sep 17 00:00:00 2001 From: Robert Austin Date: Tue, 28 Apr 2020 12:22:13 -0400 Subject: [PATCH 06/12] [Endpoint] housekeeping (#64237) Reorganizing, renaming, and generally cleaning up common code in Endpoint. * Cleaning up `common/types` * Renaming things * Adding comments * Removing `export` when it's not needed --- .../endpoint/common/alert_constants.ts | 34 +++++ .../plugins/endpoint/common/generate_data.ts | 14 +- .../endpoint/common/schema/alert_index.ts | 4 +- x-pack/plugins/endpoint/common/types.ts | 138 +++++++++--------- .../endpoint/store/alerts/middleware.ts | 4 +- .../public/applications/endpoint/types.ts | 3 +- .../policy/policy_forms/events/windows.tsx | 6 +- .../policy_forms/protections/malware.tsx | 6 +- .../plugins/endpoint/server/index_pattern.ts | 4 +- .../server/routes/alerts/details/handlers.ts | 5 +- .../routes/alerts/details/lib/pagination.ts | 12 +- .../endpoint/server/routes/alerts/index.ts | 4 +- .../server/routes/alerts/lib/index.ts | 9 +- .../server/routes/alerts/list/lib/index.ts | 10 +- .../endpoint/server/routes/alerts/types.ts | 8 +- .../endpoint/server/routes/index_pattern.ts | 5 +- .../server/routes/resolver/queries/base.ts | 4 +- .../routes/resolver/queries/children.test.ts | 6 +- .../queries/legacy_event_index_pattern.ts | 10 ++ .../routes/resolver/queries/lifecycle.test.ts | 9 +- .../resolver/queries/related_events.test.ts | 6 +- 21 files changed, 172 insertions(+), 129 deletions(-) create mode 100644 x-pack/plugins/endpoint/common/alert_constants.ts create mode 100644 x-pack/plugins/endpoint/server/routes/resolver/queries/legacy_event_index_pattern.ts diff --git a/x-pack/plugins/endpoint/common/alert_constants.ts b/x-pack/plugins/endpoint/common/alert_constants.ts new file mode 100644 index 00000000000000..85e1643d684f2c --- /dev/null +++ b/x-pack/plugins/endpoint/common/alert_constants.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export class AlertConstants { + /** + * The prefix for all Alert APIs + */ + static BASE_API_URL = '/api/endpoint'; + /** + * The path for the Alert's Index Pattern API. + */ + static INDEX_PATTERN_ROUTE = `${AlertConstants.BASE_API_URL}/index_pattern`; + /** + * Alert's Index pattern + */ + static ALERT_INDEX_NAME = 'events-endpoint-1'; + /** + * A paramter passed to Alert's Index Pattern. + */ + static EVENT_DATASET = 'events'; + /** + * Alert's Search API default page size + */ + static DEFAULT_TOTAL_HITS = 10000; + /** + * Alerts + **/ + static ALERT_LIST_DEFAULT_PAGE_SIZE = 10; + static ALERT_LIST_DEFAULT_SORT = '@timestamp'; + static MAX_LONG_INT = '9223372036854775807'; // 2^63-1 +} diff --git a/x-pack/plugins/endpoint/common/generate_data.ts b/x-pack/plugins/endpoint/common/generate_data.ts index 4f5a6eaeb0a5eb..61fbb779986dc9 100644 --- a/x-pack/plugins/endpoint/common/generate_data.ts +++ b/x-pack/plugins/endpoint/common/generate_data.ts @@ -9,9 +9,9 @@ import seedrandom from 'seedrandom'; import { AlertEvent, EndpointEvent, - HostFields, + Host, HostMetadata, - OSFields, + HostOS, PolicyData, HostPolicyResponse, HostPolicyResponseActionStatus, @@ -29,7 +29,7 @@ interface EventOptions { processName?: string; } -const Windows: OSFields[] = [ +const Windows: HostOS[] = [ { name: 'windows 10.0', full: 'Windows 10', @@ -56,11 +56,11 @@ const Windows: OSFields[] = [ }, ]; -const Linux: OSFields[] = []; +const Linux: HostOS[] = []; -const Mac: OSFields[] = []; +const Mac: HostOS[] = []; -const OS: OSFields[] = [...Windows, ...Mac, ...Linux]; +const OS: HostOS[] = [...Windows, ...Mac, ...Linux]; const POLICIES: Array<{ name: string; id: string }> = [ { @@ -102,7 +102,7 @@ interface HostInfo { version: string; id: string; }; - host: HostFields; + host: Host; endpoint: { policy: { id: string; diff --git a/x-pack/plugins/endpoint/common/schema/alert_index.ts b/x-pack/plugins/endpoint/common/schema/alert_index.ts index 7b48780f2d86bb..cffc00661515f6 100644 --- a/x-pack/plugins/endpoint/common/schema/alert_index.ts +++ b/x-pack/plugins/endpoint/common/schema/alert_index.ts @@ -7,7 +7,7 @@ import { schema, Type } from '@kbn/config-schema'; import { i18n } from '@kbn/i18n'; import { decode } from 'rison-node'; -import { EndpointAppConstants } from '../types'; +import { AlertConstants } from '../alert_constants'; /** * Used to validate GET requests against the index of the alerting APIs. @@ -18,7 +18,7 @@ export const alertingIndexGetQuerySchema = schema.object( schema.number({ min: 1, max: 100, - defaultValue: EndpointAppConstants.ALERT_LIST_DEFAULT_PAGE_SIZE, + defaultValue: AlertConstants.ALERT_LIST_DEFAULT_PAGE_SIZE, }) ), page_index: schema.maybe( diff --git a/x-pack/plugins/endpoint/common/types.ts b/x-pack/plugins/endpoint/common/types.ts index 4da4f9bc797ca6..8773c5441860a7 100644 --- a/x-pack/plugins/endpoint/common/types.ts +++ b/x-pack/plugins/endpoint/common/types.ts @@ -25,32 +25,19 @@ export type Immutable = T extends undefined | null | boolean | string | numbe ? ImmutableSet : ImmutableObject; -export type ImmutableArray = ReadonlyArray>; -export type ImmutableMap = ReadonlyMap, Immutable>; -export type ImmutableSet = ReadonlySet>; -export type ImmutableObject = { readonly [K in keyof T]: Immutable }; - -export type Direction = 'asc' | 'desc'; - -export class EndpointAppConstants { - static BASE_API_URL = '/api/endpoint'; - static INDEX_PATTERN_ROUTE = `${EndpointAppConstants.BASE_API_URL}/index_pattern`; - static ALERT_INDEX_NAME = 'events-endpoint-1'; - static EVENT_DATASET = 'events'; - static DEFAULT_TOTAL_HITS = 10000; - /** - * Legacy events are stored in indices with endgame-* prefix - */ - static LEGACY_EVENT_INDEX_NAME = 'endgame-*'; +type ImmutableArray = ReadonlyArray>; +type ImmutableMap = ReadonlyMap, Immutable>; +type ImmutableSet = ReadonlySet>; +type ImmutableObject = { readonly [K in keyof T]: Immutable }; - /** - * Alerts - **/ - static ALERT_LIST_DEFAULT_PAGE_SIZE = 10; - static ALERT_LIST_DEFAULT_SORT = '@timestamp'; - static MAX_LONG_INT = '9223372036854775807'; // 2^63-1 -} +/** + * Values for the Alert APIs 'order' and 'direction' parameters. + */ +export type AlertAPIOrdering = 'asc' | 'desc'; +/** + * Returned by 'api/endpoint/alerts' + */ export interface AlertResultList { /** * The alerts restricted by page size. @@ -88,6 +75,9 @@ export interface AlertResultList { prev: string | null; } +/** + * Returned by the server via /api/endpoint/metadata + */ export interface HostResultList { /* the hosts restricted by the page size */ hosts: HostInfo[]; @@ -99,43 +89,61 @@ export interface HostResultList { request_page_index: number; } -export interface OSFields { +/** + * Operating System metadata for a host. + */ +export interface HostOS { full: string; name: string; version: string; variant: string; } -export interface HostFields { + +/** + * Host metadata. Describes an endpoint host. + */ +export interface Host { id: string; hostname: string; ip: string[]; mac: string[]; - os: OSFields; + os: HostOS; } -export interface HashFields { + +/** + * A record of hashes for something. Provides hashes in multiple formats. A favorite structure of the Elastic Endpoint. + */ +interface Hashes { + /** + * A hash in MD5 format. + */ md5: string; + /** + * A hash in SHA-1 format. + */ sha1: string; + /** + * A hash in SHA-256 format. + */ sha256: string; } -export interface MalwareClassificationFields { + +interface MalwareClassification { identifier: string; score: number; threshold: number; version: string; } -export interface PrivilegesFields { - description: string; - name: string; - enabled: boolean; -} -export interface ThreadFields { + +interface ThreadFields { id: number; service_name: string; start: number; start_address: number; start_address_module: string; } -export interface DllFields { + +interface DllFields { pe: { architecture: string; imphash: string; @@ -145,8 +153,8 @@ export interface DllFields { trusted: boolean; }; compile_time: number; - hash: HashFields; - malware_classification: MalwareClassificationFields; + hash: Hashes; + malware_classification: MalwareClassification; mapped_address: number; mapped_size: number; path: string; @@ -154,7 +162,6 @@ export interface DllFields { /** * Describes an Alert Event. - * Should be in line with ECS schema. */ export type AlertEvent = Immutable<{ '@timestamp': number; @@ -191,14 +198,14 @@ export type AlertEvent = Immutable<{ entity_id: string; }; name: string; - hash: HashFields; + hash: Hashes; pe?: { imphash: string; }; executable: string; sid?: string; start: number; - malware_classification?: MalwareClassificationFields; + malware_classification?: MalwareClassification; token: { domain: string; type: string; @@ -206,7 +213,11 @@ export type AlertEvent = Immutable<{ sid: string; integrity_level: number; integrity_level_name: string; - privileges?: PrivilegesFields[]; + privileges?: Array<{ + description: string; + name: string; + enabled: boolean; + }>; }; thread?: ThreadFields[]; uptime: number; @@ -220,7 +231,7 @@ export type AlertEvent = Immutable<{ mtime: number; created: number; size: number; - hash: HashFields; + hash: Hashes; pe?: { imphash: string; }; @@ -228,10 +239,10 @@ export type AlertEvent = Immutable<{ trusted: boolean; subject_name: string; }; - malware_classification: MalwareClassificationFields; + malware_classification: MalwareClassification; temp_file_path: string; }; - host: HostFields; + host: Host; dll?: DllFields[]; }>; @@ -249,9 +260,6 @@ interface AlertState { }; } -/** - * Union of alert data and metadata. - */ export type AlertData = AlertEvent & AlertMetadata; export type AlertDetails = AlertData & AlertState; @@ -301,7 +309,7 @@ export type HostMetadata = Immutable<{ id: string; version: string; }; - host: HostFields; + host: Host; }>; /** @@ -365,7 +373,7 @@ export interface EndpointEvent { hostname: string; ip: string[]; mac: string[]; - os: OSFields; + os: HostOS; }; process: { entity_id: string; @@ -500,28 +508,22 @@ export interface PolicyConfig { }; } -/** - * Windows-specific policy configuration that is supported via the UI - */ -type WindowsPolicyConfig = Pick; - -/** - * Mac-specific policy configuration that is supported via the UI - */ -type MacPolicyConfig = Pick; - -/** - * Linux-specific policy configuration that is supported via the UI - */ -type LinuxPolicyConfig = Pick; - /** * The set of Policy configuration settings that are show/edited via the UI */ export interface UIPolicyConfig { - windows: WindowsPolicyConfig; - mac: MacPolicyConfig; - linux: LinuxPolicyConfig; + /** + * Windows-specific policy configuration that is supported via the UI + */ + windows: Pick; + /** + * Mac-specific policy configuration that is supported via the UI + */ + mac: Pick; + /** + * Linux-specific policy configuration that is supported via the UI + */ + linux: Pick; } interface PolicyConfigAdvancedOptions { diff --git a/x-pack/plugins/endpoint/public/applications/endpoint/store/alerts/middleware.ts b/x-pack/plugins/endpoint/public/applications/endpoint/store/alerts/middleware.ts index 90d6b8b82198af..6bc728db99819c 100644 --- a/x-pack/plugins/endpoint/public/applications/endpoint/store/alerts/middleware.ts +++ b/x-pack/plugins/endpoint/public/applications/endpoint/store/alerts/middleware.ts @@ -9,7 +9,7 @@ import { AlertResultList, AlertDetails } from '../../../../../common/types'; import { ImmutableMiddlewareFactory, AlertListState } from '../../types'; import { isOnAlertPage, apiQueryParams, hasSelectedAlert, uiQueryParams } from './selectors'; import { cloneHttpFetchQuery } from '../../../../common/clone_http_fetch_query'; -import { EndpointAppConstants } from '../../../../../common/types'; +import { AlertConstants } from '../../../../../common/alert_constants'; export const alertMiddlewareFactory: ImmutableMiddlewareFactory = ( coreStart, @@ -18,7 +18,7 @@ export const alertMiddlewareFactory: ImmutableMiddlewareFactory async function fetchIndexPatterns(): Promise { const { indexPatterns } = depsStart.data; const eventsPattern: { indexPattern: string } = await coreStart.http.get( - `${EndpointAppConstants.INDEX_PATTERN_ROUTE}/${EndpointAppConstants.EVENT_DATASET}` + `${AlertConstants.INDEX_PATTERN_ROUTE}/${AlertConstants.EVENT_DATASET}` ); const fields = await indexPatterns.getFieldsForWildcard({ pattern: eventsPattern.indexPattern, diff --git a/x-pack/plugins/endpoint/public/applications/endpoint/types.ts b/x-pack/plugins/endpoint/public/applications/endpoint/types.ts index 82b812b79670f7..58e706f20ec8e0 100644 --- a/x-pack/plugins/endpoint/public/applications/endpoint/types.ts +++ b/x-pack/plugins/endpoint/public/applications/endpoint/types.ts @@ -17,7 +17,6 @@ import { AlertData, AlertResultList, Immutable, - ImmutableArray, AlertDetails, MalwareFields, UIPolicyConfig, @@ -312,7 +311,7 @@ export type AlertListData = AlertResultList; export interface AlertListState { /** Array of alert items. */ - readonly alerts: ImmutableArray; + readonly alerts: Immutable; /** The total number of alerts on the page. */ readonly total: number; diff --git a/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_forms/events/windows.tsx b/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_forms/events/windows.tsx index 7f946de9614ca7..9d73f12869058f 100644 --- a/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_forms/events/windows.tsx +++ b/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_forms/events/windows.tsx @@ -17,18 +17,18 @@ import { } from '../../../../store/policy_details/selectors'; import { ConfigForm } from '../config_form'; import { setIn, getIn } from '../../../../models/policy_details_config'; -import { UIPolicyConfig, ImmutableArray } from '../../../../../../../common/types'; +import { UIPolicyConfig, Immutable } from '../../../../../../../common/types'; export const WindowsEvents = React.memo(() => { const selected = usePolicyDetailsSelector(selectedWindowsEvents); const total = usePolicyDetailsSelector(totalWindowsEvents); const checkboxes = useMemo(() => { - const items: ImmutableArray<{ + const items: Immutable = [ + }>> = [ { name: i18n.translate('xpack.endpoint.policyDetailsConfig.windows.events.dllDriverLoad', { defaultMessage: 'DLL and Driver Load', diff --git a/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_forms/protections/malware.tsx b/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_forms/protections/malware.tsx index 14871c71ec0386..4b2a6ece9f58fc 100644 --- a/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_forms/protections/malware.tsx +++ b/x-pack/plugins/endpoint/public/applications/endpoint/view/policy/policy_forms/protections/malware.tsx @@ -11,7 +11,7 @@ import { EuiRadio, EuiSwitch, EuiTitle, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { htmlIdGenerator } from '@elastic/eui'; -import { Immutable, ProtectionModes, ImmutableArray } from '../../../../../../../common/types'; +import { Immutable, ProtectionModes } from '../../../../../../../common/types'; import { OS, MalwareProtectionOSes } from '../../../../types'; import { ConfigForm } from '../config_form'; import { policyConfig } from '../../../../store/policy_details/selectors'; @@ -73,11 +73,11 @@ export const MalwareProtections = React.memo(() => { // currently just taking windows.malware, but both windows.malware and mac.malware should be the same value const selected = policyDetailsConfig && policyDetailsConfig.windows.malware.mode; - const radios: ImmutableArray<{ + const radios: Immutable = useMemo(() => { + }>> = useMemo(() => { return [ { id: ProtectionModes.detect, diff --git a/x-pack/plugins/endpoint/server/index_pattern.ts b/x-pack/plugins/endpoint/server/index_pattern.ts index dcedd27fc5a3d4..903d48746bfb31 100644 --- a/x-pack/plugins/endpoint/server/index_pattern.ts +++ b/x-pack/plugins/endpoint/server/index_pattern.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import { Logger, LoggerFactory, RequestHandlerContext } from 'kibana/server'; -import { EndpointAppConstants } from '../common/types'; +import { AlertConstants } from '../common/alert_constants'; import { ESIndexPatternService } from '../../ingest_manager/server'; export interface IndexPatternRetriever { @@ -33,7 +33,7 @@ export class IngestIndexPatternRetriever implements IndexPatternRetriever { * @returns a string representing the index pattern (e.g. `events-endpoint-*`) */ async getEventIndexPattern(ctx: RequestHandlerContext) { - return await this.getIndexPattern(ctx, EndpointAppConstants.EVENT_DATASET); + return await this.getIndexPattern(ctx, AlertConstants.EVENT_DATASET); } /** diff --git a/x-pack/plugins/endpoint/server/routes/alerts/details/handlers.ts b/x-pack/plugins/endpoint/server/routes/alerts/details/handlers.ts index e438ab853f3b52..92f8aacbf26a29 100644 --- a/x-pack/plugins/endpoint/server/routes/alerts/details/handlers.ts +++ b/x-pack/plugins/endpoint/server/routes/alerts/details/handlers.ts @@ -5,7 +5,8 @@ */ import { GetResponse } from 'elasticsearch'; import { KibanaRequest, RequestHandler } from 'kibana/server'; -import { AlertEvent, EndpointAppConstants } from '../../../../common/types'; +import { AlertEvent } from '../../../../common/types'; +import { AlertConstants } from '../../../../common/alert_constants'; import { EndpointAppContext } from '../../../types'; import { AlertDetailsRequestParams } from '../types'; import { AlertDetailsPagination } from './lib'; @@ -22,7 +23,7 @@ export const alertDetailsHandlerWrapper = function( try { const alertId = req.params.id; const response = (await ctx.core.elasticsearch.dataClient.callAsCurrentUser('get', { - index: EndpointAppConstants.ALERT_INDEX_NAME, + index: AlertConstants.ALERT_INDEX_NAME, id: alertId, })) as GetResponse; diff --git a/x-pack/plugins/endpoint/server/routes/alerts/details/lib/pagination.ts b/x-pack/plugins/endpoint/server/routes/alerts/details/lib/pagination.ts index d482da03872c62..0f69e1bb60c44e 100644 --- a/x-pack/plugins/endpoint/server/routes/alerts/details/lib/pagination.ts +++ b/x-pack/plugins/endpoint/server/routes/alerts/details/lib/pagination.ts @@ -5,12 +5,8 @@ */ import { GetResponse, SearchResponse } from 'elasticsearch'; -import { - AlertEvent, - AlertHits, - Direction, - EndpointAppConstants, -} from '../../../../../common/types'; +import { AlertEvent, AlertHits, AlertAPIOrdering } from '../../../../../common/types'; +import { AlertConstants } from '../../../../../common/alert_constants'; import { EndpointConfigType } from '../../../../config'; import { searchESForAlerts, Pagination } from '../../lib'; import { AlertSearchQuery, SearchCursor, AlertDetailsRequestParams } from '../../types'; @@ -36,12 +32,12 @@ export class AlertDetailsPagination extends Pagination< } protected async doSearch( - direction: Direction, + direction: AlertAPIOrdering, cursor: SearchCursor ): Promise> { const reqData: AlertSearchQuery = { pageSize: 1, - sort: EndpointAppConstants.ALERT_LIST_DEFAULT_SORT, + sort: AlertConstants.ALERT_LIST_DEFAULT_SORT, order: 'desc', query: { query: '', language: 'kuery' }, filters: [] as Filter[], diff --git a/x-pack/plugins/endpoint/server/routes/alerts/index.ts b/x-pack/plugins/endpoint/server/routes/alerts/index.ts index 09de11897813b5..b61f90b5b17f5a 100644 --- a/x-pack/plugins/endpoint/server/routes/alerts/index.ts +++ b/x-pack/plugins/endpoint/server/routes/alerts/index.ts @@ -5,12 +5,12 @@ */ import { IRouter } from 'kibana/server'; import { EndpointAppContext } from '../../types'; -import { EndpointAppConstants } from '../../../common/types'; +import { AlertConstants } from '../../../common/alert_constants'; import { alertListHandlerWrapper } from './list'; import { alertDetailsHandlerWrapper, alertDetailsReqSchema } from './details'; import { alertingIndexGetQuerySchema } from '../../../common/schema/alert_index'; -export const BASE_ALERTS_ROUTE = `${EndpointAppConstants.BASE_API_URL}/alerts`; +export const BASE_ALERTS_ROUTE = `${AlertConstants.BASE_API_URL}/alerts`; export function registerAlertRoutes(router: IRouter, endpointAppContext: EndpointAppContext) { router.get( diff --git a/x-pack/plugins/endpoint/server/routes/alerts/lib/index.ts b/x-pack/plugins/endpoint/server/routes/alerts/lib/index.ts index 74db24c85eab5e..7bc1c0c306ae2b 100644 --- a/x-pack/plugins/endpoint/server/routes/alerts/lib/index.ts +++ b/x-pack/plugins/endpoint/server/routes/alerts/lib/index.ts @@ -7,7 +7,8 @@ import { SearchResponse } from 'elasticsearch'; import { IScopedClusterClient } from 'kibana/server'; import { JsonObject } from '../../../../../../../src/plugins/kibana_utils/public'; import { esQuery } from '../../../../../../../src/plugins/data/server'; -import { AlertEvent, Direction, EndpointAppConstants } from '../../../../common/types'; +import { AlertEvent, AlertAPIOrdering } from '../../../../common/types'; +import { AlertConstants } from '../../../../common/alert_constants'; import { AlertSearchQuery, AlertSearchRequest, @@ -18,7 +19,7 @@ import { export { Pagination } from './pagination'; -function reverseSortDirection(order: Direction): Direction { +function reverseSortDirection(order: AlertAPIOrdering): AlertAPIOrdering { if (order === 'asc') { return 'desc'; } @@ -100,13 +101,13 @@ const buildAlertSearchQuery = async ( query: AlertSearchQuery, indexPattern: string ): Promise => { - let totalHitsMin: number = EndpointAppConstants.DEFAULT_TOTAL_HITS; + let totalHitsMin: number = AlertConstants.DEFAULT_TOTAL_HITS; // Calculate minimum total hits set to indicate there's a next page if (query.fromIndex) { totalHitsMin = Math.max( query.fromIndex + query.pageSize * 2, - EndpointAppConstants.DEFAULT_TOTAL_HITS + AlertConstants.DEFAULT_TOTAL_HITS ); } diff --git a/x-pack/plugins/endpoint/server/routes/alerts/list/lib/index.ts b/x-pack/plugins/endpoint/server/routes/alerts/list/lib/index.ts index 95c8e4662cfcea..92bd07a813d264 100644 --- a/x-pack/plugins/endpoint/server/routes/alerts/list/lib/index.ts +++ b/x-pack/plugins/endpoint/server/routes/alerts/list/lib/index.ts @@ -13,10 +13,10 @@ import { AlertData, AlertResultList, AlertHits, - EndpointAppConstants, ESTotal, AlertingIndexGetQueryResult, } from '../../../../../common/types'; +import { AlertConstants } from '../../../../../common/alert_constants'; import { EndpointAppContext } from '../../../../types'; import { AlertSearchQuery } from '../../types'; import { AlertListPagination } from './pagination'; @@ -28,8 +28,8 @@ export const getRequestData = async ( const config = await endpointAppContext.config(); const reqData: AlertSearchQuery = { // Defaults not enforced by schema - pageSize: request.query.page_size || EndpointAppConstants.ALERT_LIST_DEFAULT_PAGE_SIZE, - sort: request.query.sort || EndpointAppConstants.ALERT_LIST_DEFAULT_SORT, + pageSize: request.query.page_size || AlertConstants.ALERT_LIST_DEFAULT_PAGE_SIZE, + sort: request.query.sort || AlertConstants.ALERT_LIST_DEFAULT_SORT, order: request.query.order || 'desc', dateRange: ((request.query.date_range !== undefined ? decode(request.query.date_range) @@ -67,7 +67,7 @@ export const getRequestData = async ( reqData.searchBefore[0] === '' && reqData.emptyStringIsUndefined ) { - reqData.searchBefore[0] = EndpointAppConstants.MAX_LONG_INT; + reqData.searchBefore[0] = AlertConstants.MAX_LONG_INT; } if ( @@ -75,7 +75,7 @@ export const getRequestData = async ( reqData.searchAfter[0] === '' && reqData.emptyStringIsUndefined ) { - reqData.searchAfter[0] = EndpointAppConstants.MAX_LONG_INT; + reqData.searchAfter[0] = AlertConstants.MAX_LONG_INT; } return reqData; diff --git a/x-pack/plugins/endpoint/server/routes/alerts/types.ts b/x-pack/plugins/endpoint/server/routes/alerts/types.ts index cf4eac5d25f800..5aefc35b5758f1 100644 --- a/x-pack/plugins/endpoint/server/routes/alerts/types.ts +++ b/x-pack/plugins/endpoint/server/routes/alerts/types.ts @@ -5,14 +5,14 @@ */ import { Query, Filter, TimeRange } from '../../../../../../src/plugins/data/server'; import { JsonObject } from '../../../../../../src/plugins/kibana_utils/public'; -import { Direction } from '../../../common/types'; +import { AlertAPIOrdering } from '../../../common/types'; /** * Sort parameters for alerts in ES. */ export interface AlertSortParam { [key: string]: { - order: Direction; + order: AlertAPIOrdering; missing?: UndefinedResultPosition; }; } @@ -38,7 +38,7 @@ export interface AlertSearchQuery { filters: Filter[]; dateRange?: TimeRange; sort: string; - order: Direction; + order: AlertAPIOrdering; searchAfter?: SearchCursor; searchBefore?: SearchCursor; emptyStringIsUndefined?: boolean; @@ -83,7 +83,7 @@ export interface AlertListRequestQuery { filters?: string; date_range: string; sort: string; - order: Direction; + order: AlertAPIOrdering; after?: SearchCursor; before?: SearchCursor; empty_string_is_undefined?: boolean; diff --git a/x-pack/plugins/endpoint/server/routes/index_pattern.ts b/x-pack/plugins/endpoint/server/routes/index_pattern.ts index 79083f5f05e149..7e78caaf178e46 100644 --- a/x-pack/plugins/endpoint/server/routes/index_pattern.ts +++ b/x-pack/plugins/endpoint/server/routes/index_pattern.ts @@ -6,7 +6,8 @@ import { IRouter, Logger, RequestHandler } from 'kibana/server'; import { EndpointAppContext } from '../types'; -import { IndexPatternGetParamsResult, EndpointAppConstants } from '../../common/types'; +import { IndexPatternGetParamsResult } from '../../common/types'; +import { AlertConstants } from '../../common/alert_constants'; import { indexPatternGetParamsSchema } from '../../common/schema/index_pattern'; function handleIndexPattern( @@ -33,7 +34,7 @@ export function registerIndexPatternRoute(router: IRouter, endpointAppContext: E router.get( { - path: `${EndpointAppConstants.INDEX_PATTERN_ROUTE}/{datasetPath}`, + path: `${AlertConstants.INDEX_PATTERN_ROUTE}/{datasetPath}`, validate: { params: indexPatternGetParamsSchema }, options: { authRequired: true }, }, diff --git a/x-pack/plugins/endpoint/server/routes/resolver/queries/base.ts b/x-pack/plugins/endpoint/server/routes/resolver/queries/base.ts index b049439207e508..3b3b4b0c9e8ac1 100644 --- a/x-pack/plugins/endpoint/server/routes/resolver/queries/base.ts +++ b/x-pack/plugins/endpoint/server/routes/resolver/queries/base.ts @@ -5,9 +5,9 @@ */ import { IScopedClusterClient } from 'kibana/server'; -import { EndpointAppConstants } from '../../../../common/types'; import { paginate, paginatedResults, PaginationParams } from '../utils/pagination'; import { JsonObject } from '../../../../../../../src/plugins/kibana_utils/public'; +import { legacyEventIndexPattern } from './legacy_event_index_pattern'; export abstract class ResolverQuery { constructor( @@ -25,7 +25,7 @@ export abstract class ResolverQuery { build(...ids: string[]) { if (this.endpointID) { - return this.legacyQuery(this.endpointID, ids, EndpointAppConstants.LEGACY_EVENT_INDEX_NAME); + return this.legacyQuery(this.endpointID, ids, legacyEventIndexPattern); } return this.query(ids, this.indexPattern); } diff --git a/x-pack/plugins/endpoint/server/routes/resolver/queries/children.test.ts b/x-pack/plugins/endpoint/server/routes/resolver/queries/children.test.ts index e73053d53dee08..d1d090579f0cd1 100644 --- a/x-pack/plugins/endpoint/server/routes/resolver/queries/children.test.ts +++ b/x-pack/plugins/endpoint/server/routes/resolver/queries/children.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import { ChildrenQuery } from './children'; -import { EndpointAppConstants } from '../../../../common/types'; +import { legacyEventIndexPattern } from './legacy_event_index_pattern'; export const fakeEventIndexPattern = 'events-endpoint-*'; @@ -12,7 +12,7 @@ describe('children events query', () => { it('generates the correct legacy queries', () => { const timestamp = new Date().getTime(); expect( - new ChildrenQuery(EndpointAppConstants.LEGACY_EVENT_INDEX_NAME, 'awesome-id', { + new ChildrenQuery(legacyEventIndexPattern, 'awesome-id', { size: 1, timestamp, eventID: 'foo', @@ -48,7 +48,7 @@ describe('children events query', () => { size: 1, sort: [{ '@timestamp': 'asc' }, { 'endgame.serial_event_id': 'asc' }], }, - index: EndpointAppConstants.LEGACY_EVENT_INDEX_NAME, + index: legacyEventIndexPattern, }); }); diff --git a/x-pack/plugins/endpoint/server/routes/resolver/queries/legacy_event_index_pattern.ts b/x-pack/plugins/endpoint/server/routes/resolver/queries/legacy_event_index_pattern.ts new file mode 100644 index 00000000000000..01e818c89b3efc --- /dev/null +++ b/x-pack/plugins/endpoint/server/routes/resolver/queries/legacy_event_index_pattern.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/** + * Legacy events are stored in indices with endgame-* prefix + */ +export const legacyEventIndexPattern = 'endgame-*'; diff --git a/x-pack/plugins/endpoint/server/routes/resolver/queries/lifecycle.test.ts b/x-pack/plugins/endpoint/server/routes/resolver/queries/lifecycle.test.ts index 8a3955706b2781..9d3c675ecc54cf 100644 --- a/x-pack/plugins/endpoint/server/routes/resolver/queries/lifecycle.test.ts +++ b/x-pack/plugins/endpoint/server/routes/resolver/queries/lifecycle.test.ts @@ -3,15 +3,14 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { EndpointAppConstants } from '../../../../common/types'; + import { LifecycleQuery } from './lifecycle'; import { fakeEventIndexPattern } from './children.test'; +import { legacyEventIndexPattern } from './legacy_event_index_pattern'; describe('lifecycle query', () => { it('generates the correct legacy queries', () => { - expect( - new LifecycleQuery(EndpointAppConstants.LEGACY_EVENT_INDEX_NAME, 'awesome-id').build('5') - ).toStrictEqual({ + expect(new LifecycleQuery(legacyEventIndexPattern, 'awesome-id').build('5')).toStrictEqual({ body: { query: { bool: { @@ -30,7 +29,7 @@ describe('lifecycle query', () => { }, sort: [{ '@timestamp': 'asc' }], }, - index: EndpointAppConstants.LEGACY_EVENT_INDEX_NAME, + index: legacyEventIndexPattern, }); }); diff --git a/x-pack/plugins/endpoint/server/routes/resolver/queries/related_events.test.ts b/x-pack/plugins/endpoint/server/routes/resolver/queries/related_events.test.ts index 5caef935ce6214..26205e9db6e45e 100644 --- a/x-pack/plugins/endpoint/server/routes/resolver/queries/related_events.test.ts +++ b/x-pack/plugins/endpoint/server/routes/resolver/queries/related_events.test.ts @@ -4,14 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ import { RelatedEventsQuery } from './related_events'; -import { EndpointAppConstants } from '../../../../common/types'; import { fakeEventIndexPattern } from './children.test'; +import { legacyEventIndexPattern } from './legacy_event_index_pattern'; describe('related events query', () => { it('generates the correct legacy queries', () => { const timestamp = new Date().getTime(); expect( - new RelatedEventsQuery(EndpointAppConstants.LEGACY_EVENT_INDEX_NAME, 'awesome-id', { + new RelatedEventsQuery(legacyEventIndexPattern, 'awesome-id', { size: 1, timestamp, eventID: 'foo', @@ -48,7 +48,7 @@ describe('related events query', () => { size: 1, sort: [{ '@timestamp': 'asc' }, { 'endgame.serial_event_id': 'asc' }], }, - index: EndpointAppConstants.LEGACY_EVENT_INDEX_NAME, + index: legacyEventIndexPattern, }); }); From 4e0c11ea406c1b100b403a01a9f24d63ee31b725 Mon Sep 17 00:00:00 2001 From: Patrick Mueller Date: Tue, 28 Apr 2020 12:37:25 -0400 Subject: [PATCH 07/12] [Event Log] use @timestamp field for queries (#64391) resolves https://github.com/elastic/kibana/issues/64275 Changes the fields used to query the event log by time range to use the `@timestamp` field. Also allow `@timestamp` as a sort option, and make it the default sort option. --- .../server/es/cluster_client_adapter.test.ts | 8 +-- .../server/es/cluster_client_adapter.ts | 4 +- .../event_log/server/event_log_client.test.ts | 4 +- .../event_log/server/event_log_client.ts | 3 +- .../event_log/public_api_integration.ts | 51 ++++++------------- .../event_log/service_api_integration.ts | 3 +- 6 files changed, 28 insertions(+), 45 deletions(-) diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts index 470123ada48ea4..f79962a3241317 100644 --- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts +++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts @@ -226,7 +226,7 @@ describe('queryEventsBySavedObject', () => { body: { from: 0, size: 10, - sort: { 'event.start': { order: 'asc' } }, + sort: { '@timestamp': { order: 'asc' } }, query: { bool: { must: [ @@ -340,7 +340,7 @@ describe('queryEventsBySavedObject', () => { }, { range: { - 'event.start': { + '@timestamp': { gte: start, }, }, @@ -409,14 +409,14 @@ describe('queryEventsBySavedObject', () => { }, { range: { - 'event.start': { + '@timestamp': { gte: start, }, }, }, { range: { - 'event.end': { + '@timestamp': { lte: end, }, }, diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts index 6d5c6b31a637c3..47d273b9981e32 100644 --- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts +++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts @@ -176,14 +176,14 @@ export class ClusterClientAdapter { }, start && { range: { - 'event.start': { + '@timestamp': { gte: start, }, }, }, end && { range: { - 'event.end': { + '@timestamp': { lte: end, }, }, diff --git a/x-pack/plugins/event_log/server/event_log_client.test.ts b/x-pack/plugins/event_log/server/event_log_client.test.ts index 6d4c9b67abc1ba..17c073c4b27f9b 100644 --- a/x-pack/plugins/event_log/server/event_log_client.test.ts +++ b/x-pack/plugins/event_log/server/event_log_client.test.ts @@ -112,7 +112,7 @@ describe('EventLogStart', () => { { page: 1, per_page: 10, - sort_field: 'event.start', + sort_field: '@timestamp', sort_order: 'asc', } ); @@ -193,7 +193,7 @@ describe('EventLogStart', () => { { page: 1, per_page: 10, - sort_field: 'event.start', + sort_field: '@timestamp', sort_order: 'asc', start, end, diff --git a/x-pack/plugins/event_log/server/event_log_client.ts b/x-pack/plugins/event_log/server/event_log_client.ts index 765f0895f8e0d1..8ef245e60aadc4 100644 --- a/x-pack/plugins/event_log/server/event_log_client.ts +++ b/x-pack/plugins/event_log/server/event_log_client.ts @@ -36,6 +36,7 @@ export const findOptionsSchema = schema.object({ end: optionalDateFieldSchema, sort_field: schema.oneOf( [ + schema.literal('@timestamp'), schema.literal('event.start'), schema.literal('event.end'), schema.literal('event.provider'), @@ -44,7 +45,7 @@ export const findOptionsSchema = schema.object({ schema.literal('message'), ], { - defaultValue: 'event.start', + defaultValue: '@timestamp', } ), sort_order: schema.oneOf([schema.literal('asc'), schema.literal('desc')], { diff --git a/x-pack/test/plugin_api_integration/test_suites/event_log/public_api_integration.ts b/x-pack/test/plugin_api_integration/test_suites/event_log/public_api_integration.ts index d664357c3ba126..e5b840b335846f 100644 --- a/x-pack/test/plugin_api_integration/test_suites/event_log/public_api_integration.ts +++ b/x-pack/test/plugin_api_integration/test_suites/event_log/public_api_integration.ts @@ -7,7 +7,7 @@ import { merge, omit, times, chunk, isEmpty } from 'lodash'; import uuid from 'uuid'; import expect from '@kbn/expect/expect.js'; -import moment, { Moment } from 'moment'; +import moment from 'moment'; import { FtrProviderContext } from '../../ftr_provider_context'; import { IEvent } from '../../../../plugins/event_log/server'; import { IValidatedEvent } from '../../../../plugins/event_log/server/types'; @@ -43,10 +43,8 @@ export default function({ getService }: FtrProviderContext) { it('should support pagination for events', async () => { const id = uuid.v4(); - const timestamp = moment(); - const [firstExpectedEvent, ...expectedEvents] = times(6, () => - fakeEvent(id, fakeEventTiming(timestamp.add(1, 's'))) - ); + const [firstExpectedEvent, ...expectedEvents] = times(6, () => fakeEvent(id)); + // run one first to create the SO and avoid clashes await logTestEvent(id, firstExpectedEvent); await Promise.all(expectedEvents.map(event => logTestEvent(id, event))); @@ -82,10 +80,7 @@ export default function({ getService }: FtrProviderContext) { it('should support sorting by event end', async () => { const id = uuid.v4(); - const timestamp = moment(); - const [firstExpectedEvent, ...expectedEvents] = times(6, () => - fakeEvent(id, fakeEventTiming(timestamp.add(1, 's'))) - ); + const [firstExpectedEvent, ...expectedEvents] = times(6, () => fakeEvent(id)); // run one first to create the SO and avoid clashes await logTestEvent(id, firstExpectedEvent); await Promise.all(expectedEvents.map(event => logTestEvent(id, event))); @@ -106,21 +101,24 @@ export default function({ getService }: FtrProviderContext) { it('should support date ranges for events', async () => { const id = uuid.v4(); - const timestamp = moment(); - - const firstEvent = fakeEvent(id, fakeEventTiming(timestamp)); + // write a document that shouldn't be found in the inclusive date range search + const firstEvent = fakeEvent(id); await logTestEvent(id, firstEvent); - await delay(100); - const start = timestamp.add(1, 's').toISOString(); + // wait a second, get the start time for the date range search + await delay(1000); + const start = new Date().toISOString(); - const expectedEvents = times(6, () => fakeEvent(id, fakeEventTiming(timestamp.add(1, 's')))); + // write the documents that we should be found in the date range searches + const expectedEvents = times(6, () => fakeEvent(id)); await Promise.all(expectedEvents.map(event => logTestEvent(id, event))); - const end = timestamp.add(1, 's').toISOString(); + // get the end time for the date range search + const end = new Date().toISOString(); - await delay(100); - const lastEvent = fakeEvent(id, fakeEventTiming(timestamp.add(1, 's'))); + // write a document that shouldn't be found in the inclusive date range search + await delay(1000); + const lastEvent = fakeEvent(id); await logTestEvent(id, lastEvent); await retry.try(async () => { @@ -195,29 +193,12 @@ export default function({ getService }: FtrProviderContext) { .expect(200); } - function fakeEventTiming(start: Moment): Partial { - return { - event: { - start: start.toISOString(), - end: start - .clone() - .add(500, 'milliseconds') - .toISOString(), - }, - }; - } - function fakeEvent(id: string, overrides: Partial = {}): IEvent { - const start = moment().toISOString(); - const end = moment().toISOString(); return merge( { event: { provider: 'event_log_fixture', action: 'test', - start, - end, - duration: 1000000, }, kibana: { saved_objects: [ diff --git a/x-pack/test/plugin_api_integration/test_suites/event_log/service_api_integration.ts b/x-pack/test/plugin_api_integration/test_suites/event_log/service_api_integration.ts index 2de395308ce74c..31668e8345275e 100644 --- a/x-pack/test/plugin_api_integration/test_suites/event_log/service_api_integration.ts +++ b/x-pack/test/plugin_api_integration/test_suites/event_log/service_api_integration.ts @@ -3,6 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import uuid from 'uuid'; import expect from '@kbn/expect/expect.js'; import { IEvent } from '../../../../plugins/event_log/server'; import { FtrProviderContext } from '../../ftr_provider_context'; @@ -97,7 +98,7 @@ export default function({ getService }: FtrProviderContext) { await registerProviderActions('provider4', ['action1', 'action2']); } - const eventId = '1'; + const eventId = uuid.v4(); const event: IEvent = { event: { action: 'action1', provider: 'provider4' }, kibana: { saved_objects: [{ type: 'event_log_test', id: eventId }] }, From 3b753ec514a27ac26c1d13e662f3c9f032f53438 Mon Sep 17 00:00:00 2001 From: CJ Cenizal Date: Tue, 28 Apr 2020 09:41:02 -0700 Subject: [PATCH 08/12] ES UI new platform cleanup (#64332) --- ...ore-server.savedobjectscorefieldmapping.md | 1 + ...savedobjectscorefieldmapping.null_value.md | 11 +++ .../server/saved_objects/mappings/types.ts | 1 + src/core/server/server.api.md | 2 + x-pack/index.js | 6 -- .../legacy/plugins/index_management/index.ts | 13 ---- .../legacy/plugins/remote_clusters/index.ts | 40 ----------- .../legacy/plugins/upgrade_assistant/index.ts | 28 -------- .../plugins/upgrade_assistant/mappings.json | 65 ------------------ .../public/application/_hacks.scss} | 5 +- .../public/application/index.js | 2 + .../upgrade_assistant/server/plugin.ts | 15 ++++- .../server/saved_object_types}/index.ts | 5 +- .../reindex_operation_saved_object_type.ts | 63 +++++++++++++++++ .../telemetry_saved_object_type.ts | 67 +++++++++++++++++++ 15 files changed, 162 insertions(+), 162 deletions(-) create mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md delete mode 100644 x-pack/legacy/plugins/index_management/index.ts delete mode 100644 x-pack/legacy/plugins/remote_clusters/index.ts delete mode 100644 x-pack/legacy/plugins/upgrade_assistant/index.ts delete mode 100644 x-pack/legacy/plugins/upgrade_assistant/mappings.json rename x-pack/{legacy/plugins/remote_clusters/public/index.scss => plugins/remote_clusters/public/application/_hacks.scss} (82%) rename x-pack/{legacy/plugins/remote_clusters/common => plugins/upgrade_assistant/server/saved_object_types}/index.ts (59%) create mode 100644 x-pack/plugins/upgrade_assistant/server/saved_object_types/reindex_operation_saved_object_type.ts create mode 100644 x-pack/plugins/upgrade_assistant/server/saved_object_types/telemetry_saved_object_type.ts diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md index 96f11436308569..dbc7d0ca431cec 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.md @@ -19,5 +19,6 @@ export interface SavedObjectsCoreFieldMapping | [enabled](./kibana-plugin-core-server.savedobjectscorefieldmapping.enabled.md) | boolean | | | [fields](./kibana-plugin-core-server.savedobjectscorefieldmapping.fields.md) | {
[subfield: string]: {
type: string;
};
} | | | [index](./kibana-plugin-core-server.savedobjectscorefieldmapping.index.md) | boolean | | +| [null\_value](./kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md) | number | boolean | string | | | [type](./kibana-plugin-core-server.savedobjectscorefieldmapping.type.md) | string | | diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md new file mode 100644 index 00000000000000..627ea3695383a0 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsCoreFieldMapping](./kibana-plugin-core-server.savedobjectscorefieldmapping.md) > [null\_value](./kibana-plugin-core-server.savedobjectscorefieldmapping.null_value.md) + +## SavedObjectsCoreFieldMapping.null\_value property + +Signature: + +```typescript +null_value?: number | boolean | string; +``` diff --git a/src/core/server/saved_objects/mappings/types.ts b/src/core/server/saved_objects/mappings/types.ts index 47fc29f8cf7d29..c1b65763949bbe 100644 --- a/src/core/server/saved_objects/mappings/types.ts +++ b/src/core/server/saved_objects/mappings/types.ts @@ -131,6 +131,7 @@ export interface IndexMappingMeta { */ export interface SavedObjectsCoreFieldMapping { type: string; + null_value?: number | boolean | string; index?: boolean; enabled?: boolean; fields?: { diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index a36e746f6d9405..dc1c9d379d508a 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -1840,6 +1840,8 @@ export interface SavedObjectsCoreFieldMapping { // (undocumented) index?: boolean; // (undocumented) + null_value?: number | boolean | string; + // (undocumented) type: string; } diff --git a/x-pack/index.js b/x-pack/index.js index 3761af5c1ca7a8..fe4c3254059337 100644 --- a/x-pack/index.js +++ b/x-pack/index.js @@ -12,13 +12,10 @@ import { dashboardMode } from './legacy/plugins/dashboard_mode'; import { beats } from './legacy/plugins/beats_management'; import { apm } from './legacy/plugins/apm'; import { maps } from './legacy/plugins/maps'; -import { indexManagement } from './legacy/plugins/index_management'; import { spaces } from './legacy/plugins/spaces'; import { canvas } from './legacy/plugins/canvas'; import { infra } from './legacy/plugins/infra'; import { taskManager } from './legacy/plugins/task_manager'; -import { remoteClusters } from './legacy/plugins/remote_clusters'; -import { upgradeAssistant } from './legacy/plugins/upgrade_assistant'; import { uptime } from './legacy/plugins/uptime'; import { encryptedSavedObjects } from './legacy/plugins/encrypted_saved_objects'; import { actions } from './legacy/plugins/actions'; @@ -38,11 +35,8 @@ module.exports = function(kibana) { apm(kibana), maps(kibana), canvas(kibana), - indexManagement(kibana), infra(kibana), taskManager(kibana), - remoteClusters(kibana), - upgradeAssistant(kibana), uptime(kibana), encryptedSavedObjects(kibana), actions(kibana), diff --git a/x-pack/legacy/plugins/index_management/index.ts b/x-pack/legacy/plugins/index_management/index.ts deleted file mode 100644 index afca15203b9702..00000000000000 --- a/x-pack/legacy/plugins/index_management/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -// TODO: Remove this once CCR is migrated to the plugins directory. -export function indexManagement(kibana: any) { - return new kibana.Plugin({ - id: 'index_management', - configPrefix: 'xpack.index_management', - }); -} diff --git a/x-pack/legacy/plugins/remote_clusters/index.ts b/x-pack/legacy/plugins/remote_clusters/index.ts deleted file mode 100644 index 439cb818d8a562..00000000000000 --- a/x-pack/legacy/plugins/remote_clusters/index.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { resolve } from 'path'; -import { Legacy } from 'kibana'; - -import { PLUGIN } from './common'; - -export function remoteClusters(kibana: any) { - return new kibana.Plugin({ - id: PLUGIN.ID, - configPrefix: 'xpack.remote_clusters', - publicDir: resolve(__dirname, 'public'), - require: ['kibana'], - uiExports: { - styleSheetPaths: resolve(__dirname, 'public/index.scss'), - }, - // TODO: Remove once CCR has migrated to NP - config(Joi: any) { - return Joi.object({ - // display menu item - ui: Joi.object({ - enabled: Joi.boolean().default(true), - }).default(), - - // enable plugin - enabled: Joi.boolean().default(true), - }).default(); - }, - isEnabled(config: Legacy.KibanaConfig) { - return ( - config.get('xpack.remote_clusters.enabled') && config.get('xpack.index_management.enabled') - ); - }, - init() {}, - }); -} diff --git a/x-pack/legacy/plugins/upgrade_assistant/index.ts b/x-pack/legacy/plugins/upgrade_assistant/index.ts deleted file mode 100644 index b5e8ce47502155..00000000000000 --- a/x-pack/legacy/plugins/upgrade_assistant/index.ts +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { Legacy } from 'kibana'; -import mappings from './mappings.json'; - -export function upgradeAssistant(kibana: any) { - const config: Legacy.PluginSpecOptions = { - id: 'upgrade_assistant', - uiExports: { - // @ts-ignore - savedObjectSchemas: { - 'upgrade-assistant-reindex-operation': { - isNamespaceAgnostic: true, - }, - 'upgrade-assistant-telemetry': { - isNamespaceAgnostic: true, - }, - }, - mappings, - }, - - init() {}, - }; - return new kibana.Plugin(config); -} diff --git a/x-pack/legacy/plugins/upgrade_assistant/mappings.json b/x-pack/legacy/plugins/upgrade_assistant/mappings.json deleted file mode 100644 index 885ac4d5a9b44f..00000000000000 --- a/x-pack/legacy/plugins/upgrade_assistant/mappings.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "upgrade-assistant-reindex-operation": { - "dynamic": true, - "properties": { - "indexName": { - "type": "keyword" - }, - "status": { - "type": "integer" - } - } - }, - "upgrade-assistant-telemetry": { - "properties": { - "ui_open": { - "properties": { - "overview": { - "type": "long", - "null_value": 0 - }, - "cluster": { - "type": "long", - "null_value": 0 - }, - "indices": { - "type": "long", - "null_value": 0 - } - } - }, - "ui_reindex": { - "properties": { - "close": { - "type": "long", - "null_value": 0 - }, - "open": { - "type": "long", - "null_value": 0 - }, - "start": { - "type": "long", - "null_value": 0 - }, - "stop": { - "type": "long", - "null_value": 0 - } - } - }, - "features": { - "properties": { - "deprecation_logging": { - "properties": { - "enabled": { - "type": "boolean", - "null_value": true - } - } - } - } - } - } - } -} diff --git a/x-pack/legacy/plugins/remote_clusters/public/index.scss b/x-pack/plugins/remote_clusters/public/application/_hacks.scss similarity index 82% rename from x-pack/legacy/plugins/remote_clusters/public/index.scss rename to x-pack/plugins/remote_clusters/public/application/_hacks.scss index 4ae11323642d8a..b7d81885e716d0 100644 --- a/x-pack/legacy/plugins/remote_clusters/public/index.scss +++ b/x-pack/plugins/remote_clusters/public/application/_hacks.scss @@ -1,7 +1,4 @@ -// Import the EUI global scope so we can use EUI constants -@import 'src/legacy/ui/public/styles/_styling_constants'; - -// Remote clusters plugin styles +// Remote clusters plugin hacks // Prefix all styles with "remoteClusters" to avoid conflicts. // Examples diff --git a/x-pack/plugins/remote_clusters/public/application/index.js b/x-pack/plugins/remote_clusters/public/application/index.js index f2d788c7413428..cf6e855ba58dfa 100644 --- a/x-pack/plugins/remote_clusters/public/application/index.js +++ b/x-pack/plugins/remote_clusters/public/application/index.js @@ -13,6 +13,8 @@ import { App } from './app'; import { remoteClustersStore } from './store'; import { AppContextProvider } from './app_context'; +import './_hacks.scss'; + export const renderApp = (elem, I18nContext, appDependencies) => { render( diff --git a/x-pack/plugins/upgrade_assistant/server/plugin.ts b/x-pack/plugins/upgrade_assistant/server/plugin.ts index bdca506cc73385..0cdf1ca05feac2 100644 --- a/x-pack/plugins/upgrade_assistant/server/plugin.ts +++ b/x-pack/plugins/upgrade_assistant/server/plugin.ts @@ -25,6 +25,8 @@ import { registerClusterCheckupRoutes } from './routes/cluster_checkup'; import { registerDeprecationLoggingRoutes } from './routes/deprecation_logging'; import { registerReindexIndicesRoutes, createReindexWorker } from './routes/reindex_indices'; import { registerTelemetryRoutes } from './routes/telemetry'; +import { telemetrySavedObjectType, reindexOperationSavedObjectType } from './saved_object_types'; + import { RouteDependencies } from './types'; interface PluginsSetup { @@ -57,11 +59,14 @@ export class UpgradeAssistantServerPlugin implements Plugin { } setup( - { http, getStartServices, capabilities }: CoreSetup, + { http, getStartServices, capabilities, savedObjects }: CoreSetup, { usageCollection, cloud, licensing }: PluginsSetup ) { this.licensing = licensing; + savedObjects.registerType(reindexOperationSavedObjectType); + savedObjects.registerType(telemetrySavedObjectType); + const router = http.createRouter(); const dependencies: RouteDependencies = { @@ -85,8 +90,12 @@ export class UpgradeAssistantServerPlugin implements Plugin { registerTelemetryRoutes(dependencies); if (usageCollection) { - getStartServices().then(([{ savedObjects, elasticsearch }]) => { - registerUpgradeAssistantUsageCollector({ elasticsearch, usageCollection, savedObjects }); + getStartServices().then(([{ savedObjects: savedObjectsService, elasticsearch }]) => { + registerUpgradeAssistantUsageCollector({ + elasticsearch, + usageCollection, + savedObjects: savedObjectsService, + }); }); } } diff --git a/x-pack/legacy/plugins/remote_clusters/common/index.ts b/x-pack/plugins/upgrade_assistant/server/saved_object_types/index.ts similarity index 59% rename from x-pack/legacy/plugins/remote_clusters/common/index.ts rename to x-pack/plugins/upgrade_assistant/server/saved_object_types/index.ts index baad348d7a1365..dee0a74d8994bb 100644 --- a/x-pack/legacy/plugins/remote_clusters/common/index.ts +++ b/x-pack/plugins/upgrade_assistant/server/saved_object_types/index.ts @@ -4,6 +4,5 @@ * you may not use this file except in compliance with the Elastic License. */ -export const PLUGIN = { - ID: 'remoteClusters', -}; +export { reindexOperationSavedObjectType } from './reindex_operation_saved_object_type'; +export { telemetrySavedObjectType } from './telemetry_saved_object_type'; diff --git a/x-pack/plugins/upgrade_assistant/server/saved_object_types/reindex_operation_saved_object_type.ts b/x-pack/plugins/upgrade_assistant/server/saved_object_types/reindex_operation_saved_object_type.ts new file mode 100644 index 00000000000000..ba661fbeceb267 --- /dev/null +++ b/x-pack/plugins/upgrade_assistant/server/saved_object_types/reindex_operation_saved_object_type.ts @@ -0,0 +1,63 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { SavedObjectsType } from 'src/core/server'; + +import { REINDEX_OP_TYPE } from '../../common/types'; + +export const reindexOperationSavedObjectType: SavedObjectsType = { + name: REINDEX_OP_TYPE, + hidden: false, + namespaceType: 'agnostic', + mappings: { + properties: { + reindexTaskId: { + type: 'keyword', + }, + indexName: { + type: 'keyword', + }, + newIndexName: { + type: 'keyword', + }, + status: { + type: 'integer', + }, + locked: { + type: 'date', + }, + lastCompletedStep: { + type: 'integer', + }, + errorMessage: { + type: 'keyword', + }, + reindexTaskPercComplete: { + type: 'float', + }, + runningReindexCount: { + type: 'integer', + }, + reindexOptions: { + properties: { + openAndClose: { + type: 'boolean', + }, + queueSettings: { + properties: { + queuedAt: { + type: 'long', + }, + startedAt: { + type: 'long', + }, + }, + }, + }, + }, + }, + }, +}; diff --git a/x-pack/plugins/upgrade_assistant/server/saved_object_types/telemetry_saved_object_type.ts b/x-pack/plugins/upgrade_assistant/server/saved_object_types/telemetry_saved_object_type.ts new file mode 100644 index 00000000000000..b1321e634c0f1c --- /dev/null +++ b/x-pack/plugins/upgrade_assistant/server/saved_object_types/telemetry_saved_object_type.ts @@ -0,0 +1,67 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { SavedObjectsType } from 'src/core/server'; + +import { UPGRADE_ASSISTANT_TYPE } from '../../common/types'; + +export const telemetrySavedObjectType: SavedObjectsType = { + name: UPGRADE_ASSISTANT_TYPE, + hidden: false, + namespaceType: 'agnostic', + mappings: { + properties: { + ui_open: { + properties: { + overview: { + type: 'long', + null_value: 0, + }, + cluster: { + type: 'long', + null_value: 0, + }, + indices: { + type: 'long', + null_value: 0, + }, + }, + }, + ui_reindex: { + properties: { + close: { + type: 'long', + null_value: 0, + }, + open: { + type: 'long', + null_value: 0, + }, + start: { + type: 'long', + null_value: 0, + }, + stop: { + type: 'long', + null_value: 0, + }, + }, + }, + features: { + properties: { + deprecation_logging: { + properties: { + enabled: { + type: 'boolean', + null_value: true, + }, + }, + }, + }, + }, + }, + }, +}; From 02cbd9c374c2b7549427f74dded6b02823db538e Mon Sep 17 00:00:00 2001 From: Aaron Caldwell Date: Tue, 28 Apr 2020 10:41:36 -0600 Subject: [PATCH 09/12] Consolidate cross-cutting concerns between region & coordinate maps in new maps_legacy plugin (#64123) --- .../vis_type_vega/vega_visualization.js | 14 +++++ .../__tests__/region_map_visualization.js | 20 ++++-- .../public/components/region_map_options.tsx | 3 +- .../core_plugins/region_map/public/legacy.ts | 5 -- .../core_plugins/region_map/public/plugin.ts | 19 +++--- .../region_map/public/region_map_type.js | 4 +- .../public/region_map_visualization.js | 21 ++----- .../region_map/public/tooltip.html | 8 --- .../region_map/public/tooltip_formatter.js | 57 +++++++---------- .../core_plugins/region_map/public/util.ts | 3 +- .../core_plugins/tile_map/common/origin.ts | 23 ------- .../coordinate_maps_visualization.js | 20 ++++-- .../public/__tests__/geohash_layer.js | 3 +- .../public/components/tile_map_options.tsx | 4 +- .../tile_map/public/editors/_tooltip.html | 8 --- .../public/editors/_tooltip_formatter.js | 62 ------------------- .../tile_map/public/geohash_layer.js | 3 +- .../core_plugins/tile_map/public/legacy.ts | 5 -- .../core_plugins/tile_map/public/plugin.ts | 20 +++--- .../tile_map/public/shim/index.ts | 20 ------ .../tile_map/public/tile_map_type.js | 3 +- .../tile_map/public/tile_map_visualization.js | 35 ++++------- ...dencies_plugin.ts => tooltip_formatter.js} | 42 +++++++------ .../public/__tests__/map/service_settings.js | 2 +- .../public/common/{ => constants}/origin.ts | 0 .../common/types/external_basemap_types.ts} | 2 +- .../maps_legacy/public/common/types}/index.ts | 8 ++- .../public/common/types}/map_types.ts | 0 .../public/common/types/region_map_types.ts} | 4 +- .../components/wms_internal_options.tsx | 43 ++++++++----- .../public/components/wms_options.tsx | 18 +++--- src/plugins/maps_legacy/public/index.ts | 27 +++++++- .../public/map}/base_maps_visualization.js | 24 ++++--- .../maps_legacy/public/map/kibana_map.js | 30 +++++---- .../public/map/service_settings.js | 2 +- src/plugins/maps_legacy/public/plugin.ts | 12 ++-- .../maps_legacy/public/tooltip_provider.js} | 39 ++++++------ src/plugins/vis_type_vega/public/plugin.ts | 7 ++- src/plugins/vis_type_vega/public/services.ts | 3 + .../public/vega_view/vega_map_view.js | 26 +++----- .../translations/translations/ja-JP.json | 20 ------ .../translations/translations/zh-CN.json | 20 ------ 42 files changed, 274 insertions(+), 415 deletions(-) delete mode 100644 src/legacy/core_plugins/region_map/public/tooltip.html delete mode 100644 src/legacy/core_plugins/tile_map/common/origin.ts delete mode 100644 src/legacy/core_plugins/tile_map/public/editors/_tooltip.html delete mode 100644 src/legacy/core_plugins/tile_map/public/editors/_tooltip_formatter.js delete mode 100644 src/legacy/core_plugins/tile_map/public/shim/index.ts rename src/legacy/core_plugins/tile_map/public/{shim/legacy_dependencies_plugin.ts => tooltip_formatter.js} (57%) rename src/plugins/maps_legacy/public/common/{ => constants}/origin.ts (100%) rename src/{legacy/core_plugins/tile_map/public/types.ts => plugins/maps_legacy/public/common/types/external_basemap_types.ts} (95%) rename src/{legacy/core_plugins/region_map/public/shim => plugins/maps_legacy/public/common/types}/index.ts (79%) rename src/{legacy/core_plugins/tile_map/public => plugins/maps_legacy/public/common/types}/map_types.ts (100%) rename src/{legacy/core_plugins/region_map/public/types.ts => plugins/maps_legacy/public/common/types/region_map_types.ts} (89%) rename src/{legacy/core_plugins/tile_map => plugins/maps_legacy}/public/components/wms_internal_options.tsx (77%) rename src/{legacy/core_plugins/tile_map => plugins/maps_legacy}/public/components/wms_options.tsx (82%) rename src/{legacy/core_plugins/tile_map/public => plugins/maps_legacy/public/map}/base_maps_visualization.js (89%) rename src/{legacy/core_plugins/region_map/public/shim/legacy_dependencies_plugin.ts => plugins/maps_legacy/public/tooltip_provider.js} (56%) diff --git a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js index 21b7ea7dbf4c3b..9f5f4b764f9b05 100644 --- a/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js +++ b/src/legacy/core_plugins/kibana/public/__tests__/vis_type_vega/vega_visualization.js @@ -59,12 +59,14 @@ import { setData, setSavedObjects, setNotifications, + setKibanaMapFactory, // eslint-disable-next-line @kbn/eslint/no-restricted-paths } from '../../../../../../plugins/vis_type_vega/public/services'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { setInjectedVarFunc } from '../../../../../../plugins/maps_legacy/public/kibana_services'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { ServiceSettings } from '../../../../../../plugins/maps_legacy/public/map/service_settings'; +import { getKibanaMapFactoryProvider } from '../../../../../../plugins/maps_legacy/public'; const THRESHOLD = 0.1; const PIXEL_DIFF = 30; @@ -77,6 +79,18 @@ describe('VegaVisualizations', () => { let vegaVisualizationDependencies; let vegaVisType; + const coreSetupMock = { + notifications: { + toasts: {}, + }, + uiSettings: { + get: () => {}, + }, + injectedMetadata: { + getInjectedVar: () => {}, + }, + }; + setKibanaMapFactory(getKibanaMapFactoryProvider(coreSetupMock)); setInjectedVars({ emsTileLayerId: {}, enableExternalUrls: true, diff --git a/src/legacy/core_plugins/region_map/public/__tests__/region_map_visualization.js b/src/legacy/core_plugins/region_map/public/__tests__/region_map_visualization.js index 6e1b0b71609417..87592cf4e750e4 100644 --- a/src/legacy/core_plugins/region_map/public/__tests__/region_map_visualization.js +++ b/src/legacy/core_plugins/region_map/public/__tests__/region_map_visualization.js @@ -54,6 +54,7 @@ import { BaseVisType } from '../../../../../plugins/visualizations/public/vis_ty import { setInjectedVarFunc } from '../../../../../plugins/maps_legacy/public/kibana_services'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { ServiceSettings } from '../../../../../plugins/maps_legacy/public/map/service_settings'; +import { getBaseMapsVis } from '../../../../../plugins/maps_legacy/public'; const THRESHOLD = 0.45; const PIXEL_DIFF = 96; @@ -101,7 +102,7 @@ describe('RegionMapsVisualizationTests', function() { let getManifestStub; beforeEach( - ngMock.inject((Private, $injector) => { + ngMock.inject(() => { setInjectedVarFunc(injectedVar => { switch (injectedVar) { case 'mapConfig': @@ -127,17 +128,28 @@ describe('RegionMapsVisualizationTests', function() { } }); const serviceSettings = new ServiceSettings(); - const uiSettings = $injector.get('config'); const regionmapsConfig = { includeElasticMapsService: true, layers: [], }; + const coreSetupMock = { + notifications: { + toasts: {}, + }, + uiSettings: { + get: () => {}, + }, + injectedMetadata: { + getInjectedVar: () => {}, + }, + }; + const BaseMapsVisualization = getBaseMapsVis(coreSetupMock, serviceSettings); dependencies = { serviceSettings, - $injector, regionmapsConfig, - uiSettings, + uiSettings: coreSetupMock.uiSettings, + BaseMapsVisualization, }; regionMapVisType = new BaseVisType(createRegionMapTypeDefinition(dependencies)); diff --git a/src/legacy/core_plugins/region_map/public/components/region_map_options.tsx b/src/legacy/core_plugins/region_map/public/components/region_map_options.tsx index 31a27c4da7fcfe..5604067433f136 100644 --- a/src/legacy/core_plugins/region_map/public/components/region_map_options.tsx +++ b/src/legacy/core_plugins/region_map/public/components/region_map_options.tsx @@ -32,8 +32,7 @@ import { SelectOption, SwitchOption, } from '../../../../../plugins/charts/public'; -import { WmsOptions } from '../../../tile_map/public/components/wms_options'; -import { RegionMapVisParams } from '../types'; +import { RegionMapVisParams, WmsOptions } from '../../../../../plugins/maps_legacy/public'; const mapLayerForOption = ({ layerId, name }: VectorLayer) => ({ text: name, diff --git a/src/legacy/core_plugins/region_map/public/legacy.ts b/src/legacy/core_plugins/region_map/public/legacy.ts index b0cc767a044e88..4bbd839331e56b 100644 --- a/src/legacy/core_plugins/region_map/public/legacy.ts +++ b/src/legacy/core_plugins/region_map/public/legacy.ts @@ -21,17 +21,12 @@ import { PluginInitializerContext } from 'kibana/public'; import { npSetup, npStart } from 'ui/new_platform'; import { RegionMapPluginSetupDependencies } from './plugin'; -import { LegacyDependenciesPlugin } from './shim'; import { plugin } from '.'; const plugins: Readonly = { expressions: npSetup.plugins.expressions, visualizations: npSetup.plugins.visualizations, mapsLegacy: npSetup.plugins.mapsLegacy, - - // Temporary solution - // It will be removed when all dependent services are migrated to the new platform. - __LEGACY: new LegacyDependenciesPlugin(), }; const pluginInstance = plugin({} as PluginInitializerContext); diff --git a/src/legacy/core_plugins/region_map/public/plugin.ts b/src/legacy/core_plugins/region_map/public/plugin.ts index 1453c2155e2d6f..08a73517dc13b3 100644 --- a/src/legacy/core_plugins/region_map/public/plugin.ts +++ b/src/legacy/core_plugins/region_map/public/plugin.ts @@ -25,28 +25,28 @@ import { } from '../../../../core/public'; import { Plugin as ExpressionsPublicPlugin } from '../../../../plugins/expressions/public'; import { VisualizationsSetup } from '../../../../plugins/visualizations/public'; - -import { LegacyDependenciesPlugin, LegacyDependenciesPluginSetup } from './shim'; - // @ts-ignore import { createRegionMapFn } from './region_map_fn'; // @ts-ignore import { createRegionMapTypeDefinition } from './region_map_type'; -import { IServiceSettings, MapsLegacyPluginSetup } from '../../../../plugins/maps_legacy/public'; +import { + getBaseMapsVis, + IServiceSettings, + MapsLegacyPluginSetup, +} from '../../../../plugins/maps_legacy/public'; /** @private */ -interface RegionMapVisualizationDependencies extends LegacyDependenciesPluginSetup { +interface RegionMapVisualizationDependencies { uiSettings: IUiSettingsClient; regionmapsConfig: RegionMapsConfig; serviceSettings: IServiceSettings; - notificationService: any; + BaseMapsVisualization: any; } /** @internal */ export interface RegionMapPluginSetupDependencies { expressions: ReturnType; visualizations: VisualizationsSetup; - __LEGACY: LegacyDependenciesPlugin; mapsLegacy: MapsLegacyPluginSetup; } @@ -66,14 +66,13 @@ export class RegionMapPlugin implements Plugin, void> { public async setup( core: CoreSetup, - { expressions, visualizations, mapsLegacy, __LEGACY }: RegionMapPluginSetupDependencies + { expressions, visualizations, mapsLegacy }: RegionMapPluginSetupDependencies ) { const visualizationDependencies: Readonly = { uiSettings: core.uiSettings, regionmapsConfig: core.injectedMetadata.getInjectedVar('regionmap') as RegionMapsConfig, serviceSettings: mapsLegacy.serviceSettings, - notificationService: core.notifications.toasts, - ...(await __LEGACY.setup()), + BaseMapsVisualization: getBaseMapsVis(core, mapsLegacy.serviceSettings), }; expressions.registerFunction(createRegionMapFn); diff --git a/src/legacy/core_plugins/region_map/public/region_map_type.js b/src/legacy/core_plugins/region_map/public/region_map_type.js index 9174b03cf843cf..b7ed14ed3706eb 100644 --- a/src/legacy/core_plugins/region_map/public/region_map_type.js +++ b/src/legacy/core_plugins/region_map/public/region_map_type.js @@ -23,9 +23,7 @@ import { createRegionMapVisualization } from './region_map_visualization'; import { RegionMapOptions } from './components/region_map_options'; import { truncatedColorSchemas } from '../../../../plugins/charts/public'; import { Schemas } from '../../../../plugins/vis_default_editor/public'; - -// TODO: reference to TILE_MAP plugin should be removed -import { ORIGIN } from '../../tile_map/common/origin'; +import { ORIGIN } from '../../../../plugins/maps_legacy/public'; export function createRegionMapTypeDefinition(dependencies) { const { uiSettings, regionmapsConfig, serviceSettings } = dependencies; diff --git a/src/legacy/core_plugins/region_map/public/region_map_visualization.js b/src/legacy/core_plugins/region_map/public/region_map_visualization.js index f08d53ee35c8d3..5dbc1ecad277f1 100644 --- a/src/legacy/core_plugins/region_map/public/region_map_visualization.js +++ b/src/legacy/core_plugins/region_map/public/region_map_visualization.js @@ -21,30 +21,21 @@ import { i18n } from '@kbn/i18n'; import ChoroplethLayer from './choropleth_layer'; import { getFormat } from 'ui/visualize/loader/pipeline_helpers/utilities'; import { toastNotifications } from 'ui/notify'; - -import { TileMapTooltipFormatter } from './tooltip_formatter'; import { truncatedColorMaps } from '../../../../plugins/charts/public'; - -// TODO: reference to TILE_MAP plugin should be removed -import { BaseMapsVisualizationProvider } from '../../tile_map/public/base_maps_visualization'; +import { tooltipFormatter } from './tooltip_formatter'; +import { mapTooltipProvider } from '../../../../plugins/maps_legacy/public'; export function createRegionMapVisualization({ serviceSettings, - $injector, uiSettings, - notificationService, + BaseMapsVisualization, }) { - const BaseMapsVisualization = new BaseMapsVisualizationProvider( - serviceSettings, - notificationService - ); - const tooltipFormatter = new TileMapTooltipFormatter($injector); - return class RegionMapsVisualization extends BaseMapsVisualization { constructor(container, vis) { super(container, vis); this._vis = this.vis; this._choroplethLayer = null; + this._tooltipFormatter = mapTooltipProvider(container, tooltipFormatter); } async render(esResponse, visParams) { @@ -89,7 +80,7 @@ export function createRegionMapVisualization({ this._choroplethLayer.setMetrics(results, metricFieldFormatter, valueColumn.name); if (termColumn && valueColumn) { this._choroplethLayer.setTooltipFormatter( - tooltipFormatter, + this._tooltipFormatter, metricFieldFormatter, termColumn.name, valueColumn.name @@ -123,7 +114,7 @@ export function createRegionMapVisualization({ this._choroplethLayer.setColorRamp(truncatedColorMaps[visParams.colorSchema].value); this._choroplethLayer.setLineWeight(visParams.outlineWeight); this._choroplethLayer.setTooltipFormatter( - tooltipFormatter, + this._tooltipFormatter, metricFieldFormatter, this._metricLabel ); diff --git a/src/legacy/core_plugins/region_map/public/tooltip.html b/src/legacy/core_plugins/region_map/public/tooltip.html deleted file mode 100644 index 0d57120c80a983..00000000000000 --- a/src/legacy/core_plugins/region_map/public/tooltip.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - -
{{detail.label}}{{detail.value}}
diff --git a/src/legacy/core_plugins/region_map/public/tooltip_formatter.js b/src/legacy/core_plugins/region_map/public/tooltip_formatter.js index 6df08aea0baa69..8d38095ac25e07 100644 --- a/src/legacy/core_plugins/region_map/public/tooltip_formatter.js +++ b/src/legacy/core_plugins/region_map/public/tooltip_formatter.js @@ -17,39 +17,24 @@ * under the License. */ -import $ from 'jquery'; -import template from './tooltip.html'; - -export const TileMapTooltipFormatter = $injector => { - const $rootScope = $injector.get('$rootScope'); - const $compile = $injector.get('$compile'); - - const $tooltipScope = $rootScope.$new(); - const $el = $('
').html(template); - - $compile($el)($tooltipScope); - - return function tooltipFormatter(metric, fieldFormatter, fieldName, metricName) { - if (!metric) { - return ''; - } - - $tooltipScope.details = []; - if (fieldName && metric) { - $tooltipScope.details.push({ - label: fieldName, - value: metric.term, - }); - } - - if (metric) { - $tooltipScope.details.push({ - label: metricName, - value: fieldFormatter ? fieldFormatter.convert(metric.value, 'text') : metric.value, - }); - } - - $tooltipScope.$apply(); - return $el.html(); - }; -}; +export function tooltipFormatter(metric, fieldFormatter, fieldName, metricName) { + if (!metric) { + return ''; + } + + const details = []; + if (fieldName && metric) { + details.push({ + label: fieldName, + value: metric.term, + }); + } + + if (metric) { + details.push({ + label: metricName, + value: fieldFormatter ? fieldFormatter.convert(metric.value, 'text') : metric.value, + }); + } + return details; +} diff --git a/src/legacy/core_plugins/region_map/public/util.ts b/src/legacy/core_plugins/region_map/public/util.ts index 24c721da1f31ac..b4e0dcd5f35102 100644 --- a/src/legacy/core_plugins/region_map/public/util.ts +++ b/src/legacy/core_plugins/region_map/public/util.ts @@ -18,8 +18,7 @@ */ import { FileLayer, VectorLayer } from '../../../../plugins/maps_legacy/public'; -// TODO: reference to TILE_MAP plugin should be removed -import { ORIGIN } from '../../../../legacy/core_plugins/tile_map/common/origin'; +import { ORIGIN } from '../../../../plugins/maps_legacy/public'; export const mapToLayerWithId = (prefix: string, layer: FileLayer): VectorLayer => ({ ...layer, diff --git a/src/legacy/core_plugins/tile_map/common/origin.ts b/src/legacy/core_plugins/tile_map/common/origin.ts deleted file mode 100644 index 7fcf1c659bdf3c..00000000000000 --- a/src/legacy/core_plugins/tile_map/common/origin.ts +++ /dev/null @@ -1,23 +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 enum ORIGIN { - EMS = 'elastic_maps_service', - KIBANA_YML = 'self_hosted', -} diff --git a/src/legacy/core_plugins/tile_map/public/__tests__/coordinate_maps_visualization.js b/src/legacy/core_plugins/tile_map/public/__tests__/coordinate_maps_visualization.js index 3904c43707906b..bce2e157ebbc8d 100644 --- a/src/legacy/core_plugins/tile_map/public/__tests__/coordinate_maps_visualization.js +++ b/src/legacy/core_plugins/tile_map/public/__tests__/coordinate_maps_visualization.js @@ -53,6 +53,7 @@ import { import { ServiceSettings } from '../../../../../plugins/maps_legacy/public/map/service_settings'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths import { setInjectedVarFunc } from '../../../../../plugins/maps_legacy/public/kibana_services'; +import { getBaseMapsVis } from '../../../../../plugins/maps_legacy/public'; function mockRawData() { const stack = [dummyESResponse]; @@ -114,15 +115,26 @@ describe('CoordinateMapsVisualizationTest', function() { return 'not found'; } }); + + const coreSetupMock = { + notifications: { + toasts: {}, + }, + uiSettings: {}, + injectedMetadata: { + getInjectedVar: () => {}, + }, + }; const serviceSettings = new ServiceSettings(); + const BaseMapsVisualization = getBaseMapsVis(coreSetupMock, serviceSettings); const uiSettings = $injector.get('config'); dependencies = { - serviceSettings, - uiSettings, - $injector, - getPrecision, getZoomPrecision, + getPrecision, + BaseMapsVisualization, + uiSettings, + serviceSettings, }; visType = new BaseVisType(createTileMapTypeDefinition(dependencies)); diff --git a/src/legacy/core_plugins/tile_map/public/__tests__/geohash_layer.js b/src/legacy/core_plugins/tile_map/public/__tests__/geohash_layer.js index fc029d6bccb6e6..bdf9cd806eb8b5 100644 --- a/src/legacy/core_plugins/tile_map/public/__tests__/geohash_layer.js +++ b/src/legacy/core_plugins/tile_map/public/__tests__/geohash_layer.js @@ -24,7 +24,8 @@ import scaledCircleMarkersPng from './scaledCircleMarkers.png'; // import shadedCircleMarkersPng from './shadedCircleMarkers.png'; import { ImageComparator } from 'test_utils/image_comparator'; import GeoHashSampleData from './dummy_es_response.json'; -import { KibanaMap } from '../../../../../plugins/maps_legacy/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { KibanaMap } from '../../../../../plugins/maps_legacy/public/map/kibana_map'; describe('geohash_layer', function() { let domNode; diff --git a/src/legacy/core_plugins/tile_map/public/components/tile_map_options.tsx b/src/legacy/core_plugins/tile_map/public/components/tile_map_options.tsx index 9ca42fe3e4074c..1efb0b2f884f85 100644 --- a/src/legacy/core_plugins/tile_map/public/components/tile_map_options.tsx +++ b/src/legacy/core_plugins/tile_map/public/components/tile_map_options.tsx @@ -28,9 +28,7 @@ import { SelectOption, SwitchOption, } from '../../../../../plugins/charts/public'; -import { WmsOptions } from './wms_options'; -import { TileMapVisParams } from '../types'; -import { MapTypes } from '../map_types'; +import { WmsOptions, TileMapVisParams, MapTypes } from '../../../../../plugins/maps_legacy/public'; export type TileMapOptionsProps = VisOptionsProps; diff --git a/src/legacy/core_plugins/tile_map/public/editors/_tooltip.html b/src/legacy/core_plugins/tile_map/public/editors/_tooltip.html deleted file mode 100644 index 9df5b94a21edad..00000000000000 --- a/src/legacy/core_plugins/tile_map/public/editors/_tooltip.html +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - -
{{detail.label}}{{detail.value}}
diff --git a/src/legacy/core_plugins/tile_map/public/editors/_tooltip_formatter.js b/src/legacy/core_plugins/tile_map/public/editors/_tooltip_formatter.js deleted file mode 100644 index eec90e512b4623..00000000000000 --- a/src/legacy/core_plugins/tile_map/public/editors/_tooltip_formatter.js +++ /dev/null @@ -1,62 +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. - */ - -import $ from 'jquery'; -import { i18n } from '@kbn/i18n'; - -import template from './_tooltip.html'; - -export function TileMapTooltipFormatterProvider($injector) { - const $rootScope = $injector.get('$rootScope'); - const $compile = $injector.get('$compile'); - - const $tooltipScope = $rootScope.$new(); - const $el = $('
').html(template); - - $compile($el)($tooltipScope); - - return function tooltipFormatter(metricTitle, metricFormat, feature) { - if (!feature) { - return ''; - } - - $tooltipScope.details = [ - { - label: metricTitle, - value: metricFormat(feature.properties.value), - }, - { - label: i18n.translate('tileMap.tooltipFormatter.latitudeLabel', { - defaultMessage: 'Latitude', - }), - value: feature.geometry.coordinates[1], - }, - { - label: i18n.translate('tileMap.tooltipFormatter.longitudeLabel', { - defaultMessage: 'Longitude', - }), - value: feature.geometry.coordinates[0], - }, - ]; - - $tooltipScope.$apply(); - - return $el.html(); - }; -} diff --git a/src/legacy/core_plugins/tile_map/public/geohash_layer.js b/src/legacy/core_plugins/tile_map/public/geohash_layer.js index b9acf1a15208f7..f0261483d302d2 100644 --- a/src/legacy/core_plugins/tile_map/public/geohash_layer.js +++ b/src/legacy/core_plugins/tile_map/public/geohash_layer.js @@ -20,12 +20,11 @@ import L from 'leaflet'; import { min, isEqual } from 'lodash'; import { i18n } from '@kbn/i18n'; -import { KibanaMapLayer } from '../../../../plugins/maps_legacy/public'; +import { KibanaMapLayer, MapTypes } from '../../../../plugins/maps_legacy/public'; import { HeatmapMarkers } from './markers/heatmap'; import { ScaledCirclesMarkers } from './markers/scaled_circles'; import { ShadedCirclesMarkers } from './markers/shaded_circles'; import { GeohashGridMarkers } from './markers/geohash_grid'; -import { MapTypes } from './map_types'; export class GeohashLayer extends KibanaMapLayer { constructor(featureCollection, featureCollectionMetaData, options, zoom, kibanaMap) { diff --git a/src/legacy/core_plugins/tile_map/public/legacy.ts b/src/legacy/core_plugins/tile_map/public/legacy.ts index 741e118750f320..dd8d4c6e9311e6 100644 --- a/src/legacy/core_plugins/tile_map/public/legacy.ts +++ b/src/legacy/core_plugins/tile_map/public/legacy.ts @@ -21,17 +21,12 @@ import { PluginInitializerContext } from 'kibana/public'; import { npSetup, npStart } from 'ui/new_platform'; import { TileMapPluginSetupDependencies } from './plugin'; -import { LegacyDependenciesPlugin } from './shim'; import { plugin } from '.'; const plugins: Readonly = { expressions: npSetup.plugins.expressions, visualizations: npSetup.plugins.visualizations, mapsLegacy: npSetup.plugins.mapsLegacy, - - // Temporary solution - // It will be removed when all dependent services are migrated to the new platform. - __LEGACY: new LegacyDependenciesPlugin(), }; const pluginInstance = plugin({} as PluginInitializerContext); diff --git a/src/legacy/core_plugins/tile_map/public/plugin.ts b/src/legacy/core_plugins/tile_map/public/plugin.ts index 2b97407b17b38c..aa1460a7e2890a 100644 --- a/src/legacy/core_plugins/tile_map/public/plugin.ts +++ b/src/legacy/core_plugins/tile_map/public/plugin.ts @@ -25,22 +25,21 @@ import { } from '../../../../core/public'; import { Plugin as ExpressionsPublicPlugin } from '../../../../plugins/expressions/public'; import { VisualizationsSetup } from '../../../../plugins/visualizations/public'; - -import { LegacyDependenciesPlugin, LegacyDependenciesPluginSetup } from './shim'; +// TODO: Determine why visualizations don't populate without this +import 'angular-sanitize'; // @ts-ignore import { createTileMapFn } from './tile_map_fn'; // @ts-ignore import { createTileMapTypeDefinition } from './tile_map_type'; -import { IServiceSettings, MapsLegacyPluginSetup } from '../../../../plugins/maps_legacy/public'; +import { getBaseMapsVis, MapsLegacyPluginSetup } from '../../../../plugins/maps_legacy/public'; /** @private */ -interface TileMapVisualizationDependencies extends LegacyDependenciesPluginSetup { - serviceSettings: IServiceSettings; +interface TileMapVisualizationDependencies { uiSettings: IUiSettingsClient; getZoomPrecision: any; getPrecision: any; - notificationService: any; + BaseMapsVisualization: any; } /** @internal */ @@ -48,7 +47,6 @@ export interface TileMapPluginSetupDependencies { expressions: ReturnType; visualizations: VisualizationsSetup; mapsLegacy: MapsLegacyPluginSetup; - __LEGACY: LegacyDependenciesPlugin; } /** @internal */ @@ -61,16 +59,14 @@ export class TileMapPlugin implements Plugin, void> { public async setup( core: CoreSetup, - { expressions, visualizations, mapsLegacy, __LEGACY }: TileMapPluginSetupDependencies + { expressions, visualizations, mapsLegacy }: TileMapPluginSetupDependencies ) { - const { getZoomPrecision, getPrecision, serviceSettings } = mapsLegacy; + const { getZoomPrecision, getPrecision } = mapsLegacy; const visualizationDependencies: Readonly = { - serviceSettings, getZoomPrecision, getPrecision, - notificationService: core.notifications.toasts, + BaseMapsVisualization: getBaseMapsVis(core, mapsLegacy.serviceSettings), uiSettings: core.uiSettings, - ...(await __LEGACY.setup()), }; expressions.registerFunction(() => createTileMapFn(visualizationDependencies)); diff --git a/src/legacy/core_plugins/tile_map/public/shim/index.ts b/src/legacy/core_plugins/tile_map/public/shim/index.ts deleted file mode 100644 index cfc7b62ff4f86d..00000000000000 --- a/src/legacy/core_plugins/tile_map/public/shim/index.ts +++ /dev/null @@ -1,20 +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 * from './legacy_dependencies_plugin'; diff --git a/src/legacy/core_plugins/tile_map/public/tile_map_type.js b/src/legacy/core_plugins/tile_map/public/tile_map_type.js index ae3a839b600e94..ca6a586d220080 100644 --- a/src/legacy/core_plugins/tile_map/public/tile_map_type.js +++ b/src/legacy/core_plugins/tile_map/public/tile_map_type.js @@ -19,11 +19,10 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; -import { convertToGeoJson } from '../../../../plugins/maps_legacy/public'; +import { convertToGeoJson, MapTypes } from '../../../../plugins/maps_legacy/public'; import { Schemas } from '../../../../plugins/vis_default_editor/public'; import { createTileMapVisualization } from './tile_map_visualization'; import { TileMapOptions } from './components/tile_map_options'; -import { MapTypes } from './map_types'; import { supportsCssFilters } from './css_filters'; import { truncatedColorSchemas } from '../../../../plugins/charts/public'; diff --git a/src/legacy/core_plugins/tile_map/public/tile_map_visualization.js b/src/legacy/core_plugins/tile_map/public/tile_map_visualization.js index fdce8bc51fe869..6a7bda5e188831 100644 --- a/src/legacy/core_plugins/tile_map/public/tile_map_visualization.js +++ b/src/legacy/core_plugins/tile_map/public/tile_map_visualization.js @@ -19,30 +19,24 @@ import { get } from 'lodash'; import { GeohashLayer } from './geohash_layer'; -import { BaseMapsVisualizationProvider } from './base_maps_visualization'; -import { TileMapTooltipFormatterProvider } from './editors/_tooltip_formatter'; import { npStart } from 'ui/new_platform'; import { getFormat } from '../../../ui/public/visualize/loader/pipeline_helpers/utilities'; -import { scaleBounds, geoContains } from '../../../../plugins/maps_legacy/public'; - -export const createTileMapVisualization = ({ - serviceSettings, - $injector, - getZoomPrecision, - getPrecision, - notificationService, -}) => { - const BaseMapsVisualization = new BaseMapsVisualizationProvider( - serviceSettings, - notificationService - ); - const tooltipFormatter = new TileMapTooltipFormatterProvider($injector); +import { + scaleBounds, + geoContains, + mapTooltipProvider, +} from '../../../../plugins/maps_legacy/public'; +import { tooltipFormatter } from './tooltip_formatter'; + +export const createTileMapVisualization = dependencies => { + const { getZoomPrecision, getPrecision, BaseMapsVisualization } = dependencies; return class CoordinateMapsVisualization extends BaseMapsVisualization { constructor(element, vis) { super(element, vis); this._geohashLayer = null; + this._tooltipFormatter = mapTooltipProvider(element, tooltipFormatter); } updateGeohashAgg = () => { @@ -190,18 +184,15 @@ export const createTileMapVisualization = ({ const metricDimension = this._params.dimensions.metric; const metricLabel = metricDimension ? metricDimension.label : ''; const metricFormat = getFormat(metricDimension && metricDimension.format); - const boundTooltipFormatter = tooltipFormatter.bind( - null, - metricLabel, - metricFormat.getConverterFor('text') - ); return { label: metricLabel, valueFormatter: this._geoJsonFeatureCollectionAndMeta ? metricFormat.getConverterFor('text') : null, - tooltipFormatter: this._geoJsonFeatureCollectionAndMeta ? boundTooltipFormatter : null, + tooltipFormatter: this._geoJsonFeatureCollectionAndMeta + ? this._tooltipFormatter.bind(null, metricLabel, metricFormat.getConverterFor('text')) + : null, mapType: newParams.mapType, isFilteredByCollar: this._isFilteredByCollar(), colorRamp: newParams.colorSchema, diff --git a/src/legacy/core_plugins/tile_map/public/shim/legacy_dependencies_plugin.ts b/src/legacy/core_plugins/tile_map/public/tooltip_formatter.js similarity index 57% rename from src/legacy/core_plugins/tile_map/public/shim/legacy_dependencies_plugin.ts rename to src/legacy/core_plugins/tile_map/public/tooltip_formatter.js index 5296e98b09efe8..1c87d4dcca2b57 100644 --- a/src/legacy/core_plugins/tile_map/public/shim/legacy_dependencies_plugin.ts +++ b/src/legacy/core_plugins/tile_map/public/tooltip_formatter.js @@ -17,27 +17,29 @@ * under the License. */ -import chrome from 'ui/chrome'; -import { CoreStart, Plugin } from 'kibana/public'; -// TODO: Determine why visualizations don't populate without this -import 'angular-sanitize'; +import { i18n } from '@kbn/i18n'; -/** @internal */ -export interface LegacyDependenciesPluginSetup { - $injector: any; -} - -export class LegacyDependenciesPlugin - implements Plugin, void> { - public async setup() { - const $injector = await chrome.dangerouslyGetActiveInjector(); - - return { - $injector, - } as LegacyDependenciesPluginSetup; +export function tooltipFormatter(metricTitle, metricFormat, feature) { + if (!feature) { + return ''; } - public start(core: CoreStart) { - // nothing to do here yet - } + return [ + { + label: metricTitle, + value: metricFormat(feature.properties.value), + }, + { + label: i18n.translate('tileMap.tooltipFormatter.latitudeLabel', { + defaultMessage: 'Latitude', + }), + value: feature.geometry.coordinates[1], + }, + { + label: i18n.translate('tileMap.tooltipFormatter.longitudeLabel', { + defaultMessage: 'Longitude', + }), + value: feature.geometry.coordinates[0], + }, + ]; } diff --git a/src/plugins/maps_legacy/public/__tests__/map/service_settings.js b/src/plugins/maps_legacy/public/__tests__/map/service_settings.js index 4cbe098501c675..822378163a7ebc 100644 --- a/src/plugins/maps_legacy/public/__tests__/map/service_settings.js +++ b/src/plugins/maps_legacy/public/__tests__/map/service_settings.js @@ -26,7 +26,7 @@ import EMS_TILES from './ems_mocks/sample_tiles.json'; import EMS_STYLE_ROAD_MAP_BRIGHT from './ems_mocks/sample_style_bright'; import EMS_STYLE_ROAD_MAP_DESATURATED from './ems_mocks/sample_style_desaturated'; import EMS_STYLE_DARK_MAP from './ems_mocks/sample_style_dark'; -import { ORIGIN } from '../../common/origin'; +import { ORIGIN } from '../../common/constants/origin'; describe('service_settings (FKA tilemaptest)', function() { let serviceSettings; diff --git a/src/plugins/maps_legacy/public/common/origin.ts b/src/plugins/maps_legacy/public/common/constants/origin.ts similarity index 100% rename from src/plugins/maps_legacy/public/common/origin.ts rename to src/plugins/maps_legacy/public/common/constants/origin.ts diff --git a/src/legacy/core_plugins/tile_map/public/types.ts b/src/plugins/maps_legacy/public/common/types/external_basemap_types.ts similarity index 95% rename from src/legacy/core_plugins/tile_map/public/types.ts rename to src/plugins/maps_legacy/public/common/types/external_basemap_types.ts index e1b4c27319123a..be9c4d0d9c37bb 100644 --- a/src/legacy/core_plugins/tile_map/public/types.ts +++ b/src/plugins/maps_legacy/public/common/types/external_basemap_types.ts @@ -17,7 +17,7 @@ * under the License. */ -import { TmsLayer } from '../../../../plugins/maps_legacy/public'; +import { TmsLayer } from '../../index'; import { MapTypes } from './map_types'; export interface WMSOptions { diff --git a/src/legacy/core_plugins/region_map/public/shim/index.ts b/src/plugins/maps_legacy/public/common/types/index.ts similarity index 79% rename from src/legacy/core_plugins/region_map/public/shim/index.ts rename to src/plugins/maps_legacy/public/common/types/index.ts index cfc7b62ff4f86d..e6cabdde82cd9a 100644 --- a/src/legacy/core_plugins/region_map/public/shim/index.ts +++ b/src/plugins/maps_legacy/public/common/types/index.ts @@ -17,4 +17,10 @@ * under the License. */ -export * from './legacy_dependencies_plugin'; +/** + * Use * syntax so that these exports do not break when internal + * types are stripped. + */ +export * from './external_basemap_types'; +export * from './map_types'; +export * from './region_map_types'; diff --git a/src/legacy/core_plugins/tile_map/public/map_types.ts b/src/plugins/maps_legacy/public/common/types/map_types.ts similarity index 100% rename from src/legacy/core_plugins/tile_map/public/map_types.ts rename to src/plugins/maps_legacy/public/common/types/map_types.ts diff --git a/src/legacy/core_plugins/region_map/public/types.ts b/src/plugins/maps_legacy/public/common/types/region_map_types.ts similarity index 89% rename from src/legacy/core_plugins/region_map/public/types.ts rename to src/plugins/maps_legacy/public/common/types/region_map_types.ts index 8585bf720e0cf7..0da597068f11e0 100644 --- a/src/legacy/core_plugins/region_map/public/types.ts +++ b/src/plugins/maps_legacy/public/common/types/region_map_types.ts @@ -17,8 +17,8 @@ * under the License. */ -import { VectorLayer, FileLayerField } from '../../../../plugins/maps_legacy/public'; -import { WMSOptions } from '../../tile_map/public/types'; +import { VectorLayer, FileLayerField } from '../../index'; +import { WMSOptions } from './external_basemap_types'; export interface RegionMapVisParams { readonly addTooltip: true; diff --git a/src/legacy/core_plugins/tile_map/public/components/wms_internal_options.tsx b/src/plugins/maps_legacy/public/components/wms_internal_options.tsx similarity index 77% rename from src/legacy/core_plugins/tile_map/public/components/wms_internal_options.tsx rename to src/plugins/maps_legacy/public/components/wms_internal_options.tsx index 47f5b8f31e62be..d1def8153d1a84 100644 --- a/src/legacy/core_plugins/tile_map/public/components/wms_internal_options.tsx +++ b/src/plugins/maps_legacy/public/components/wms_internal_options.tsx @@ -21,8 +21,8 @@ import React from 'react'; import { EuiLink, EuiSpacer, EuiText, EuiScreenReaderOnly } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { TextInputOption } from '../../../../../plugins/charts/public'; -import { WMSOptions } from '../types'; +import { TextInputOption } from '../../../charts/public'; +import { WMSOptions } from '../common/types/external_basemap_types'; interface WmsInternalOptions { wms: WMSOptions; @@ -32,14 +32,14 @@ interface WmsInternalOptions { function WmsInternalOptions({ wms, setValue }: WmsInternalOptions) { const wmsLink = ( - + ); const footnoteText = ( <> @@ -64,7 +64,7 @@ function WmsInternalOptions({ wms, setValue }: WmsInternalOptions) { @@ -74,14 +74,14 @@ function WmsInternalOptions({ wms, setValue }: WmsInternalOptions) { - + } helpText={ <> {footnote} @@ -95,14 +95,17 @@ function WmsInternalOptions({ wms, setValue }: WmsInternalOptions) { - + } helpText={ <> {footnote} @@ -117,7 +120,7 @@ function WmsInternalOptions({ wms, setValue }: WmsInternalOptions) { label={ <> @@ -126,7 +129,7 @@ function WmsInternalOptions({ wms, setValue }: WmsInternalOptions) { helpText={ <> {footnote} @@ -140,14 +143,17 @@ function WmsInternalOptions({ wms, setValue }: WmsInternalOptions) { - + } helpText={ <> {footnote} @@ -161,13 +167,13 @@ function WmsInternalOptions({ wms, setValue }: WmsInternalOptions) { } helpText={ } @@ -179,14 +185,17 @@ function WmsInternalOptions({ wms, setValue }: WmsInternalOptions) { - + } helpText={ <> {footnote} diff --git a/src/legacy/core_plugins/tile_map/public/components/wms_options.tsx b/src/plugins/maps_legacy/public/components/wms_options.tsx similarity index 82% rename from src/legacy/core_plugins/tile_map/public/components/wms_options.tsx rename to src/plugins/maps_legacy/public/components/wms_options.tsx index e74c260d3b8e5c..4892463bb9f856 100644 --- a/src/legacy/core_plugins/tile_map/public/components/wms_options.tsx +++ b/src/plugins/maps_legacy/public/components/wms_options.tsx @@ -21,12 +21,12 @@ import React, { useMemo } from 'react'; import { EuiPanel, EuiSpacer, EuiTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { TmsLayer } from '../../../../../plugins/maps_legacy/public'; -import { Vis } from '../../../../../plugins/visualizations/public'; -import { RegionMapVisParams } from '../../../region_map/public/types'; -import { SelectOption, SwitchOption } from '../../../../../plugins/charts/public'; +import { TmsLayer } from '../index'; +import { Vis } from '../../../visualizations/public'; +import { RegionMapVisParams } from '../common/types/region_map_types'; +import { SelectOption, SwitchOption } from '../../../charts/public'; import { WmsInternalOptions } from './wms_internal_options'; -import { WMSOptions, TileMapVisParams } from '../types'; +import { WMSOptions, TileMapVisParams } from '../common/types/external_basemap_types'; interface Props { stateParams: TileMapVisParams | RegionMapVisParams; @@ -59,7 +59,7 @@ function WmsOptions({ stateParams, setValue, vis }: Props) {

@@ -67,10 +67,10 @@ function WmsOptions({ stateParams, setValue, vis }: Props) { new KibanaMap(...args); +} + +export function getBaseMapsVis(core: CoreSetup, serviceSettings: IServiceSettings) { + const getKibanaMap = getKibanaMapFactoryProvider(core); + return new BaseMapsVisualizationProvider(getKibanaMap, serviceSettings); +} + +export * from './common/types'; +export { ORIGIN } from './common/constants/origin'; + +export { WmsOptions } from './components/wms_options'; + export type MapsLegacyPluginSetup = ReturnType; export type MapsLegacyPluginStart = ReturnType; diff --git a/src/legacy/core_plugins/tile_map/public/base_maps_visualization.js b/src/plugins/maps_legacy/public/map/base_maps_visualization.js similarity index 89% rename from src/legacy/core_plugins/tile_map/public/base_maps_visualization.js rename to src/plugins/maps_legacy/public/map/base_maps_visualization.js index 1dac4607280cc7..c4ac671a5187c6 100644 --- a/src/legacy/core_plugins/tile_map/public/base_maps_visualization.js +++ b/src/plugins/maps_legacy/public/map/base_maps_visualization.js @@ -19,16 +19,14 @@ import _ from 'lodash'; import { i18n } from '@kbn/i18n'; -import { KibanaMap } from '../../../../plugins/maps_legacy/public'; import * as Rx from 'rxjs'; import { filter, first } from 'rxjs/operators'; -import { toastNotifications } from 'ui/notify'; -import chrome from 'ui/chrome'; +import { getInjectedVarFunc, getUiSettings, getToasts } from '../kibana_services'; const WMS_MINZOOM = 0; const WMS_MAXZOOM = 22; //increase this to 22. Better for WMS -export function BaseMapsVisualizationProvider(mapServiceSettings, notificationService) { +export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings) { /** * Abstract base class for a visualization consisting of a map with a single baselayer. * @class BaseMapsVisualization @@ -36,7 +34,7 @@ export function BaseMapsVisualizationProvider(mapServiceSettings, notificationSe */ const serviceSettings = mapServiceSettings; - const toastService = notificationService; + const toastService = getToasts(); return class BaseMapsVisualization { constructor(element, vis) { @@ -99,7 +97,7 @@ export function BaseMapsVisualizationProvider(mapServiceSettings, notificationSe options.center = centerFromUIState ? centerFromUIState : this.vis.params.mapCenter; const services = { toastService }; - this._kibanaMap = new KibanaMap(this._container, options, services); + this._kibanaMap = getKibanaMap(this._container, options, services); this._kibanaMap.setMinZoom(WMS_MINZOOM); //use a default this._kibanaMap.setMaxZoom(WMS_MAXZOOM); //use a default @@ -118,20 +116,20 @@ export function BaseMapsVisualizationProvider(mapServiceSettings, notificationSe _tmsConfigured() { const { wms } = this._getMapsParams(); - const hasTmsBaseLayer = !!wms.selectedTmsLayer; + const hasTmsBaseLayer = wms && !!wms.selectedTmsLayer; return hasTmsBaseLayer; } _wmsConfigured() { const { wms } = this._getMapsParams(); - const hasWmsBaseLayer = !!wms.enabled; + const hasWmsBaseLayer = wms && !!wms.enabled; return hasWmsBaseLayer; } async _updateBaseLayer() { - const emsTileLayerId = chrome.getInjected('emsTileLayerId', true); + const emsTileLayerId = getInjectedVarFunc()('emsTileLayerId', true); if (!this._kibanaMap) { return; @@ -149,7 +147,7 @@ export function BaseMapsVisualizationProvider(mapServiceSettings, notificationSe this._setTmsLayer(initBasemapLayer); } } catch (e) { - toastNotifications.addWarning(e.message); + toastService.addWarning(e.message); return; } return; @@ -176,7 +174,7 @@ export function BaseMapsVisualizationProvider(mapServiceSettings, notificationSe this._setTmsLayer(selectedTmsLayer); } } catch (tmsLoadingError) { - toastNotifications.addWarning(tmsLoadingError.message); + toastService.addWarning(tmsLoadingError.message); } } @@ -190,7 +188,7 @@ export function BaseMapsVisualizationProvider(mapServiceSettings, notificationSe if (typeof isDesaturated !== 'boolean') { isDesaturated = true; } - const isDarkMode = chrome.getUiSettingsClient().get('theme:darkMode'); + const isDarkMode = getUiSettings().get('theme:darkMode'); const meta = await serviceSettings.getAttributesForTMSLayer( tmsLayer, isDesaturated, @@ -208,7 +206,7 @@ export function BaseMapsVisualizationProvider(mapServiceSettings, notificationSe async _updateData() { throw new Error( - i18n.translate('tileMap.baseMapsVisualization.childShouldImplementMethodErrorMessage', { + i18n.translate('maps_legacy.baseMapsVisualization.childShouldImplementMethodErrorMessage', { defaultMessage: 'Child should implement this method to respond to data-update', }) ); diff --git a/src/plugins/maps_legacy/public/map/kibana_map.js b/src/plugins/maps_legacy/public/map/kibana_map.js index 1c4d0882cb7da4..c7cec1b14159aa 100644 --- a/src/plugins/maps_legacy/public/map/kibana_map.js +++ b/src/plugins/maps_legacy/public/map/kibana_map.js @@ -24,7 +24,8 @@ import $ from 'jquery'; import _ from 'lodash'; import { zoomToPrecision } from './zoom_to_precision'; import { i18n } from '@kbn/i18n'; -import { ORIGIN } from '../common/origin'; +import { ORIGIN } from '../common/constants/origin'; +import { getToasts } from '../kibana_services'; function makeFitControl(fitContainer, kibanaMap) { const FitControl = L.Control.extend({ @@ -101,7 +102,7 @@ function makeLegendControl(container, kibanaMap, position) { * Serves as simple abstraction for leaflet as well. */ export class KibanaMap extends EventEmitter { - constructor(containerNode, options, services) { + constructor(containerNode, options) { super(); this._containerNode = containerNode; this._leafletBaseLayer = null; @@ -116,7 +117,6 @@ export class KibanaMap extends EventEmitter { this._layers = []; this._listeners = []; this._showTooltip = false; - this.toastService = services ? services.toastService : null; const leafletOptions = { minZoom: options.minZoom, @@ -483,21 +483,19 @@ export class KibanaMap extends EventEmitter { } _addMaxZoomMessage = layer => { - if (this.toastService) { - const zoomWarningMsg = createZoomWarningMsg( - this.toastService, - this.getZoomLevel, - this.getMaxZoomLevel - ); + const zoomWarningMsg = createZoomWarningMsg( + getToasts(), + this.getZoomLevel, + this.getMaxZoomLevel + ); - this._leafletMap.on('zoomend', zoomWarningMsg); - this._containerNode.setAttribute('data-test-subj', 'zoomWarningEnabled'); + this._leafletMap.on('zoomend', zoomWarningMsg); + this._containerNode.setAttribute('data-test-subj', 'zoomWarningEnabled'); - layer.on('remove', () => { - this._leafletMap.off('zoomend', zoomWarningMsg); - this._containerNode.removeAttribute('data-test-subj'); - }); - } + layer.on('remove', () => { + this._leafletMap.off('zoomend', zoomWarningMsg); + this._containerNode.removeAttribute('data-test-subj'); + }); }; setLegendPosition(position) { diff --git a/src/plugins/maps_legacy/public/map/service_settings.js b/src/plugins/maps_legacy/public/map/service_settings.js index f4f0d66ee20ded..8e3a0648e99d4b 100644 --- a/src/plugins/maps_legacy/public/map/service_settings.js +++ b/src/plugins/maps_legacy/public/map/service_settings.js @@ -22,7 +22,7 @@ import MarkdownIt from 'markdown-it'; import { EMSClient } from '@elastic/ems-client'; import { i18n } from '@kbn/i18n'; import { getInjectedVarFunc } from '../kibana_services'; -import { ORIGIN } from '../common/origin'; +import { ORIGIN } from '../common/constants/origin'; const TMS_IN_YML_ID = 'TMS in config/kibana.yml'; diff --git a/src/plugins/maps_legacy/public/plugin.ts b/src/plugins/maps_legacy/public/plugin.ts index 751be65e1dbf6e..acc7655a5e2636 100644 --- a/src/plugins/maps_legacy/public/plugin.ts +++ b/src/plugins/maps_legacy/public/plugin.ts @@ -33,18 +33,20 @@ import { MapsLegacyPluginSetup, MapsLegacyPluginStart } from './index'; * @public */ +export const bindSetupCoreAndPlugins = (core: CoreSetup) => { + setToasts(core.notifications.toasts); + setUiSettings(core.uiSettings); + setInjectedVarFunc(core.injectedMetadata.getInjectedVar); +}; + // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface MapsLegacySetupDependencies {} // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface MapsLegacyStartDependencies {} export class MapsLegacyPlugin implements Plugin { - constructor() {} - public setup(core: CoreSetup, plugins: MapsLegacySetupDependencies) { - setToasts(core.notifications.toasts); - setUiSettings(core.uiSettings); - setInjectedVarFunc(core.injectedMetadata.getInjectedVar); + bindSetupCoreAndPlugins(core); return { serviceSettings: new ServiceSettings(), diff --git a/src/legacy/core_plugins/region_map/public/shim/legacy_dependencies_plugin.ts b/src/plugins/maps_legacy/public/tooltip_provider.js similarity index 56% rename from src/legacy/core_plugins/region_map/public/shim/legacy_dependencies_plugin.ts rename to src/plugins/maps_legacy/public/tooltip_provider.js index 3a7615e83f2817..85631408169971 100644 --- a/src/legacy/core_plugins/region_map/public/shim/legacy_dependencies_plugin.ts +++ b/src/plugins/maps_legacy/public/tooltip_provider.js @@ -17,26 +17,27 @@ * under the License. */ -import chrome from 'ui/chrome'; -import { CoreStart, Plugin } from 'kibana/public'; +import React from 'react'; +import ReactDOMServer from 'react-dom/server'; -/** @internal */ -export interface LegacyDependenciesPluginSetup { - $injector: any; - serviceSettings: any; +function getToolTipContent(details) { + return ReactDOMServer.renderToStaticMarkup( + + + {details.map((detail, i) => ( + + + + + ))} + +
{detail.label}{detail.value}
+ ); } -export class LegacyDependenciesPlugin - implements Plugin, void> { - public async setup() { - const $injector = await chrome.dangerouslyGetActiveInjector(); - - return { - $injector, - } as LegacyDependenciesPluginSetup; - } - - public start(core: CoreStart) { - // nothing to do here yet - } +export function mapTooltipProvider(element, formatter) { + return (...args) => { + const details = formatter(...args); + return details && getToolTipContent(details); + }; } diff --git a/src/plugins/vis_type_vega/public/plugin.ts b/src/plugins/vis_type_vega/public/plugin.ts index c312705194cde2..b52dcfbd914f9a 100644 --- a/src/plugins/vis_type_vega/public/plugin.ts +++ b/src/plugins/vis_type_vega/public/plugin.ts @@ -26,14 +26,14 @@ import { setSavedObjects, setInjectedVars, setUISettings, + setKibanaMapFactory, } from './services'; import { createVegaFn } from './vega_fn'; import { createVegaTypeDefinition } from './vega_type'; -import { IServiceSettings } from '../../maps_legacy/public'; -import { ConfigSchema } from '../config'; - +import { getKibanaMapFactoryProvider, IServiceSettings } from '../../maps_legacy/public'; import './index.scss'; +import { ConfigSchema } from '../config'; /** @internal */ export interface VegaVisualizationDependencies { @@ -75,6 +75,7 @@ export class VegaPlugin implements Plugin, void> { emsTileLayerId: core.injectedMetadata.getInjectedVar('emsTileLayerId', true), }); setUISettings(core.uiSettings); + setKibanaMapFactory(getKibanaMapFactoryProvider(core)); const visualizationDependencies: Readonly = { core, diff --git a/src/plugins/vis_type_vega/public/services.ts b/src/plugins/vis_type_vega/public/services.ts index e349cfbdc0024d..f81f87d7ad2e17 100644 --- a/src/plugins/vis_type_vega/public/services.ts +++ b/src/plugins/vis_type_vega/public/services.ts @@ -27,6 +27,9 @@ export const [getData, setData] = createGetterSetter('Dat export const [getNotifications, setNotifications] = createGetterSetter( 'Notifications' ); +export const [getKibanaMapFactory, setKibanaMapFactory] = createGetterSetter( + 'KibanaMapFactory' +); export const [getUISettings, setUISettings] = createGetterSetter('UISettings'); diff --git a/src/plugins/vis_type_vega/public/vega_view/vega_map_view.js b/src/plugins/vis_type_vega/public/vega_view/vega_map_view.js index bd6652a597203b..895d496a896aa3 100644 --- a/src/plugins/vis_type_vega/public/vega_view/vega_map_view.js +++ b/src/plugins/vis_type_vega/public/vega_view/vega_map_view.js @@ -21,13 +21,11 @@ import * as vega from 'vega-lib'; import { i18n } from '@kbn/i18n'; import { VegaBaseView } from './vega_base_view'; import { VegaMapLayer } from './vega_map_layer'; -import { KibanaMap } from '../../../maps_legacy/public'; -import { getEmsTileLayerId, getUISettings } from '../services'; +import { getEmsTileLayerId, getUISettings, getKibanaMapFactory } from '../services'; export class VegaMapView extends VegaBaseView { - constructor(opts, services) { + constructor(opts) { super(opts); - this.services = services; } async _initViewCustomizations() { @@ -107,18 +105,14 @@ export class VegaMapView extends VegaBaseView { // maxBounds = L.latLngBounds(L.latLng(b[1], b[0]), L.latLng(b[3], b[2])); // } - this._kibanaMap = new KibanaMap( - this._$container.get(0), - { - zoom, - minZoom, - maxZoom, - center: [mapConfig.latitude, mapConfig.longitude], - zoomControl: mapConfig.zoomControl, - scrollWheelZoom: mapConfig.scrollWheelZoom, - }, - this.services - ); + this._kibanaMap = getKibanaMapFactory()(this._$container.get(0), { + zoom, + minZoom, + maxZoom, + center: [mapConfig.latitude, mapConfig.longitude], + zoomControl: mapConfig.zoomControl, + scrollWheelZoom: mapConfig.scrollWheelZoom, + }); if (baseMapOpts) { this._kibanaMap.setBaseLayer({ diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index ac074d99e9ff50..d48e65fabb8d35 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -2579,7 +2579,6 @@ "telemetry.welcomeBanner.enableButtonLabel": "有効にする", "telemetry.welcomeBanner.telemetryConfigDetailsDescription.telemetryPrivacyStatementLinkText": "遠隔測定に関するプライバシーステートメント", "telemetry.welcomeBanner.title": "Elastic Stack の改善にご協力ください", - "tileMap.baseMapsVisualization.childShouldImplementMethodErrorMessage": "子は data-update に対応できるようこのメソドを導入する必要があります", "tileMap.function.help": "タイルマップのビジュアライゼーションです", "tileMap.geohashLayer.mapTitle": "{mapType} マップタイプが認識されません", "tileMap.tooltipFormatter.latitudeLabel": "緯度", @@ -2601,25 +2600,6 @@ "tileMap.visParams.desaturateTilesLabel": "タイルを不飽和化", "tileMap.visParams.mapTypeLabel": "マップタイプ", "tileMap.visParams.reduceVibrancyOfTileColorsTip": "色の鮮明度を下げます。この機能は Internet Explorer ではバージョンにかかわらず利用できません。", - "tileMap.wmsOptions.attributionStringTip": "右下角の属性文字列", - "tileMap.wmsOptions.baseLayerSettingsTitle": "ベースレイヤー設定", - "tileMap.wmsOptions.imageFormatToUseTip": "通常画像/png または画像/jpeg です。サーバーが透明レイヤーを返す場合は png を使用します。", - "tileMap.wmsOptions.layersLabel": "レイヤー", - "tileMap.wmsOptions.listOfLayersToUseTip": "使用するレイヤーのコンマ区切りのリストです。", - "tileMap.wmsOptions.mapLoadFailDescription": "このパラメーターが正しくないと、マップが正常に読み込まれません。", - "tileMap.wmsOptions.urlOfWMSWebServiceTip": "WMS web サービスの URL です。", - "tileMap.wmsOptions.useWMSCompliantMapTileServerTip": "WMS 対応のマップタイルサーバーを使用します。上級者向けです。", - "tileMap.wmsOptions.versionOfWMSserverSupportsTip": "サーバーがサポートしている WMS のバージョンです。", - "tileMap.wmsOptions.wmsAttributionLabel": "WMS 属性", - "tileMap.wmsOptions.wmsDescription": "WMS は、マップイメージサービスの {wmsLink} です。", - "tileMap.wmsOptions.wmsFormatLabel": "WMS フォーマット", - "tileMap.wmsOptions.wmsLayersLabel": "WMS レイヤー", - "tileMap.wmsOptions.wmsLinkText": "OGC スタンダード", - "tileMap.wmsOptions.wmsMapServerLabel": "WMS マップサーバー", - "tileMap.wmsOptions.wmsServerSupportedStylesListTip": "WMS サーバーがサポートしている使用スタイルのコンマ区切りのリストです。大抵は空白のままです。", - "tileMap.wmsOptions.wmsStylesLabel": "WMS スタイル", - "tileMap.wmsOptions.wmsUrlLabel": "WMS URL", - "tileMap.wmsOptions.wmsVersionLabel": "WMS バージョン", "timelion.badge.readOnly.text": "読み込み専用", "timelion.badge.readOnly.tooltip": "Timelion シートを保存できません", "timelion.breadcrumbs.create": "作成", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 60b958623bdc76..196c8183e0cc11 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -2580,7 +2580,6 @@ "telemetry.welcomeBanner.enableButtonLabel": "启用", "telemetry.welcomeBanner.telemetryConfigDetailsDescription.telemetryPrivacyStatementLinkText": "遥测隐私声明", "telemetry.welcomeBanner.title": "帮助我们改进 Elastic Stack", - "tileMap.baseMapsVisualization.childShouldImplementMethodErrorMessage": "子函数应实现此方法以响应数据更新", "tileMap.function.help": "磁贴地图可视化", "tileMap.geohashLayer.mapTitle": "{mapType} 地图类型无法识别", "tileMap.tooltipFormatter.latitudeLabel": "纬度", @@ -2602,25 +2601,6 @@ "tileMap.visParams.desaturateTilesLabel": "降低平铺地图饱和度", "tileMap.visParams.mapTypeLabel": "地图类型", "tileMap.visParams.reduceVibrancyOfTileColorsTip": "降低平铺地图颜色的亮度。此设置在任何版本的 IE 浏览器中均不起作用。", - "tileMap.wmsOptions.attributionStringTip": "右下角的属性字符串。", - "tileMap.wmsOptions.baseLayerSettingsTitle": "基础图层设置", - "tileMap.wmsOptions.imageFormatToUseTip": "通常为 image/png 或 image/jpeg。如果服务器返回透明图层,则使用 png。", - "tileMap.wmsOptions.layersLabel": "图层", - "tileMap.wmsOptions.listOfLayersToUseTip": "要使用的图层逗号分隔列表。", - "tileMap.wmsOptions.mapLoadFailDescription": "如果此参数不正确,将无法加载地图。", - "tileMap.wmsOptions.urlOfWMSWebServiceTip": "WMS Web 服务的 URL。", - "tileMap.wmsOptions.useWMSCompliantMapTileServerTip": "使用符合 WMS 规范的平铺地图服务器。仅适用于高级用户。", - "tileMap.wmsOptions.versionOfWMSserverSupportsTip": "服务器支持的 WMS 版本。", - "tileMap.wmsOptions.wmsAttributionLabel": "WMS 属性", - "tileMap.wmsOptions.wmsDescription": "WMS 是用于地图图像服务的 {wmsLink}。", - "tileMap.wmsOptions.wmsFormatLabel": "WMS 格式", - "tileMap.wmsOptions.wmsLayersLabel": "WMS 图层", - "tileMap.wmsOptions.wmsLinkText": "OGC 标准", - "tileMap.wmsOptions.wmsMapServerLabel": "WMS 地图服务器", - "tileMap.wmsOptions.wmsServerSupportedStylesListTip": "要使用的以逗号分隔的 WMS 服务器支持的样式列表。在大部分情况下为空。", - "tileMap.wmsOptions.wmsStylesLabel": "WMS 样式", - "tileMap.wmsOptions.wmsUrlLabel": "WMS url", - "tileMap.wmsOptions.wmsVersionLabel": "WMS 版本", "timelion.badge.readOnly.text": "只读", "timelion.badge.readOnly.tooltip": "无法保存 Timelion 工作表", "timelion.breadcrumbs.create": "创建", From cd4980a72ba9f4804f0968f8cf1d0172885edc18 Mon Sep 17 00:00:00 2001 From: Nicolas Chaulet Date: Tue, 28 Apr 2020 13:42:46 -0400 Subject: [PATCH 10/12] [Ingest] Fix GET /enrollment-api-keys/null error (#64595) --- .../hooks/use_request/agent_config.ts | 16 +- .../hooks/use_request/enrollment_api_keys.ts | 18 ++- .../hooks/use_request/use_request.ts | 66 ++++++++ .../details_page/components/yaml/index.tsx | 2 +- .../components/details_section.tsx | 2 +- .../agent_enrollment_flyout/index.tsx | 2 +- .../agent_enrollment_flyout/instructions.tsx | 7 +- .../agent_enrollment_flyout/key_selection.tsx | 26 ++- .../confirm_delete_modal.tsx | 46 ------ .../create_api_key_form.tsx | 94 ----------- .../components/enrollment_api_keys/hooks.tsx | 43 ----- .../components/enrollment_api_keys/index.tsx | 152 ------------------ .../agent_reassign_config_flyout/index.tsx | 2 +- .../translations/translations/ja-JP.json | 11 -- .../translations/translations/zh-CN.json | 11 -- 15 files changed, 108 insertions(+), 390 deletions(-) delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/confirm_delete_modal.tsx delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/create_api_key_form.tsx delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/hooks.tsx delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/index.tsx diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_config.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_config.ts index d16d835f8c701c..bed3f994005ad2 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_config.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_config.ts @@ -4,7 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ import { HttpFetchQuery } from 'src/core/public'; -import { useRequest, sendRequest } from './use_request'; +import { + useRequest, + sendRequest, + useConditionalRequest, + SendConditionalRequestConfig, +} from './use_request'; import { agentConfigRouteService } from '../../services'; import { GetAgentConfigsResponse, @@ -25,11 +30,12 @@ export const useGetAgentConfigs = (query: HttpFetchQuery = {}) => { }); }; -export const useGetOneAgentConfig = (agentConfigId: string) => { - return useRequest({ - path: agentConfigRouteService.getInfoPath(agentConfigId), +export const useGetOneAgentConfig = (agentConfigId: string | undefined) => { + return useConditionalRequest({ + path: agentConfigId ? agentConfigRouteService.getInfoPath(agentConfigId) : undefined, method: 'get', - }); + shouldSendRequest: !!agentConfigId, + } as SendConditionalRequestConfig); }; export const useGetOneAgentConfigFull = (agentConfigId: string) => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/enrollment_api_keys.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/enrollment_api_keys.ts index e4abb4ccd22cb5..10d9e03e986e10 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/enrollment_api_keys.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/enrollment_api_keys.ts @@ -4,7 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useRequest, UseRequestConfig, sendRequest } from './use_request'; +import { + useRequest, + UseRequestConfig, + sendRequest, + useConditionalRequest, + SendConditionalRequestConfig, +} from './use_request'; import { enrollmentAPIKeyRouteService } from '../../services'; import { GetOneEnrollmentAPIKeyResponse, @@ -14,12 +20,12 @@ import { type RequestOptions = Pick, 'pollIntervalMs'>; -export function useGetOneEnrollmentAPIKey(keyId: string, options?: RequestOptions) { - return useRequest({ +export function useGetOneEnrollmentAPIKey(keyId: string | undefined) { + return useConditionalRequest({ method: 'get', - path: enrollmentAPIKeyRouteService.getInfoPath(keyId), - ...options, - }); + path: keyId ? enrollmentAPIKeyRouteService.getInfoPath(keyId) : undefined, + shouldSendRequest: !!keyId, + } as SendConditionalRequestConfig); } export function sendGetOneEnrollmentAPIKey(keyId: string, options?: RequestOptions) { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/use_request.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/use_request.ts index c63383637e792f..fbbc482fb96af2 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/use_request.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/use_request.ts @@ -3,6 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { useState, useEffect } from 'react'; import { HttpSetup } from 'src/core/public'; import { SendRequestConfig, @@ -35,3 +36,68 @@ export const useRequest = (config: UseRequestConfig) => { } return _useRequest(httpClient, config); }; + +export type SendConditionalRequestConfig = + | (SendRequestConfig & { shouldSendRequest: true }) + | (Partial & { shouldSendRequest: false }); + +export const useConditionalRequest = (config: SendConditionalRequestConfig) => { + const [state, setState] = useState<{ + error: Error | null; + data: D | null; + isLoading: boolean; + }>({ + error: null, + data: null, + isLoading: false, + }); + + const { path, method, shouldSendRequest, query, body } = config; + + async function sendGetOneEnrollmentAPIKeyRequest() { + if (!config.shouldSendRequest) { + setState({ + data: null, + isLoading: false, + error: null, + }); + return; + } + + try { + setState({ + data: null, + isLoading: true, + error: null, + }); + const res = await sendRequest({ + method: config.method, + path: config.path, + query: config.query, + body: config.body, + }); + if (res.error) { + throw res.error; + } + setState({ + data: res.data, + isLoading: false, + error: null, + }); + return res; + } catch (error) { + setState({ + data: null, + isLoading: false, + error, + }); + } + } + + useEffect(() => { + sendGetOneEnrollmentAPIKeyRequest(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [path, method, shouldSendRequest, JSON.stringify(query), JSON.stringify(body)]); + + return { ...state, sendRequest: sendGetOneEnrollmentAPIKeyRequest }; +}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/yaml/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/yaml/index.tsx index ad27c590d5eaae..f1d7bd5dbc0396 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/yaml/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/yaml/index.tsx @@ -45,7 +45,7 @@ export const ConfigYamlView = memo<{ config: AgentConfig }>(({ config }) => { page: 1, perPage: 1000, }); - const apiKeyRequest = useGetOneEnrollmentAPIKey(apiKeysRequest.data?.list?.[0]?.id as string); + const apiKeyRequest = useGetOneEnrollmentAPIKey(apiKeysRequest.data?.list?.[0]?.id); if (fullConfigRequest.isLoading && !fullConfigRequest.data) { return ; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/details_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/details_section.tsx index 653e2eb9a3a3bb..b69dd6bcf84319 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/details_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/details_section.tsx @@ -71,7 +71,7 @@ export const AgentDetailSection: React.FunctionComponent = ({ agent }) => // Fetch AgentConfig information const { isLoading: isAgentConfigLoading, data: agentConfigData } = useGetOneAgentConfig( - agent.config_id as string + agent.config_id ); const items = [ diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/index.tsx index 9c14a2e9dfed13..dd34e7260b27b4 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/index.tsx @@ -30,7 +30,7 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ onClose, agentConfigs = [], }) => { - const [selectedAPIKeyId, setSelectedAPIKeyId] = useState(null); + const [selectedAPIKeyId, setSelectedAPIKeyId] = useState(); return ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/instructions.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/instructions.tsx index a0244c601cd963..1d2f3bd155622f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/instructions.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/instructions.tsx @@ -7,16 +7,15 @@ import React, { useState } from 'react'; import { i18n } from '@kbn/i18n'; import { EuiSpacer, EuiText, EuiButtonGroup, EuiSteps } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { useEnrollmentApiKey } from '../enrollment_api_keys'; import { ShellEnrollmentInstructions, ManualInstructions, } from '../../../../../components/enrollment_instructions'; -import { useCore, useGetAgents } from '../../../../../hooks'; +import { useCore, useGetAgents, useGetOneEnrollmentAPIKey } from '../../../../../hooks'; import { Loading } from '../../../components'; interface Props { - selectedAPIKeyId: string | null; + selectedAPIKeyId: string | undefined; } function useNewEnrolledAgents() { // New enrolled agents @@ -44,7 +43,7 @@ export const EnrollmentInstructions: React.FunctionComponent = ({ selecte const core = useCore(); const [installType, setInstallType] = useState<'quickInstall' | 'manual'>('quickInstall'); - const apiKey = useEnrollmentApiKey(selectedAPIKeyId); + const apiKey = useGetOneEnrollmentAPIKey(selectedAPIKeyId); const newAgents = useNewEnrolledAgents(); if (!apiKey.data) { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/key_selection.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/key_selection.tsx index 89801bc6bee1ed..67930e51418b0c 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/key_selection.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/agent_enrollment_flyout/key_selection.tsx @@ -16,17 +16,16 @@ import { EuiFieldText, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { useEnrollmentApiKeys } from '../enrollment_api_keys'; import { AgentConfig } from '../../../../../types'; -import { useInput, useCore, sendRequest } from '../../../../../hooks'; +import { useInput, useCore, sendRequest, useGetEnrollmentAPIKeys } from '../../../../../hooks'; import { enrollmentAPIKeyRouteService } from '../../../../../services'; interface Props { - onKeyChange: (keyId: string | null) => void; + onKeyChange: (keyId: string | undefined) => void; agentConfigs: AgentConfig[]; } -function useCreateApiKeyForm(configId: string | null, onSuccess: (keyId: string) => void) { +function useCreateApiKeyForm(configId: string | undefined, onSuccess: (keyId: string) => void) { const { notifications } = useCore(); const [isLoading, setIsLoading] = useState(false); const apiKeyNameInput = useInput(''); @@ -62,17 +61,16 @@ function useCreateApiKeyForm(configId: string | null, onSuccess: (keyId: string) } export const APIKeySelection: React.FunctionComponent = ({ onKeyChange, agentConfigs }) => { - const enrollmentAPIKeysRequest = useEnrollmentApiKeys({ - currentPage: 1, - pageSize: 1000, + const enrollmentAPIKeysRequest = useGetEnrollmentAPIKeys({ + page: 1, + perPage: 1000, }); const [selectedState, setSelectedState] = useState<{ - agentConfigId: string | null; - enrollmentAPIKeyId: string | null; + agentConfigId?: string; + enrollmentAPIKeyId?: string; }>({ - agentConfigId: agentConfigs.length ? agentConfigs[0].id : null, - enrollmentAPIKeyId: null, + agentConfigId: agentConfigs.length ? agentConfigs[0].id : undefined, }); const filteredEnrollmentAPIKeys = React.useMemo(() => { if (!selectedState.agentConfigId || !enrollmentAPIKeysRequest.data) { @@ -99,10 +97,10 @@ export const APIKeySelection: React.FunctionComponent = ({ onKeyChange, a const [showAPIKeyForm, setShowAPIKeyForm] = useState(false); const apiKeyForm = useCreateApiKeyForm(selectedState.agentConfigId, async (keyId: string) => { - const res = await enrollmentAPIKeysRequest.refresh(); + const res = await enrollmentAPIKeysRequest.sendRequest(); setSelectedState({ ...selectedState, - enrollmentAPIKeyId: res.data?.list.find(key => key.id === keyId)?.id ?? null, + enrollmentAPIKeyId: res.data?.list.find(key => key.id === keyId)?.id, }); setShowAPIKeyForm(false); }); @@ -135,7 +133,7 @@ export const APIKeySelection: React.FunctionComponent = ({ onKeyChange, a onChange={e => setSelectedState({ agentConfigId: e.target.value, - enrollmentAPIKeyId: null, + enrollmentAPIKeyId: undefined, }) } /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/confirm_delete_modal.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/confirm_delete_modal.tsx deleted file mode 100644 index 8ce20a85e14b82..00000000000000 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/confirm_delete_modal.tsx +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { EuiOverlayMask, EuiConfirmModal } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; - -export const ConfirmDeleteModal: React.FunctionComponent<{ - onConfirm: () => void; - onCancel: () => void; - apiKeyId: string; -}> = ({ onConfirm, onCancel, apiKeyId }) => { - return ( - - - } - onCancel={onCancel} - onConfirm={onConfirm} - cancelButtonText={ - - } - confirmButtonText={ - - } - buttonColor="danger" - /> - - ); -}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/create_api_key_form.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/create_api_key_form.tsx deleted file mode 100644 index 009080a4da1860..00000000000000 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/create_api_key_form.tsx +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { - EuiFlexGroup, - EuiFlexItem, - EuiFormRow, - EuiFieldText, - EuiButton, - EuiSelect, -} from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { useInput, sendRequest } from '../../../../../hooks'; -import { useConfigs } from './hooks'; -import { enrollmentAPIKeyRouteService } from '../../../../../services'; - -export const CreateApiKeyForm: React.FunctionComponent<{ onChange: () => void }> = ({ - onChange, -}) => { - const { data: configs } = useConfigs(); - const { inputs, onSubmit, submitted } = useCreateApiKey(() => onChange()); - - return ( - - - - - - - - - ({ - value: config.id, - text: config.name, - }))} - /> - - - - - onSubmit()}> - - - - - - ); -}; - -function useCreateApiKey(onSuccess: () => void) { - const [submitted, setSubmitted] = React.useState(false); - const inputs = { - nameInput: useInput(), - configIdInput: useInput('default'), - }; - - const onSubmit = async () => { - setSubmitted(true); - await sendRequest({ - method: 'post', - path: enrollmentAPIKeyRouteService.getCreatePath(), - body: JSON.stringify({ - name: inputs.nameInput.value, - config_id: inputs.configIdInput.value, - }), - }); - setSubmitted(false); - onSuccess(); - }; - - return { - inputs, - onSubmit, - submitted, - }; -} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/hooks.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/hooks.tsx deleted file mode 100644 index 41c6b5912cd319..00000000000000 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/hooks.tsx +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { - Pagination, - useGetAgentConfigs, - useGetEnrollmentAPIKeys, - useGetOneEnrollmentAPIKey, -} from '../../../../../hooks'; - -export function useEnrollmentApiKeys(pagination: Pagination) { - const request = useGetEnrollmentAPIKeys({ - page: pagination.currentPage, - perPage: pagination.pageSize, - }); - - return { - data: request.data, - isLoading: request.isLoading, - refresh: () => request.sendRequest(), - }; -} - -export function useConfigs() { - const request = useGetAgentConfigs(); - - return { - data: request.data ? request.data.items : [], - isLoading: request.isLoading, - }; -} - -export function useEnrollmentApiKey(apiKeyId: string | null) { - const request = useGetOneEnrollmentAPIKey(apiKeyId as string); - - return { - data: request.data, - isLoading: request.isLoading, - }; -} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/index.tsx deleted file mode 100644 index 19957e7827680b..00000000000000 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_list_page/components/enrollment_api_keys/index.tsx +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import React, { useState } from 'react'; -import { EuiBasicTable, EuiButtonEmpty, EuiSpacer, EuiPopover, EuiLink } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { i18n } from '@kbn/i18n'; -import { usePagination, sendRequest } from '../../../../../hooks'; -import { useEnrollmentApiKeys, useEnrollmentApiKey } from './hooks'; -import { ConfirmDeleteModal } from './confirm_delete_modal'; -import { CreateApiKeyForm } from './create_api_key_form'; -import { EnrollmentAPIKey } from '../../../../../types'; -import { useCapabilities } from '../../../../../hooks'; -import { enrollmentAPIKeyRouteService } from '../../../../../services'; -export { useEnrollmentApiKeys, useEnrollmentApiKey } from './hooks'; - -export const EnrollmentApiKeysTable: React.FunctionComponent<{ - onChange: () => void; -}> = ({ onChange }) => { - const [confirmDeleteApiKeyId, setConfirmDeleteApiKeyId] = useState(null); - const { pagination } = usePagination(); - const { data, isLoading, refresh } = useEnrollmentApiKeys(pagination); - - const columns: any[] = [ - { - field: 'name', - name: i18n.translate('xpack.ingestManager.apiKeysList.nameColumnTitle', { - defaultMessage: 'Name', - }), - width: '300px', - }, - { - field: 'config_id', - name: i18n.translate('xpack.ingestManager.apiKeysList.configColumnTitle', { - defaultMessage: 'Config', - }), - width: '100px', - }, - { - field: null, - name: i18n.translate('xpack.ingestManager.apiKeysList.apiKeyColumnTitle', { - defaultMessage: 'API Key', - }), - render: (key: EnrollmentAPIKey) => , - }, - { - field: null, - width: '50px', - render: (key: EnrollmentAPIKey) => { - return ( - setConfirmDeleteApiKeyId(key.id)} iconType={'trash'} /> - ); - }, - }, - ]; - - return ( - <> - {confirmDeleteApiKeyId && ( - setConfirmDeleteApiKeyId(null)} - onConfirm={async () => { - await sendRequest({ - method: 'delete', - path: enrollmentAPIKeyRouteService.getDeletePath(confirmDeleteApiKeyId), - }); - setConfirmDeleteApiKeyId(null); - refresh(); - }} - /> - )} - - } - items={data ? data.list : []} - itemId="id" - columns={columns} - /> - - { - refresh(); - onChange(); - }} - /> - - ); -}; - -export const CreateApiKeyButton: React.FunctionComponent<{ onChange: () => void }> = ({ - onChange, -}) => { - const hasWriteCapabilites = useCapabilities().write; - const [isOpen, setIsOpen] = React.useState(false); - - return ( - setIsOpen(true)} color="primary"> - - - } - isOpen={isOpen} - closePopover={() => setIsOpen(false)} - > - { - setIsOpen(false); - onChange(); - }} - /> - - ); - return <>; -}; - -const ApiKeyField: React.FunctionComponent<{ apiKeyId: string }> = ({ apiKeyId }) => { - const [visible, setVisible] = useState(false); - const { data } = useEnrollmentApiKey(apiKeyId); - - return ( - <> - {visible && data ? data.item.api_key : '••••••••••••••••••••••••••••'} - setVisible(!visible)}> - {visible ? ( - - ) : ( - - )} - {' '} - - ); -}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx index 11a049047b7877..692c60cdce38c1 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx @@ -45,7 +45,7 @@ export const AgentReassignConfigFlyout: React.FunctionComponent = ({ onCl const agentConfigsRequest = useGetAgentConfigs(); const agentConfigs = agentConfigsRequest.data ? agentConfigsRequest.data.items : []; - const agentConfigRequest = useGetOneAgentConfig(selectedAgentConfigId as string); + const agentConfigRequest = useGetOneAgentConfig(selectedAgentConfigId); const agentConfig = agentConfigRequest.data ? agentConfigRequest.data.item : null; const [isSubmitting, setIsSubmitting] = useState(false); diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index d48e65fabb8d35..cdff34ec3a6039 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -8305,13 +8305,6 @@ "xpack.ingestManager.agentListStatus.offlineLabel": "オフライン", "xpack.ingestManager.agentListStatus.onlineLabel": "オンライン", "xpack.ingestManager.agentListStatus.totalLabel": "エージェント", - "xpack.ingestManager.apiKeysForm.configLabel": "構成", - "xpack.ingestManager.apiKeysForm.nameLabel": "キー名", - "xpack.ingestManager.apiKeysForm.saveButton": "保存", - "xpack.ingestManager.apiKeysList.apiKeyColumnTitle": "API キー", - "xpack.ingestManager.apiKeysList.configColumnTitle": "構成", - "xpack.ingestManager.apiKeysList.emptyEnrollmentKeysMessage": "API キーがありません", - "xpack.ingestManager.apiKeysList.nameColumnTitle": "名前", "xpack.ingestManager.appNavigation.configurationsLinkText": "構成", "xpack.ingestManager.appNavigation.fleetLinkText": "フリート", "xpack.ingestManager.appNavigation.overviewLinkText": "概要", @@ -8390,8 +8383,6 @@ "xpack.ingestManager.deleteAgentConfigs.successMultipleNotificationTitle": "{count} 件のエージェント構成を削除しました", "xpack.ingestManager.deleteAgentConfigs.successSingleNotificationTitle": "エージェント構成「{id}」を削除しました", "xpack.ingestManager.deleteApiKeys.confirmModal.cancelButtonLabel": "キャンセル", - "xpack.ingestManager.deleteApiKeys.confirmModal.confirmButtonLabel": "削除", - "xpack.ingestManager.deleteApiKeys.confirmModal.title": "API キーを削除: {apiKeyId}", "xpack.ingestManager.deleteDatasource.confirmModal.affectedAgentsMessage": "{agentConfigName} が一部のエージェントで既に使用されていることをフリートが検出しました。", "xpack.ingestManager.deleteDatasource.confirmModal.affectedAgentsTitle": "このアクションは {agentsCount} {agentsCount, plural, one {# エージェント} other {# エージェント}}に影響します", "xpack.ingestManager.deleteDatasource.confirmModal.cancelButtonLabel": "キャンセル", @@ -8414,9 +8405,7 @@ "xpack.ingestManager.editConfig.successNotificationTitle": "エージェント構成「{name}」を更新しました", "xpack.ingestManager.enrollmentApiKeyForm.namePlaceholder": "名前を選択", "xpack.ingestManager.enrollmentApiKeyList.createNewButton": "新規キーを作成", - "xpack.ingestManager.enrollmentApiKeyList.hideTableButton": "を非表示", "xpack.ingestManager.enrollmentApiKeyList.useExistingsButton": "既存のキーを使用", - "xpack.ingestManager.enrollmentApiKeyList.viewTableButton": "表示", "xpack.ingestManager.epm.addDatasourceButtonText": "データソースを作成", "xpack.ingestManager.epm.pageSubtitle": "人気のアプリやサービスのパッケージを参照する", "xpack.ingestManager.epm.pageTitle": "Elastic Package Manager", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 196c8183e0cc11..819112feb9f572 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -8308,13 +8308,6 @@ "xpack.ingestManager.agentListStatus.offlineLabel": "脱机", "xpack.ingestManager.agentListStatus.onlineLabel": "联机", "xpack.ingestManager.agentListStatus.totalLabel": "代理", - "xpack.ingestManager.apiKeysForm.configLabel": "配置", - "xpack.ingestManager.apiKeysForm.nameLabel": "密钥名称", - "xpack.ingestManager.apiKeysForm.saveButton": "保存", - "xpack.ingestManager.apiKeysList.apiKeyColumnTitle": "API 密钥", - "xpack.ingestManager.apiKeysList.configColumnTitle": "配置", - "xpack.ingestManager.apiKeysList.emptyEnrollmentKeysMessage": "无 API 密钥", - "xpack.ingestManager.apiKeysList.nameColumnTitle": "名称", "xpack.ingestManager.appNavigation.configurationsLinkText": "配置", "xpack.ingestManager.appNavigation.fleetLinkText": "Fleet", "xpack.ingestManager.appNavigation.overviewLinkText": "概览", @@ -8393,8 +8386,6 @@ "xpack.ingestManager.deleteAgentConfigs.successMultipleNotificationTitle": "已删除 {count} 个代理配置", "xpack.ingestManager.deleteAgentConfigs.successSingleNotificationTitle": "已删除代理配置“{id}”", "xpack.ingestManager.deleteApiKeys.confirmModal.cancelButtonLabel": "取消", - "xpack.ingestManager.deleteApiKeys.confirmModal.confirmButtonLabel": "删除", - "xpack.ingestManager.deleteApiKeys.confirmModal.title": "删除 api 密钥:{apiKeyId}", "xpack.ingestManager.deleteDatasource.confirmModal.affectedAgentsMessage": "Fleet 已检测到 {agentConfigName} 已由您的部分代理使用。", "xpack.ingestManager.deleteDatasource.confirmModal.affectedAgentsTitle": "此操作将影响 {agentsCount} 个 {agentsCount, plural, one {代理} other {代理}}。", "xpack.ingestManager.deleteDatasource.confirmModal.cancelButtonLabel": "取消", @@ -8417,9 +8408,7 @@ "xpack.ingestManager.editConfig.successNotificationTitle": "代理配置“{name}”已更新", "xpack.ingestManager.enrollmentApiKeyForm.namePlaceholder": "选择名称", "xpack.ingestManager.enrollmentApiKeyList.createNewButton": "创建新密钥", - "xpack.ingestManager.enrollmentApiKeyList.hideTableButton": "隐藏", "xpack.ingestManager.enrollmentApiKeyList.useExistingsButton": "使用现有密钥", - "xpack.ingestManager.enrollmentApiKeyList.viewTableButton": "查看", "xpack.ingestManager.epm.addDatasourceButtonText": "创建数据源", "xpack.ingestManager.epm.pageSubtitle": "浏览热门应用和服务的软件。", "xpack.ingestManager.epm.pageTitle": "Elastic Package Manager", From d5c1812d006d0a530f6ca5fd0a4b7129530e112f Mon Sep 17 00:00:00 2001 From: Shahzad Date: Tue, 28 Apr 2020 19:48:34 +0200 Subject: [PATCH 11/12] [Uptime] Update uptime ml job id to limit to 64 char (#64394) --- .../state/api/__tests__/ml_anomaly.test.ts | 34 +++++++++++++++++++ .../uptime/public/state/api/ml_anomaly.ts | 27 +++++++++++---- 2 files changed, 55 insertions(+), 6 deletions(-) create mode 100644 x-pack/legacy/plugins/uptime/public/state/api/__tests__/ml_anomaly.test.ts diff --git a/x-pack/legacy/plugins/uptime/public/state/api/__tests__/ml_anomaly.test.ts b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/ml_anomaly.test.ts new file mode 100644 index 00000000000000..838e5b8246b4b5 --- /dev/null +++ b/x-pack/legacy/plugins/uptime/public/state/api/__tests__/ml_anomaly.test.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getMLJobId } from '../ml_anomaly'; + +describe('ML Anomaly API', () => { + it('it generates a lowercase job id', async () => { + const monitorId = 'ABC1334haa'; + + const jobId = getMLJobId(monitorId); + + expect(jobId).toEqual(jobId.toLowerCase()); + }); + + it('should truncate long monitor IDs', () => { + const longAndWeirdMonitorId = + 'https://auto-mmmmxhhhhhccclongAndWeirdMonitorId123yyyyyrereauto-xcmpa-1345555454646'; + + expect(getMLJobId(longAndWeirdMonitorId)).toHaveLength(64); + }); + + it('should remove special characters and replace them with underscore', () => { + const monIdSpecialChars = '/ ? , " < > | * a'; + + const jobId = getMLJobId(monIdSpecialChars); + + const format = /[/?,"<>|*]+/; + + expect(format.test(jobId)).toBe(false); + }); +}); diff --git a/x-pack/legacy/plugins/uptime/public/state/api/ml_anomaly.ts b/x-pack/legacy/plugins/uptime/public/state/api/ml_anomaly.ts index 16b90e99214284..ca324895c26dbd 100644 --- a/x-pack/legacy/plugins/uptime/public/state/api/ml_anomaly.ts +++ b/x-pack/legacy/plugins/uptime/public/state/api/ml_anomaly.ts @@ -18,7 +18,25 @@ import { import { DataRecognizerConfigResponse } from '../../../../../../plugins/ml/common/types/modules'; import { JobExistResult } from '../../../../../../plugins/ml/common/types/data_recognizer'; -export const getMLJobId = (monitorId: string) => `${monitorId}_${ML_JOB_ID}`.toLowerCase(); +const getJobPrefix = (monitorId: string) => { + // ML App doesn't support upper case characters in job name + // Also Spaces and the characters / ? , " < > | * are not allowed + // so we will replace all special chars with _ + + const prefix = monitorId.replace(/[^A-Z0-9]+/gi, '_').toLowerCase(); + + // ML Job ID can't be greater than 64 length, so will be substring it, and hope + // At such big length, there is minimum chance of having duplicate monitor id + // Subtracting ML_JOB_ID constant as well + const postfix = '_' + ML_JOB_ID; + + if ((prefix + postfix).length > 64) { + return prefix.substring(0, 64 - postfix.length) + '_'; + } + return prefix + '_'; +}; + +export const getMLJobId = (monitorId: string) => `${getJobPrefix(monitorId)}${ML_JOB_ID}`; export const getMLCapabilities = async (): Promise => { return await apiService.get(API_URLS.ML_CAPABILITIES); @@ -34,11 +52,8 @@ export const createMLJob = async ({ }: MonitorIdParam & HeartbeatIndicesParam): Promise => { const url = API_URLS.ML_SETUP_MODULE + ML_MODULE_ID; - // ML App doesn't support upper case characters in job name - const lowerCaseMonitorId = monitorId.toLowerCase(); - const data = { - prefix: `${lowerCaseMonitorId}_`, + prefix: `${getJobPrefix(monitorId)}`, useDedicatedIndex: false, startDatafeed: true, start: moment() @@ -48,7 +63,7 @@ export const createMLJob = async ({ query: { bool: { filter: [ - { term: { 'monitor.id': lowerCaseMonitorId } }, + { term: { 'monitor.id': monitorId } }, { range: { 'monitor.duration.us': { gt: 0 } } }, ], }, From dfb4c331a0242c80a10572f3db69ed06f982de46 Mon Sep 17 00:00:00 2001 From: Josh Dover Date: Tue, 28 Apr 2020 11:54:25 -0600 Subject: [PATCH 12/12] Use short URLs for legacy plugin deprecation warning (#64540) --- .../legacy/plugins/log_legacy_plugins_warning.test.ts | 4 ++-- .../server/legacy/plugins/log_legacy_plugins_warning.ts | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/core/server/legacy/plugins/log_legacy_plugins_warning.test.ts b/src/core/server/legacy/plugins/log_legacy_plugins_warning.test.ts index 1790b096a71aea..dfa2396d5904bc 100644 --- a/src/core/server/legacy/plugins/log_legacy_plugins_warning.test.ts +++ b/src/core/server/legacy/plugins/log_legacy_plugins_warning.test.ts @@ -48,7 +48,7 @@ describe('logLegacyThirdPartyPluginDeprecationWarning', () => { expect(log.warn).toHaveBeenCalledTimes(1); expect(log.warn.mock.calls[0]).toMatchInlineSnapshot(` Array [ - "Some installed third party plugin(s) [plugin] are using the legacy plugin format and will no longer work in a future Kibana release. Please refer to https://www.elastic.co/guide/en/kibana/master/breaking-changes-8.0.html for a list of breaking changes and https://github.com/elastic/kibana/blob/master/src/core/MIGRATION.md for documentation on how to migrate legacy plugins.", + "Some installed third party plugin(s) [plugin] are using the legacy plugin format and will no longer work in a future Kibana release. Please refer to https://ela.st/kibana-breaking-changes-8-0 for a list of breaking changes and https://ela.st/kibana-platform-migration for documentation on how to migrate legacy plugins.", ] `); }); @@ -65,7 +65,7 @@ describe('logLegacyThirdPartyPluginDeprecationWarning', () => { expect(log.warn).toHaveBeenCalledTimes(1); expect(log.warn.mock.calls[0]).toMatchInlineSnapshot(` Array [ - "Some installed third party plugin(s) [pluginA, pluginB, pluginC] are using the legacy plugin format and will no longer work in a future Kibana release. Please refer to https://www.elastic.co/guide/en/kibana/master/breaking-changes-8.0.html for a list of breaking changes and https://github.com/elastic/kibana/blob/master/src/core/MIGRATION.md for documentation on how to migrate legacy plugins.", + "Some installed third party plugin(s) [pluginA, pluginB, pluginC] are using the legacy plugin format and will no longer work in a future Kibana release. Please refer to https://ela.st/kibana-breaking-changes-8-0 for a list of breaking changes and https://ela.st/kibana-platform-migration for documentation on how to migrate legacy plugins.", ] `); }); diff --git a/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts b/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts index f9c3dcbf554cb8..df86f5a2b40317 100644 --- a/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts +++ b/src/core/server/legacy/plugins/log_legacy_plugins_warning.ts @@ -22,9 +22,10 @@ import { LegacyPluginSpec } from '../types'; const internalPaths = ['/src/legacy/core_plugins', '/x-pack']; -const breakingChangesUrl = - 'https://www.elastic.co/guide/en/kibana/master/breaking-changes-8.0.html'; -const migrationGuideUrl = 'https://github.com/elastic/kibana/blob/master/src/core/MIGRATION.md'; +// Use shortened URLs so destinations can be updated if/when documentation moves +// All platform team members have access to edit these +const breakingChangesUrl = 'https://ela.st/kibana-breaking-changes-8-0'; +const migrationGuideUrl = 'https://ela.st/kibana-platform-migration'; export const logLegacyThirdPartyPluginDeprecationWarning = ({ specs,